mpcio.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. std::vector<PreCompStorage<CDPF, CDPFName>> cdpfs;
  172. // The outer vector is (like above) one item per thread
  173. // The inner array is indexed by DPF depth (depth d is at entry d-1)
  174. std::vector<std::array<PreCompStorage<RDPFTriple, RDPFTripleName>,ADDRESS_MAX_BITS>> rdpftriples;
  175. MPCPeerIO(unsigned player, bool preprocessing,
  176. std::deque<tcp::socket> &peersocks,
  177. std::deque<tcp::socket> &serversocks);
  178. void dump_precomp_stats(std::ostream &os);
  179. void reset_precomp_stats();
  180. void dump_stats(std::ostream &os);
  181. };
  182. // A class to represent all of the server party's IO, either to
  183. // computational parties or to local storage
  184. struct MPCServerIO : public MPCIO {
  185. std::deque<MPCSingleIO> p0ios;
  186. std::deque<MPCSingleIO> p1ios;
  187. // The outer vector is (like above) one item per thread
  188. // The inner array is indexed by DPF depth (depth d is at entry d-1)
  189. std::vector<std::array<PreCompStorage<RDPFPair, RDPFPairName>,ADDRESS_MAX_BITS>> rdpfpairs;
  190. MPCServerIO(bool preprocessing,
  191. std::deque<tcp::socket> &p0socks,
  192. std::deque<tcp::socket> &p1socks);
  193. void dump_precomp_stats(std::ostream &os);
  194. void reset_precomp_stats();
  195. void dump_stats(std::ostream &os);
  196. };
  197. class MPCSingleIOStream {
  198. MPCSingleIO &sio;
  199. lamport_t &lamport;
  200. size_t &msgs_sent;
  201. size_t &msg_bytes_sent;
  202. public:
  203. MPCSingleIOStream(MPCSingleIO &sio, lamport_t &lamport,
  204. size_t &msgs_sent, size_t &msg_bytes_sent) :
  205. sio(sio), lamport(lamport), msgs_sent(msgs_sent),
  206. msg_bytes_sent(msg_bytes_sent) {}
  207. MPCSingleIOStream& write(const char *data, std::streamsize len) {
  208. size_t newmsg = sio.queue(data, len, lamport);
  209. msgs_sent += newmsg;
  210. msg_bytes_sent += len;
  211. return *this;
  212. }
  213. MPCSingleIOStream& read(char *data, std::streamsize len) {
  214. sio.recv(data, len, lamport);
  215. return *this;
  216. }
  217. };
  218. // A handle to one thread's sockets and streams in a MPCIO
  219. class MPCTIO {
  220. int thread_num;
  221. lamport_t thread_lamport;
  222. MPCIO &mpcio;
  223. std::optional<MPCSingleIOStream> peer_iostream;
  224. std::optional<MPCSingleIOStream> server_iostream;
  225. std::optional<MPCSingleIOStream> p0_iostream;
  226. std::optional<MPCSingleIOStream> p1_iostream;
  227. public:
  228. MPCTIO(MPCIO &mpcio, int thread_num);
  229. // Sync our per-thread lamport clock with the master one in the
  230. // mpcio. You only need to call this explicitly if your MPCTIO
  231. // outlives your thread (in which case call it after the join), or
  232. // if your threads do interthread communication amongst themselves
  233. // (in which case call it in the sending thread before the send, and
  234. // call it in the receiving thread after the receive).
  235. void sync_lamport();
  236. // The normal case, where the MPCIO is created inside the thread,
  237. // and so destructed when the thread ends, is handled automatically
  238. // here.
  239. ~MPCTIO() {
  240. sync_lamport();
  241. }
  242. // Computational peers use these functions:
  243. // Queue up data to the peer or to the server
  244. void queue_peer(const void *data, size_t len);
  245. void queue_server(const void *data, size_t len);
  246. // Receive data from the peer or to the server
  247. size_t recv_peer(void *data, size_t len);
  248. size_t recv_server(void *data, size_t len);
  249. // Or get these MPCSingleIOStreams
  250. MPCSingleIOStream& iostream_peer() { return peer_iostream.value(); }
  251. MPCSingleIOStream& iostream_server() { return server_iostream.value(); }
  252. // The server uses these functions:
  253. // Queue up data to p0 or p1
  254. void queue_p0(const void *data, size_t len);
  255. void queue_p1(const void *data, size_t len);
  256. // Receive data from p0 or p1
  257. size_t recv_p0(void *data, size_t len);
  258. size_t recv_p1(void *data, size_t len);
  259. // Or get these MPCSingleIOStreams
  260. MPCSingleIOStream& iostream_p0() { return p0_iostream.value(); }
  261. MPCSingleIOStream& iostream_p1() { return p1_iostream.value(); }
  262. // Everyone can use the remaining functions.
  263. // Send all queued data for this thread
  264. void send();
  265. // Functions to get precomputed values. If we're in the online
  266. // phase, get them from PreCompStorage. If we're in the
  267. // preprocessing phase, read them from the server.
  268. MultTriple triple();
  269. HalfTriple halftriple();
  270. SelectTriple selecttriple();
  271. // These ones only work during the online phase
  272. // Computational peers call:
  273. RDPFTriple rdpftriple(nbits_t depth);
  274. // The server calls:
  275. RDPFPair rdpfpair(nbits_t depth);
  276. // Anyone can call:
  277. CDPF cdpf();
  278. // Accessors
  279. inline int player() { return mpcio.player; }
  280. inline bool preprocessing() { return mpcio.preprocessing; }
  281. inline bool is_server() { return mpcio.player == 2; }
  282. inline size_t& aes_ops() { return mpcio.aes_ops[thread_num]; }
  283. };
  284. // Set up the socket connections between the two computational parties
  285. // (P0 and P1) and the server party (P2). For each connection, the
  286. // lower-numbered party does the accept() and the higher-numbered party
  287. // does the connect().
  288. // Computational parties call this version with player=0 or 1
  289. void mpcio_setup_computational(unsigned player,
  290. boost::asio::io_context &io_context,
  291. const char *p0addr, // can be NULL when player=0
  292. int num_threads,
  293. std::deque<tcp::socket> &peersocks,
  294. std::deque<tcp::socket> &serversocks);
  295. // Server calls this version
  296. void mpcio_setup_server(boost::asio::io_context &io_context,
  297. const char *p0addr, const char *p1addr, int num_threads,
  298. std::deque<tcp::socket> &p0socks,
  299. std::deque<tcp::socket> &p1socks);
  300. #endif