mpcio.hpp 13 KB

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