mpcio.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #ifndef __MCPIO_HPP__
  2. #define __MCPIO_HPP__
  3. #include <iostream>
  4. #include <fstream>
  5. #include <vector>
  6. #include <array>
  7. #include <deque>
  8. #include <queue>
  9. #include <string>
  10. #include <atomic>
  11. #include <optional>
  12. #include <bsd/stdlib.h> // arc4random_buf
  13. #include <boost/asio.hpp>
  14. #include <boost/thread.hpp>
  15. #include <boost/chrono.hpp>
  16. #include "types.hpp"
  17. #include "corotypes.hpp"
  18. using boost::asio::ip::tcp;
  19. // Classes to represent stored precomputed data (e.g., multiplication triples)
  20. template<typename T, typename N>
  21. class PreCompStorage {
  22. public:
  23. PreCompStorage() : name(N::name), depth(0), count(0) {}
  24. PreCompStorage(unsigned player, ProcessingMode mode,
  25. const char *filenameprefix, unsigned thread_num);
  26. void init(unsigned player, ProcessingMode mode,
  27. const char *filenameprefix, unsigned thread_num, nbits_t depth = 0);
  28. void get(T& nextval);
  29. inline void inc() { ++count; }
  30. inline size_t get_stats() { return count; }
  31. inline void reset_stats() { count = 0; }
  32. private:
  33. std::ifstream storage;
  34. std::string name;
  35. nbits_t depth;
  36. size_t count;
  37. };
  38. // If we want to send Lamport clocks in messages, define this. It adds
  39. // an 8-byte header to each message (length and Lamport clock), so it
  40. // has a small network cost. We always define and pass the Lamport
  41. // clock member of MPCIO to the IO functions for simplicity, but they're
  42. // ignored if this isn't defined
  43. #define SEND_LAMPORT_CLOCKS
  44. using lamport_t = uint32_t;
  45. using atomic_lamport_t = std::atomic<lamport_t>;
  46. using opt_lamport_t = std::optional<lamport_t>;
  47. #ifdef SEND_LAMPORT_CLOCKS
  48. struct MessageWithHeader {
  49. std::string header;
  50. std::string message;
  51. MessageWithHeader(std::string &&msg, lamport_t lamport) :
  52. message(std::move(msg)) {
  53. char hdr[sizeof(uint32_t) + sizeof(lamport_t)];
  54. uint32_t msglen = uint32_t(message.size());
  55. memmove(hdr, &msglen, sizeof(msglen));
  56. memmove(hdr+sizeof(msglen), &lamport, sizeof(lamport));
  57. header.assign(hdr, sizeof(hdr));
  58. }
  59. };
  60. #endif
  61. // A class to wrap a socket to another MPC party. This wrapping allows
  62. // us to do some useful logging, and perform async_writes transparently
  63. // to the application.
  64. class MPCSingleIO {
  65. tcp::socket sock;
  66. size_t totread, totwritten;
  67. std::string dest;
  68. int thread_num;
  69. #ifdef RECORD_IOTRACE
  70. std::vector<ssize_t> iotrace;
  71. #endif
  72. // To avoid blocking if both we and our peer are trying to send
  73. // something very large, and neither side is receiving, we will send
  74. // with async_write. But this has a number of implications:
  75. // - The data to be sent has to be copied into this MPCSingleIO,
  76. // since asio::buffer pointers are not guaranteed to remain valid
  77. // after the end of the coroutine that created them
  78. // - We have to keep a queue of messages to be sent, in case
  79. // coroutines call send() before the previous message has finished
  80. // being sent
  81. // - This queue may be accessed from the async_write thread as well
  82. // as the work thread that uses this MPCSingleIO directly (there
  83. // should be only one of the latter), so we need some locking
  84. // This is where we accumulate data passed in queue()
  85. std::string dataqueue;
  86. // When send() is called, the above dataqueue is appended to this
  87. // messagequeue, and the dataqueue is reset. If messagequeue was
  88. // empty before this append, launch async_write to write the first
  89. // thing in the messagequeue. When async_write completes, it will
  90. // delete the first thing in the messagequeue, and see if there are
  91. // any more elements. If so, it will start another async_write.
  92. // The invariant is that there is an async_write currently running
  93. // iff messagequeue is nonempty.
  94. #ifdef SEND_LAMPORT_CLOCKS
  95. std::queue<MessageWithHeader> messagequeue;
  96. #else
  97. std::queue<std::string> messagequeue;
  98. #endif
  99. // If a single message is broken into chunks in order to get the
  100. // first part of it out on the wire while the rest of it is still
  101. // being computed, we want the Lamport clock of all the chunks to be
  102. // that of when the message is first created. This value will be
  103. // nullopt when there has been no queue() since the last explicit
  104. // send() (as opposed to the implicit send() called by queue()
  105. // itself if it wants to get a chunk on its way), and will be set to
  106. // the current lamport clock when that first queue() after each
  107. // explicit send() happens.
  108. opt_lamport_t message_lamport;
  109. #ifdef SEND_LAMPORT_CLOCKS
  110. // If Lamport clocks are being sent, then the data stream is divided
  111. // into chunks, each with a header containing the length of the
  112. // chunk and the Lamport clock. So when we read, we'll read a whole
  113. // chunk, and store it here. Then calls to recv() will read pieces
  114. // of this buffer until it has all been read, and then read the next
  115. // header and chunk.
  116. std::string recvdata;
  117. size_t recvdataremain;
  118. #endif
  119. // Never touch the above messagequeue without holding this lock (you
  120. // _can_ touch the strings it contains, though, if you looked one up
  121. // while holding the lock).
  122. boost::mutex messagequeuelock;
  123. // Asynchronously send the first message from the message queue.
  124. // * The messagequeuelock must be held when this is called! *
  125. // This method may be called from either thread (the work thread or
  126. // the async_write handler thread).
  127. void async_send_from_msgqueue();
  128. public:
  129. MPCSingleIO(tcp::socket &&sock, const char *dest, int thread_num) :
  130. sock(std::move(sock)), totread(0), totwritten(0), dest(dest),
  131. thread_num(thread_num)
  132. #ifdef SEND_LAMPORT_CLOCKS
  133. , recvdataremain(0)
  134. #endif
  135. {}
  136. // Returns 1 if a new message is started, 0 otherwise
  137. size_t queue(const void *data, size_t len, lamport_t lamport);
  138. void send(bool implicit_send = false);
  139. size_t recv(void *data, size_t len, lamport_t &lamport);
  140. #ifdef RECORD_IOTRACE
  141. void dumptrace(std::ostream &os, const char *label = NULL);
  142. void resettrace() {
  143. iotrace.clear();
  144. }
  145. #endif
  146. };
  147. // A base class to represent all of a computation peer or server's IO,
  148. // either to other parties or to local storage (the computation and
  149. // server cases are separate subclasses below).
  150. struct MPCIO {
  151. int player;
  152. ProcessingMode mode;
  153. size_t num_threads;
  154. atomic_lamport_t lamport;
  155. std::vector<size_t> msgs_sent;
  156. std::vector<size_t> msg_bytes_sent;
  157. std::vector<size_t> aes_ops;
  158. boost::chrono::steady_clock::time_point steady_start;
  159. boost::chrono::process_cpu_clock::time_point cpu_start;
  160. MPCIO(int player, ProcessingMode mode, size_t num_threads) :
  161. player(player), mode(mode),
  162. num_threads(num_threads), lamport(0)
  163. {
  164. reset_stats();
  165. }
  166. void reset_stats();
  167. static void dump_memusage(std::ostream &os);
  168. void dump_stats(std::ostream &os);
  169. };
  170. // A class to represent all of a computation peer's IO, either to other
  171. // parties or to local storage
  172. struct MPCPeerIO : public MPCIO {
  173. // We use a deque here instead of a vector because you can't have a
  174. // vector of a type without a copy constructor (tcp::socket is the
  175. // culprit), but you can have a deque of those for some reason.
  176. std::deque<MPCSingleIO> peerios;
  177. std::deque<MPCSingleIO> serverios;
  178. std::vector<PreCompStorage<MultTriple, MultTripleName>> multtriples;
  179. std::vector<PreCompStorage<HalfTriple, HalfTripleName>> halftriples;
  180. std::vector<PreCompStorage<AndTriple, AndTripleName>> andtriples;
  181. std::vector<PreCompStorage<
  182. SelectTriple<value_t>, ValSelectTripleName>> valselecttriples;
  183. std::vector<PreCompStorage<CDPF, CDPFName>> cdpfs;
  184. // The outer vector is (like above) one item per thread
  185. // The inner array is indexed by DPF depth (depth d is at entry d-1)
  186. std::vector<std::array<PreCompStorage<RDPFTriple<1>, RDPFTripleName>,ADDRESS_MAX_BITS>> rdpftriples;
  187. MPCPeerIO(unsigned player, ProcessingMode mode,
  188. std::deque<tcp::socket> &peersocks,
  189. std::deque<tcp::socket> &serversocks);
  190. void dump_precomp_stats(std::ostream &os);
  191. void reset_precomp_stats();
  192. void dump_stats(std::ostream &os);
  193. };
  194. // A class to represent all of the server party's IO, either to
  195. // computational parties or to local storage
  196. struct MPCServerIO : public MPCIO {
  197. std::deque<MPCSingleIO> p0ios;
  198. std::deque<MPCSingleIO> p1ios;
  199. // The outer vector is (like above) one item per thread
  200. // The inner array is indexed by DPF depth (depth d is at entry d-1)
  201. std::vector<std::array<PreCompStorage<RDPFPair<1>, RDPFPairName>,ADDRESS_MAX_BITS>> rdpfpairs;
  202. MPCServerIO(ProcessingMode mode,
  203. std::deque<tcp::socket> &p0socks,
  204. std::deque<tcp::socket> &p1socks);
  205. void dump_precomp_stats(std::ostream &os);
  206. void reset_precomp_stats();
  207. void dump_stats(std::ostream &os);
  208. };
  209. class MPCSingleIOStream {
  210. MPCSingleIO &sio;
  211. lamport_t &lamport;
  212. size_t &msgs_sent;
  213. size_t &msg_bytes_sent;
  214. public:
  215. MPCSingleIOStream(MPCSingleIO &sio, lamport_t &lamport,
  216. size_t &msgs_sent, size_t &msg_bytes_sent) :
  217. sio(sio), lamport(lamport), msgs_sent(msgs_sent),
  218. msg_bytes_sent(msg_bytes_sent) {}
  219. MPCSingleIOStream& write(const char *data, std::streamsize len) {
  220. size_t newmsg = sio.queue(data, len, lamport);
  221. msgs_sent += newmsg;
  222. msg_bytes_sent += len;
  223. return *this;
  224. }
  225. MPCSingleIOStream& read(char *data, std::streamsize len) {
  226. sio.recv(data, len, lamport);
  227. return *this;
  228. }
  229. };
  230. // A handle to one thread's sockets and streams in a MPCIO
  231. class MPCTIO {
  232. int thread_num;
  233. // The number of threads a coroutine using this MPCTIO can use for
  234. // local computation (no communication and no yielding). Multiple
  235. // coroutines with the same MPCTIO can have this value larger than
  236. // 1, since they will not be able to use multiple threads at the
  237. // same time.
  238. int local_cpu_nthreads;
  239. // The number of threads a coroutine using this MPCTIO can launch
  240. // into separate MPCTIOs with their own communication. It is
  241. // important that at most one coroutine using this MPCTIO can have
  242. // this value set larger than 1, since all MPCTIOs with the same
  243. // thread_num (and so using the same sockets) have to be controlled
  244. // by the same run_coroutines(tio, ...) call.
  245. int communication_nthreads;
  246. lamport_t thread_lamport;
  247. MPCIO &mpcio;
  248. std::optional<MPCSingleIOStream> peer_iostream;
  249. std::optional<MPCSingleIOStream> server_iostream;
  250. std::optional<MPCSingleIOStream> p0_iostream;
  251. std::optional<MPCSingleIOStream> p1_iostream;
  252. #ifdef VERBOSE_COMMS
  253. size_t round_num;
  254. #endif
  255. // We implement SelectTriple<bit_t> by fetching a single AndTriple
  256. // and using it for producing 64 bitwise SelectTriple<bit_t>s.
  257. AndTriple last_andtriple;
  258. nbits_t last_andtriple_bits_remaining;
  259. public:
  260. MPCTIO(MPCIO &mpcio, int thread_num, int num_threads = 1);
  261. // Sync our per-thread lamport clock with the master one in the
  262. // mpcio. You only need to call this explicitly if your MPCTIO
  263. // outlives your thread (in which case call it after the join), or
  264. // if your threads do interthread communication amongst themselves
  265. // (in which case call it in the sending thread before the send, and
  266. // call it in the receiving thread after the receive). If you want
  267. // to call MPCIO::dump_stats() in the middle of a run (while the
  268. // MPCTIO is still alive), call this as well.
  269. void sync_lamport();
  270. // Only call this if you can be sure that there are no outstanding
  271. // messages in flight, you can call it on all existing MPCTIOs, and
  272. // you really want to reset the Lamport clock in the midding of a
  273. // run.
  274. void reset_lamport();
  275. // The normal case, where the MPCIO is created inside the thread,
  276. // and so destructed when the thread ends, is handled automatically
  277. // here.
  278. ~MPCTIO() {
  279. send();
  280. sync_lamport();
  281. }
  282. // Computational peers use these functions:
  283. // Queue up data to the peer or to the server
  284. void queue_peer(const void *data, size_t len);
  285. void queue_server(const void *data, size_t len);
  286. // Receive data from the peer or to the server
  287. size_t recv_peer(void *data, size_t len);
  288. size_t recv_server(void *data, size_t len);
  289. // Or get these MPCSingleIOStreams
  290. MPCSingleIOStream& iostream_peer() { return peer_iostream.value(); }
  291. MPCSingleIOStream& iostream_server() { return server_iostream.value(); }
  292. // The server uses these functions:
  293. // Queue up data to p0 or p1
  294. void queue_p0(const void *data, size_t len);
  295. void queue_p1(const void *data, size_t len);
  296. // Receive data from p0 or p1
  297. size_t recv_p0(void *data, size_t len);
  298. size_t recv_p1(void *data, size_t len);
  299. // Or get these MPCSingleIOStreams
  300. MPCSingleIOStream& iostream_p0() { return p0_iostream.value(); }
  301. MPCSingleIOStream& iostream_p1() { return p1_iostream.value(); }
  302. // Everyone can use the remaining functions.
  303. // Send all queued data for this thread
  304. void send();
  305. // Functions to get precomputed values. If we're in the online
  306. // phase, get them from PreCompStorage. If we're in the
  307. // preprocessing phase, read them from the server.
  308. MultTriple multtriple(yield_t &yield);
  309. HalfTriple halftriple(yield_t &yield, bool tally=true);
  310. AndTriple andtriple(yield_t &yield);
  311. SelectTriple<DPFnode> nodeselecttriple(yield_t &yield);
  312. SelectTriple<value_t> valselecttriple(yield_t &yield);
  313. SelectTriple<bit_t> bitselecttriple(yield_t &yield);
  314. // These ones only work during the online phase
  315. // Computational peers call:
  316. RDPFTriple<1> rdpftriple(yield_t &yield, nbits_t depth,
  317. bool keep_expansion = true);
  318. // The server calls:
  319. RDPFPair<1> rdpfpair(yield_t &yield, nbits_t depth);
  320. // Anyone can call:
  321. CDPF cdpf(yield_t &yield);
  322. // Accessors
  323. inline int player() { return mpcio.player; }
  324. inline bool preprocessing() { return mpcio.mode == MODE_PREPROCESSING; }
  325. inline bool is_server() { return mpcio.player == 2; }
  326. inline size_t& aes_ops() { return mpcio.aes_ops[thread_num]; }
  327. inline size_t msgs_sent() { return mpcio.msgs_sent[thread_num]; }
  328. inline int cpu_nthreads(int nthreads=0) {
  329. int res = local_cpu_nthreads;
  330. if (nthreads > 0) {
  331. local_cpu_nthreads = nthreads;
  332. }
  333. return res;
  334. }
  335. inline int comm_nthreads(int nthreads=0) {
  336. int res = communication_nthreads;
  337. if (nthreads > 0) {
  338. communication_nthreads = nthreads;
  339. }
  340. return res;
  341. }
  342. };
  343. // Set up the socket connections between the two computational parties
  344. // (P0 and P1) and the server party (P2). For each connection, the
  345. // lower-numbered party does the accept() and the higher-numbered party
  346. // does the connect().
  347. // Computational parties call this version with player=0 or 1
  348. void mpcio_setup_computational(unsigned player,
  349. boost::asio::io_context &io_context,
  350. const char *p0addr, // can be NULL when player=0
  351. int num_threads,
  352. std::deque<tcp::socket> &peersocks,
  353. std::deque<tcp::socket> &serversocks);
  354. // Server calls this version
  355. void mpcio_setup_server(boost::asio::io_context &io_context,
  356. const char *p0addr, const char *p1addr, int num_threads,
  357. std::deque<tcp::socket> &p0socks,
  358. std::deque<tcp::socket> &p1socks);
  359. #endif