mpcio.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #ifndef __MCPIO_HPP__
  2. #define __MCPIO_HPP__
  3. #include <iostream>
  4. #include <fstream>
  5. #include <vector>
  6. #include <deque>
  7. #include <queue>
  8. #include <string>
  9. #include <atomic>
  10. #include <optional>
  11. #include <bsd/stdlib.h> // arc4random_buf
  12. #include <boost/asio.hpp>
  13. #include <boost/thread.hpp>
  14. #include <boost/chrono.hpp>
  15. #include "types.hpp"
  16. using boost::asio::ip::tcp;
  17. // Classes to represent stored precomputed data (e.g., multiplication triples)
  18. template<typename T>
  19. class PreCompStorage {
  20. public:
  21. PreCompStorage(unsigned player, bool preprocessing,
  22. const char *filenameprefix, unsigned thread_num);
  23. void get(T& nextval);
  24. inline size_t get_stats() { return count; }
  25. inline void reset_stats() { count = 0; }
  26. private:
  27. std::ifstream storage;
  28. size_t count;
  29. };
  30. // If we want to send Lamport clocks in messages, define this. It adds
  31. // an 8-byte header to each message (length and Lamport clock), so it
  32. // has a small network cost. We always define and pass the Lamport
  33. // clock member of MPCIO to the IO functions for simplicity, but they're
  34. // ignored if this isn't defined
  35. #define SEND_LAMPORT_CLOCKS
  36. using lamport_t = uint32_t;
  37. using atomic_lamport_t = std::atomic<lamport_t>;
  38. using opt_lamport_t = std::optional<lamport_t>;
  39. #ifdef SEND_LAMPORT_CLOCKS
  40. struct MessageWithHeader {
  41. std::string header;
  42. std::string message;
  43. MessageWithHeader(std::string &&msg, lamport_t lamport) :
  44. message(std::move(msg)) {
  45. char hdr[sizeof(uint32_t) + sizeof(lamport_t)];
  46. uint32_t msglen = uint32_t(message.size());
  47. memmove(hdr, &msglen, sizeof(msglen));
  48. memmove(hdr+sizeof(msglen), &lamport, sizeof(lamport));
  49. header.assign(hdr, sizeof(hdr));
  50. }
  51. };
  52. #endif
  53. // A class to wrap a socket to another MPC party. This wrapping allows
  54. // us to do some useful logging, and perform async_writes transparently
  55. // to the application.
  56. class MPCSingleIO {
  57. tcp::socket sock;
  58. size_t totread, totwritten;
  59. #ifdef RECORD_IOTRACE
  60. std::vector<ssize_t> iotrace;
  61. #endif
  62. // To avoid blocking if both we and our peer are trying to send
  63. // something very large, and neither side is receiving, we will send
  64. // with async_write. But this has a number of implications:
  65. // - The data to be sent has to be copied into this MPCSingleIO,
  66. // since asio::buffer pointers are not guaranteed to remain valid
  67. // after the end of the coroutine that created them
  68. // - We have to keep a queue of messages to be sent, in case
  69. // coroutines call send() before the previous message has finished
  70. // being sent
  71. // - This queue may be accessed from the async_write thread as well
  72. // as the work thread that uses this MPCSingleIO directly (there
  73. // should be only one of the latter), so we need some locking
  74. // This is where we accumulate data passed in queue()
  75. std::string dataqueue;
  76. // When send() is called, the above dataqueue is appended to this
  77. // messagequeue, and the dataqueue is reset. If messagequeue was
  78. // empty before this append, launch async_write to write the first
  79. // thing in the messagequeue. When async_write completes, it will
  80. // delete the first thing in the messagequeue, and see if there are
  81. // any more elements. If so, it will start another async_write.
  82. // The invariant is that there is an async_write currently running
  83. // iff messagequeue is nonempty.
  84. #ifdef SEND_LAMPORT_CLOCKS
  85. std::queue<MessageWithHeader> messagequeue;
  86. #else
  87. std::queue<std::string> messagequeue;
  88. #endif
  89. // If a single message is broken into chunks in order to get the
  90. // first part of it out on the wire while the rest of it is still
  91. // being computed, we want the Lamport clock of all the chunks to be
  92. // that of when the message is first created. This value will be
  93. // nullopt when there has been no queue() since the last explicit
  94. // send() (as opposed to the implicit send() called by queue()
  95. // itself if it wants to get a chunk on its way), and will be set to
  96. // the current lamport clock when that first queue() after each
  97. // explicit send() happens.
  98. opt_lamport_t message_lamport;
  99. #ifdef SEND_LAMPORT_CLOCKS
  100. // If Lamport clocks are being sent, then the data stream is divided
  101. // into chunks, each with a header containing the length of the
  102. // chunk and the Lamport clock. So when we read, we'll read a whole
  103. // chunk, and store it here. Then calls to recv() will read pieces
  104. // of this buffer until it has all been read, and then read the next
  105. // header and chunk.
  106. std::string recvdata;
  107. size_t recvdataremain;
  108. #endif
  109. // Never touch the above messagequeue without holding this lock (you
  110. // _can_ touch the strings it contains, though, if you looked one up
  111. // while holding the lock).
  112. boost::mutex messagequeuelock;
  113. // Asynchronously send the first message from the message queue.
  114. // * The messagequeuelock must be held when this is called! *
  115. // This method may be called from either thread (the work thread or
  116. // the async_write handler thread).
  117. void async_send_from_msgqueue();
  118. public:
  119. MPCSingleIO(tcp::socket &&sock) :
  120. sock(std::move(sock)), totread(0), totwritten(0) {}
  121. // Returns 1 if a new message is started, 0 otherwise
  122. size_t queue(const void *data, size_t len, lamport_t lamport);
  123. void send(bool implicit_send = false);
  124. size_t recv(void *data, size_t len, lamport_t &lamport);
  125. #ifdef RECORD_IOTRACE
  126. void dumptrace(std::ostream &os, const char *label = NULL);
  127. void resettrace() {
  128. iotrace.clear();
  129. }
  130. #endif
  131. };
  132. // A base class to represent all of a computation peer or server's IO,
  133. // either to other parties or to local storage (the computation and
  134. // server cases are separate subclasses below).
  135. struct MPCIO {
  136. int player;
  137. bool preprocessing;
  138. size_t num_threads;
  139. atomic_lamport_t lamport;
  140. std::vector<size_t> msgs_sent;
  141. std::vector<size_t> msg_bytes_sent;
  142. std::vector<size_t> aes_ops;
  143. boost::chrono::steady_clock::time_point steady_start;
  144. boost::chrono::process_cpu_clock::time_point cpu_start;
  145. MPCIO(int player, bool preprocessing, size_t num_threads) :
  146. player(player), preprocessing(preprocessing),
  147. num_threads(num_threads), lamport(0)
  148. {
  149. reset_stats();
  150. }
  151. void reset_stats();
  152. void dump_stats(std::ostream &os);
  153. };
  154. // A class to represent all of a computation peer's IO, either to other
  155. // parties or to local storage
  156. struct MPCPeerIO : public MPCIO {
  157. // We use a deque here instead of a vector because you can't have a
  158. // vector of a type without a copy constructor (tcp::socket is the
  159. // culprit), but you can have a deque of those for some reason.
  160. std::deque<MPCSingleIO> peerios;
  161. std::deque<MPCSingleIO> serverios;
  162. std::vector<PreCompStorage<MultTriple>> triples;
  163. std::vector<PreCompStorage<HalfTriple>> halftriples;
  164. MPCPeerIO(unsigned player, bool preprocessing,
  165. std::deque<tcp::socket> &peersocks,
  166. std::deque<tcp::socket> &serversocks);
  167. void dump_precomp_stats(std::ostream &os);
  168. void reset_precomp_stats();
  169. void dump_stats(std::ostream &os);
  170. };
  171. // A class to represent all of the server party's IO, either to
  172. // computational parties or to local storage
  173. struct MPCServerIO : public MPCIO {
  174. std::deque<MPCSingleIO> p0ios;
  175. std::deque<MPCSingleIO> p1ios;
  176. MPCServerIO(bool preprocessing,
  177. std::deque<tcp::socket> &p0socks,
  178. std::deque<tcp::socket> &p1socks);
  179. };
  180. // A handle to one thread's sockets and streams in a MPCIO
  181. class MPCTIO {
  182. int thread_num;
  183. lamport_t thread_lamport;
  184. MPCIO &mpcio;
  185. public:
  186. MPCTIO(MPCIO &mpcio, int thread_num):
  187. thread_num(thread_num), thread_lamport(mpcio.lamport),
  188. mpcio(mpcio) {}
  189. // Sync our per-thread lamport clock with the master one in the
  190. // mpcio. You only need to call this explicitly if your MPCTIO
  191. // outlives your thread (in which case call it after the join), or
  192. // if your threads do interthread communication amongst themselves
  193. // (in which case call it in the sending thread before the send, and
  194. // call it in the receiving thread after the receive).
  195. void sync_lamport();
  196. // The normal case, where the MPCIO is created inside the thread,
  197. // and so destructed when the thread ends, is handled automatically
  198. // here.
  199. ~MPCTIO() {
  200. sync_lamport();
  201. }
  202. // Queue up data to the peer or to the server
  203. void queue_peer(const void *data, size_t len);
  204. void queue_server(const void *data, size_t len);
  205. // Receive data from the peer or to the server
  206. size_t recv_peer(void *data, size_t len);
  207. size_t recv_server(void *data, size_t len);
  208. // Queue up data to p0 or p1
  209. void queue_p0(const void *data, size_t len);
  210. void queue_p1(const void *data, size_t len);
  211. // Receive data from p0 or p1
  212. size_t recv_p0(void *data, size_t len);
  213. size_t recv_p1(void *data, size_t len);
  214. // Send all queued data for this thread
  215. void send();
  216. // Functions to get precomputed values. If we're in the online
  217. // phase, get them from PreCompStorage. If we're in the
  218. // preprocessing phase, read them from the server.
  219. MultTriple triple();
  220. HalfTriple halftriple();
  221. AndTriple andtriple();
  222. // Accessors
  223. inline int player() { return mpcio.player; }
  224. inline bool preprocessing() { return mpcio.preprocessing; }
  225. inline bool is_server() { return mpcio.player == 2; }
  226. inline size_t& aes_ops() { return mpcio.aes_ops[thread_num]; }
  227. };
  228. // Set up the socket connections between the two computational parties
  229. // (P0 and P1) and the server party (P2). For each connection, the
  230. // lower-numbered party does the accept() and the higher-numbered party
  231. // does the connect().
  232. // Computational parties call this version with player=0 or 1
  233. void mpcio_setup_computational(unsigned player,
  234. boost::asio::io_context &io_context,
  235. const char *p0addr, // can be NULL when player=0
  236. int num_threads,
  237. std::deque<tcp::socket> &peersocks,
  238. std::deque<tcp::socket> &serversocks);
  239. // Server calls this version
  240. void mpcio_setup_server(boost::asio::io_context &io_context,
  241. const char *p0addr, const char *p1addr, int num_threads,
  242. std::deque<tcp::socket> &p0socks,
  243. std::deque<tcp::socket> &p1socks);
  244. #endif