mpcio.hpp 13 KB

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