mpcio.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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, int num_threads) :
  375. thread_num(thread_num), local_cpu_nthreads(num_threads),
  376. communication_nthreads(num_threads),
  377. thread_lamport(mpcio.lamport), mpcio(mpcio)
  378. #ifdef VERBOSE_COMMS
  379. , round_num(0)
  380. #endif
  381. {
  382. if (mpcio.player < 2) {
  383. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  384. peer_iostream.emplace(mpcpio.peerios[thread_num],
  385. thread_lamport, mpcpio.msgs_sent[thread_num],
  386. mpcpio.msg_bytes_sent[thread_num]);
  387. server_iostream.emplace(mpcpio.serverios[thread_num],
  388. thread_lamport, mpcpio.msgs_sent[thread_num],
  389. mpcpio.msg_bytes_sent[thread_num]);
  390. } else {
  391. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  392. p0_iostream.emplace(mpcsrvio.p0ios[thread_num],
  393. thread_lamport, mpcsrvio.msgs_sent[thread_num],
  394. mpcsrvio.msg_bytes_sent[thread_num]);
  395. p1_iostream.emplace(mpcsrvio.p1ios[thread_num],
  396. thread_lamport, mpcsrvio.msgs_sent[thread_num],
  397. mpcsrvio.msg_bytes_sent[thread_num]);
  398. }
  399. }
  400. // Sync our per-thread lamport clock with the master one in the
  401. // mpcio. You only need to call this explicitly if your MPCTIO
  402. // outlives your thread (in which case call it after the join), or
  403. // if your threads do interthread communication amongst themselves
  404. // (in which case call it in the sending thread before the send, and
  405. // call it in the receiving thread after the receive).
  406. void MPCTIO::sync_lamport()
  407. {
  408. // Update the mpcio Lamport time to be max of the thread Lamport
  409. // time and what we thought it was before. We use this
  410. // compare_exchange construction in order to atomically
  411. // do the comparison, computation, and replacement
  412. lamport_t old_lamport = mpcio.lamport;
  413. lamport_t new_lamport = thread_lamport;
  414. do {
  415. if (new_lamport < old_lamport) {
  416. new_lamport = old_lamport;
  417. }
  418. // The next line atomically checks if lamport still has
  419. // the value old_lamport; if so, it changes its value to
  420. // new_lamport and returns true (ending the loop). If
  421. // not, it sets old_lamport to the current value of
  422. // lamport, and returns false (continuing the loop so
  423. // that new_lamport can be recomputed based on this new
  424. // value).
  425. } while (!mpcio.lamport.compare_exchange_weak(
  426. old_lamport, new_lamport));
  427. thread_lamport = new_lamport;
  428. }
  429. // Queue up data to the peer or to the server
  430. void MPCTIO::queue_peer(const void *data, size_t len)
  431. {
  432. if (mpcio.player < 2) {
  433. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  434. size_t newmsg = mpcpio.peerios[thread_num].queue(data, len, thread_lamport);
  435. mpcpio.msgs_sent[thread_num] += newmsg;
  436. mpcpio.msg_bytes_sent[thread_num] += len;
  437. }
  438. }
  439. void MPCTIO::queue_server(const void *data, size_t len)
  440. {
  441. if (mpcio.player < 2) {
  442. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  443. size_t newmsg = mpcpio.serverios[thread_num].queue(data, len, thread_lamport);
  444. mpcpio.msgs_sent[thread_num] += newmsg;
  445. mpcpio.msg_bytes_sent[thread_num] += len;
  446. }
  447. }
  448. // Receive data from the peer or to the server
  449. size_t MPCTIO::recv_peer(void *data, size_t len)
  450. {
  451. if (mpcio.player < 2) {
  452. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  453. return mpcpio.peerios[thread_num].recv(data, len, thread_lamport);
  454. }
  455. return 0;
  456. }
  457. size_t MPCTIO::recv_server(void *data, size_t len)
  458. {
  459. if (mpcio.player < 2) {
  460. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  461. return mpcpio.serverios[thread_num].recv(data, len, thread_lamport);
  462. }
  463. return 0;
  464. }
  465. // Queue up data to p0 or p1
  466. void MPCTIO::queue_p0(const void *data, size_t len)
  467. {
  468. if (mpcio.player == 2) {
  469. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  470. size_t newmsg = mpcsrvio.p0ios[thread_num].queue(data, len, thread_lamport);
  471. mpcsrvio.msgs_sent[thread_num] += newmsg;
  472. mpcsrvio.msg_bytes_sent[thread_num] += len;
  473. }
  474. }
  475. void MPCTIO::queue_p1(const void *data, size_t len)
  476. {
  477. if (mpcio.player == 2) {
  478. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  479. size_t newmsg = mpcsrvio.p1ios[thread_num].queue(data, len, thread_lamport);
  480. mpcsrvio.msgs_sent[thread_num] += newmsg;
  481. mpcsrvio.msg_bytes_sent[thread_num] += len;
  482. }
  483. }
  484. // Receive data from p0 or p1
  485. size_t MPCTIO::recv_p0(void *data, size_t len)
  486. {
  487. if (mpcio.player == 2) {
  488. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  489. return mpcsrvio.p0ios[thread_num].recv(data, len, thread_lamport);
  490. }
  491. return 0;
  492. }
  493. size_t MPCTIO::recv_p1(void *data, size_t len)
  494. {
  495. if (mpcio.player == 2) {
  496. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  497. return mpcsrvio.p1ios[thread_num].recv(data, len, thread_lamport);
  498. }
  499. return 0;
  500. }
  501. // Send all queued data for this thread
  502. void MPCTIO::send()
  503. {
  504. #ifdef VERBOSE_COMMS
  505. printf("Thread %u sending round %lu\n", thread_num, ++round_num);
  506. #endif
  507. if (mpcio.player < 2) {
  508. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  509. mpcpio.peerios[thread_num].send();
  510. mpcpio.serverios[thread_num].send();
  511. } else {
  512. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  513. mpcsrvio.p0ios[thread_num].send();
  514. mpcsrvio.p1ios[thread_num].send();
  515. }
  516. }
  517. // Functions to get precomputed values. If we're in the online
  518. // phase, get them from PreCompStorage. If we're in the
  519. // preprocessing or online-only phase, read them from the server.
  520. MultTriple MPCTIO::triple(yield_t &yield)
  521. {
  522. MultTriple val;
  523. if (mpcio.player < 2) {
  524. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  525. if (mpcpio.mode != MODE_ONLINE) {
  526. yield();
  527. recv_server(&val, sizeof(val));
  528. mpcpio.triples[thread_num].inc();
  529. } else {
  530. mpcpio.triples[thread_num].get(val);
  531. }
  532. } else if (mpcio.mode != MODE_ONLINE) {
  533. // Create triples (X0,Y0,Z0),(X1,Y1,Z1) such that
  534. // (X0*Y1 + Y0*X1) = (Z0+Z1)
  535. value_t X0, Y0, Z0, X1, Y1, Z1;
  536. arc4random_buf(&X0, sizeof(X0));
  537. arc4random_buf(&Y0, sizeof(Y0));
  538. arc4random_buf(&Z0, sizeof(Z0));
  539. arc4random_buf(&X1, sizeof(X1));
  540. arc4random_buf(&Y1, sizeof(Y1));
  541. Z1 = X0 * Y1 + X1 * Y0 - Z0;
  542. MultTriple T0, T1;
  543. T0 = std::make_tuple(X0, Y0, Z0);
  544. T1 = std::make_tuple(X1, Y1, Z1);
  545. queue_p0(&T0, sizeof(T0));
  546. queue_p1(&T1, sizeof(T1));
  547. yield();
  548. }
  549. return val;
  550. }
  551. HalfTriple MPCTIO::halftriple(yield_t &yield)
  552. {
  553. HalfTriple val;
  554. if (mpcio.player < 2) {
  555. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  556. if (mpcpio.mode != MODE_ONLINE) {
  557. yield();
  558. recv_server(&val, sizeof(val));
  559. mpcpio.halftriples[thread_num].inc();
  560. } else {
  561. mpcpio.halftriples[thread_num].get(val);
  562. }
  563. } else if (mpcio.mode != MODE_ONLINE) {
  564. // Create half-triples (X0,Z0),(Y1,Z1) such that
  565. // X0*Y1 = Z0 + Z1
  566. value_t X0, Z0, Y1, Z1;
  567. arc4random_buf(&X0, sizeof(X0));
  568. arc4random_buf(&Z0, sizeof(Z0));
  569. arc4random_buf(&Y1, sizeof(Y1));
  570. Z1 = X0 * Y1 - Z0;
  571. HalfTriple H0, H1;
  572. H0 = std::make_tuple(X0, Z0);
  573. H1 = std::make_tuple(Y1, Z1);
  574. queue_p0(&H0, sizeof(H0));
  575. queue_p1(&H1, sizeof(H1));
  576. yield();
  577. }
  578. return val;
  579. }
  580. SelectTriple MPCTIO::selecttriple(yield_t &yield)
  581. {
  582. SelectTriple val;
  583. if (mpcio.player < 2) {
  584. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  585. if (mpcpio.mode != MODE_ONLINE) {
  586. uint8_t Xbyte;
  587. yield();
  588. recv_server(&Xbyte, sizeof(Xbyte));
  589. val.X = Xbyte & 1;
  590. recv_server(&val.Y, sizeof(val.Y));
  591. recv_server(&val.Z, sizeof(val.Z));
  592. } else {
  593. std::cerr << "Attempted to read SelectTriple in online phase\n";
  594. }
  595. } else if (mpcio.mode != MODE_ONLINE) {
  596. // Create triples (X0,Y0,Z0),(X1,Y1,Z1) such that
  597. // (X0*Y1 ^ Y0*X1) = (Z0^Z1)
  598. bit_t X0, X1;
  599. DPFnode Y0, Z0, Y1, Z1;
  600. X0 = arc4random() & 1;
  601. arc4random_buf(&Y0, sizeof(Y0));
  602. arc4random_buf(&Z0, sizeof(Z0));
  603. X1 = arc4random() & 1;
  604. arc4random_buf(&Y1, sizeof(Y1));
  605. DPFnode X0ext, X1ext;
  606. // Sign-extend X0 and X1 (so that 0 -> 0000...0 and
  607. // 1 -> 1111...1)
  608. X0ext = if128_mask[X0];
  609. X1ext = if128_mask[X1];
  610. Z1 = ((X0ext & Y1) ^ (X1ext & Y0)) ^ Z0;
  611. queue_p0(&X0, sizeof(X0));
  612. queue_p0(&Y0, sizeof(Y0));
  613. queue_p0(&Z0, sizeof(Z0));
  614. queue_p1(&X1, sizeof(X1));
  615. queue_p1(&Y1, sizeof(Y1));
  616. queue_p1(&Z1, sizeof(Z1));
  617. yield();
  618. }
  619. return val;
  620. }
  621. // Only computational peers call this; the server should be calling
  622. // rdpfpair() at the same time
  623. RDPFTriple MPCTIO::rdpftriple(yield_t &yield, nbits_t depth,
  624. bool keep_expansion)
  625. {
  626. assert(mpcio.player < 2);
  627. RDPFTriple val;
  628. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  629. if (mpcio.mode == MODE_ONLINE) {
  630. mpcpio.rdpftriples[thread_num][depth-1].get(val);
  631. } else {
  632. val = RDPFTriple(*this, yield, depth,
  633. keep_expansion);
  634. iostream_server() <<
  635. val.dpf[(mpcio.player == 0) ? 1 : 2];
  636. mpcpio.rdpftriples[thread_num][depth-1].inc();
  637. yield();
  638. }
  639. return val;
  640. }
  641. // Only the server calls this; the computational peers should be calling
  642. // rdpftriple() at the same time
  643. RDPFPair MPCTIO::rdpfpair(yield_t &yield, nbits_t depth)
  644. {
  645. assert(mpcio.player == 2);
  646. RDPFPair val;
  647. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  648. if (mpcio.mode == MODE_ONLINE) {
  649. mpcsrvio.rdpfpairs[thread_num][depth-1].get(val);
  650. } else {
  651. RDPFTriple trip(*this, yield, depth, true);
  652. yield();
  653. iostream_p0() >> val.dpf[0];
  654. iostream_p1() >> val.dpf[1];
  655. mpcsrvio.rdpfpairs[thread_num][depth-1].inc();
  656. }
  657. return val;
  658. }
  659. CDPF MPCTIO::cdpf(yield_t &yield)
  660. {
  661. CDPF val;
  662. if (mpcio.player < 2) {
  663. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  664. if (mpcpio.mode != MODE_ONLINE) {
  665. yield();
  666. iostream_server() >> val;
  667. mpcpio.cdpfs[thread_num].inc();
  668. } else {
  669. mpcpio.cdpfs[thread_num].get(val);
  670. }
  671. } else if (mpcio.mode != MODE_ONLINE) {
  672. auto [ cdpf0, cdpf1 ] = CDPF::generate(aes_ops());
  673. iostream_p0() << cdpf0;
  674. iostream_p1() << cdpf1;
  675. yield();
  676. }
  677. return val;
  678. }
  679. // The port number for the P1 -> P0 connection
  680. static const unsigned short port_p1_p0 = 2115;
  681. // The port number for the P2 -> P0 connection
  682. static const unsigned short port_p2_p0 = 2116;
  683. // The port number for the P2 -> P1 connection
  684. static const unsigned short port_p2_p1 = 2117;
  685. void mpcio_setup_computational(unsigned player,
  686. boost::asio::io_context &io_context,
  687. const char *p0addr, // can be NULL when player=0
  688. int num_threads,
  689. std::deque<tcp::socket> &peersocks,
  690. std::deque<tcp::socket> &serversocks)
  691. {
  692. if (player == 0) {
  693. // Listen for connections from P1 and from P2
  694. tcp::acceptor acceptor_p1(io_context,
  695. tcp::endpoint(tcp::v4(), port_p1_p0));
  696. tcp::acceptor acceptor_p2(io_context,
  697. tcp::endpoint(tcp::v4(), port_p2_p0));
  698. peersocks.clear();
  699. serversocks.clear();
  700. for (int i=0;i<num_threads;++i) {
  701. peersocks.emplace_back(io_context);
  702. serversocks.emplace_back(io_context);
  703. }
  704. for (int i=0;i<num_threads;++i) {
  705. tcp::socket peersock = acceptor_p1.accept();
  706. // Read 2 bytes from the socket, which will be the thread
  707. // number
  708. unsigned short thread_num;
  709. boost::asio::read(peersock,
  710. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  711. if (thread_num >= num_threads) {
  712. std::cerr << "Received bad thread number from peer\n";
  713. } else {
  714. peersocks[thread_num] = std::move(peersock);
  715. }
  716. }
  717. for (int i=0;i<num_threads;++i) {
  718. tcp::socket serversock = acceptor_p2.accept();
  719. // Read 2 bytes from the socket, which will be the thread
  720. // number
  721. unsigned short thread_num;
  722. boost::asio::read(serversock,
  723. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  724. if (thread_num >= num_threads) {
  725. std::cerr << "Received bad thread number from server\n";
  726. } else {
  727. serversocks[thread_num] = std::move(serversock);
  728. }
  729. }
  730. } else if (player == 1) {
  731. // Listen for connections from P2, make num_threads connections to P0
  732. tcp::acceptor acceptor_p2(io_context,
  733. tcp::endpoint(tcp::v4(), port_p2_p1));
  734. tcp::resolver resolver(io_context);
  735. boost::system::error_code err;
  736. peersocks.clear();
  737. serversocks.clear();
  738. for (int i=0;i<num_threads;++i) {
  739. serversocks.emplace_back(io_context);
  740. }
  741. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  742. tcp::socket peersock(io_context);
  743. while(1) {
  744. boost::asio::connect(peersock,
  745. resolver.resolve(p0addr, std::to_string(port_p1_p0)), err);
  746. if (!err) break;
  747. std::cerr << "Connection to p0 refused, will retry.\n";
  748. sleep(1);
  749. }
  750. // Write 2 bytes to the socket indicating which thread
  751. // number this socket is for
  752. boost::asio::write(peersock,
  753. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  754. peersocks.push_back(std::move(peersock));
  755. }
  756. for (int i=0;i<num_threads;++i) {
  757. tcp::socket serversock = acceptor_p2.accept();
  758. // Read 2 bytes from the socket, which will be the thread
  759. // number
  760. unsigned short thread_num;
  761. boost::asio::read(serversock,
  762. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  763. if (thread_num >= num_threads) {
  764. std::cerr << "Received bad thread number from server\n";
  765. } else {
  766. serversocks[thread_num] = std::move(serversock);
  767. }
  768. }
  769. } else {
  770. std::cerr << "Invalid player number passed to mpcio_setup_computational\n";
  771. }
  772. }
  773. void mpcio_setup_server(boost::asio::io_context &io_context,
  774. const char *p0addr, const char *p1addr, int num_threads,
  775. std::deque<tcp::socket> &p0socks,
  776. std::deque<tcp::socket> &p1socks)
  777. {
  778. // Make connections to P0 and P1
  779. tcp::resolver resolver(io_context);
  780. boost::system::error_code err;
  781. p0socks.clear();
  782. p1socks.clear();
  783. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  784. tcp::socket p0sock(io_context);
  785. while(1) {
  786. boost::asio::connect(p0sock,
  787. resolver.resolve(p0addr, std::to_string(port_p2_p0)), err);
  788. if (!err) break;
  789. std::cerr << "Connection to p0 refused, will retry.\n";
  790. sleep(1);
  791. }
  792. // Write 2 bytes to the socket indicating which thread
  793. // number this socket is for
  794. boost::asio::write(p0sock,
  795. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  796. p0socks.push_back(std::move(p0sock));
  797. }
  798. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  799. tcp::socket p1sock(io_context);
  800. while(1) {
  801. boost::asio::connect(p1sock,
  802. resolver.resolve(p1addr, std::to_string(port_p2_p1)), err);
  803. if (!err) break;
  804. std::cerr << "Connection to p1 refused, will retry.\n";
  805. sleep(1);
  806. }
  807. // Write 2 bytes to the socket indicating which thread
  808. // number this socket is for
  809. boost::asio::write(p1sock,
  810. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  811. p1socks.push_back(std::move(p1sock));
  812. }
  813. }