mpcio.hpp 12 KB

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