mpcio.hpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #ifndef __MCPIO_HPP__
  2. #define __MCPIO_HPP__
  3. #include <iostream>
  4. #include <fstream>
  5. #include <tuple>
  6. #include <vector>
  7. #include <deque>
  8. #include <queue>
  9. #include <string>
  10. #include <cstdint>
  11. #include <boost/asio.hpp>
  12. #include <boost/coroutine2/all.hpp>
  13. #include <boost/thread.hpp>
  14. using boost::asio::ip::tcp;
  15. // Classes to represent stored precomputed data (e.g., multiplicative triples)
  16. typedef std::tuple<uint64_t, uint64_t, uint64_t> MultTriple;
  17. typedef std::tuple<uint64_t, uint64_t> HalfTriple;
  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. private:
  25. std::ifstream storage;
  26. };
  27. template<typename T>
  28. PreCompStorage<T>::PreCompStorage(unsigned player, bool preprocessing,
  29. const char *filenameprefix, unsigned thread_num) {
  30. if (preprocessing) return;
  31. std::string filename(filenameprefix);
  32. char suffix[20];
  33. sprintf(suffix, ".p%d.t%u", player%10, thread_num);
  34. filename.append(suffix);
  35. storage.open(filename);
  36. if (storage.fail()) {
  37. std::cerr << "Failed to open " << filename << "\n";
  38. exit(1);
  39. }
  40. }
  41. template<typename T>
  42. void PreCompStorage<T>::get(T& nextval) {
  43. storage.read((char *)&nextval, sizeof(T));
  44. if (storage.gcount() != sizeof(T)) {
  45. std::cerr << "Failed to read precomputed value from storage\n";
  46. exit(1);
  47. }
  48. }
  49. // A class to wrap a socket to another MPC party. This wrapping allows
  50. // us to do some useful logging, and perform async_writes transparently
  51. // to the application.
  52. class MPCSingleIO {
  53. tcp::socket sock;
  54. size_t totread, totwritten;
  55. std::vector<ssize_t> iotrace;
  56. // To avoid blocking if both we and our peer are trying to send
  57. // something very large, and neither side is receiving, we will send
  58. // with async_write. But this has a number of implications:
  59. // - The data to be sent has to be copied into this MPCSingleIO,
  60. // since asio::buffer pointers are not guaranteed to remain valid
  61. // after the end of the coroutine that created them
  62. // - We have to keep a queue of messages to be sent, in case
  63. // coroutines call send() before the previous message has finished
  64. // being sent
  65. // - This queue may be accessed from the async_write thread as well
  66. // as the work thread that uses this MPCSingleIO directly (there
  67. // should be only one of the latter), so we need some locking
  68. // This is where we accumulate data passed in queue()
  69. std::string dataqueue;
  70. // When send() is called, the above dataqueue is appended to this
  71. // messagequeue, and the dataqueue is reset. If messagequeue was
  72. // empty before this append, launch async_write to write the first
  73. // thing in the messagequeue. When async_write completes, it will
  74. // delete the first thing in the messagequeue, and see if there are
  75. // any more elements. If so, it will start another async_write.
  76. // The invariant is that there is an async_write currently running
  77. // iff messagequeue is nonempty.
  78. std::queue<std::string> messagequeue;
  79. // Never touch the above messagequeue without holding this lock (you
  80. // _can_ touch the strings it contains, though, if you looked one up
  81. // while holding the lock).
  82. boost::mutex messagequeuelock;
  83. // Asynchronously send the first message from the message queue.
  84. // * The messagequeuelock must be held when this is called! *
  85. // This method may be called from either thread (the work thread or
  86. // the async_write handler thread).
  87. void async_send_from_msgqueue() {
  88. boost::asio::async_write(sock,
  89. boost::asio::buffer(messagequeue.front()),
  90. [&](boost::system::error_code ec, std::size_t amt){
  91. messagequeuelock.lock();
  92. messagequeue.pop();
  93. if (messagequeue.size() > 0) {
  94. async_send_from_msgqueue();
  95. }
  96. messagequeuelock.unlock();
  97. });
  98. }
  99. public:
  100. MPCSingleIO(tcp::socket &&sock) :
  101. sock(std::move(sock)), totread(0), totwritten(0) {}
  102. void queue(const void *data, size_t len) {
  103. dataqueue.append((const char *)data, len);
  104. // If we already have some full packets worth of data, may as
  105. // well send it.
  106. if (dataqueue.size() > 28800) {
  107. send();
  108. }
  109. }
  110. void send() {
  111. size_t thissize = dataqueue.size();
  112. // Ignore spurious calls to send()
  113. if (thissize == 0) return;
  114. iotrace.push_back(thissize);
  115. messagequeuelock.lock();
  116. // Move the current message to send into the message queue (this
  117. // moves a pointer to the data, not copying the data itself)
  118. messagequeue.emplace(std::move(dataqueue));
  119. // If this is now the first thing in the message queue, launch
  120. // an async_write to write it
  121. if (messagequeue.size() == 1) {
  122. async_send_from_msgqueue();
  123. }
  124. messagequeuelock.unlock();
  125. }
  126. size_t recv(const std::vector<boost::asio::mutable_buffer>& buffers) {
  127. size_t res = boost::asio::read(sock, buffers);
  128. iotrace.push_back(-(ssize_t(res)));
  129. return res;
  130. }
  131. size_t recv(const boost::asio::mutable_buffer& buffer) {
  132. size_t res = boost::asio::read(sock, buffer);
  133. iotrace.push_back(-(ssize_t(res)));
  134. return res;
  135. }
  136. size_t recv(void *data, size_t len) {
  137. size_t res = boost::asio::read(sock, boost::asio::buffer(data, len));
  138. iotrace.push_back(-(ssize_t(res)));
  139. return res;
  140. }
  141. void dumptrace(std::ostream &os, const char *label = NULL) {
  142. if (label) {
  143. os << label << " ";
  144. }
  145. os << "IO trace:";
  146. for (auto& s: iotrace) {
  147. os << " " << s;
  148. }
  149. os << "\n";
  150. }
  151. void resettrace() {
  152. iotrace.clear();
  153. }
  154. };
  155. // A class to represent all of a computation party's IO, either to other
  156. // parties or to local storage
  157. struct MPCIO {
  158. int player;
  159. // We use a deque here instead of a vector because you can't have a
  160. // vector of a type without a copy constructor (tcp::socket is the
  161. // culprit), but you can have a deque of those for some reason.
  162. std::deque<MPCSingleIO> peerios;
  163. MPCSingleIO serverio;
  164. std::vector<PreCompStorage<MultTriple>> triples;
  165. MPCIO(unsigned player, bool preprocessing,
  166. std::deque<tcp::socket> &peersocks, tcp::socket &&serversock) :
  167. player(player), serverio(std::move(serversock)) {
  168. unsigned num_threads = unsigned(peersocks.size());
  169. for (unsigned i=0; i<num_threads; ++i) {
  170. triples.emplace_back(player, preprocessing, "triples", i);
  171. }
  172. for (auto &&sock : peersocks) {
  173. peerios.emplace_back(std::move(sock));
  174. }
  175. }
  176. };
  177. // A class to represent all of the server party's IO, either to
  178. // computational parties or to local storage
  179. struct MPCServerIO {
  180. MPCSingleIO p0io;
  181. MPCSingleIO p1io;
  182. MPCServerIO(bool preprocessing, tcp::socket &&p0sock,
  183. tcp::socket &&p1sock) :
  184. p0io(std::move(p0sock)), p1io(std::move(p1sock)) {}
  185. };
  186. // Set up the socket connections between the two computational parties
  187. // (P0 and P1) and the server party (P2). For each connection, the
  188. // lower-numbered party does the accept() and the higher-numbered party
  189. // does the connect().
  190. // Computational parties call this version with player=0 or 1
  191. void mpcio_setup_computational(unsigned player,
  192. boost::asio::io_context &io_context,
  193. const char *p0addr, // can be NULL when player=0
  194. int num_threads,
  195. std::deque<tcp::socket> &peersocks, tcp::socket &serversock);
  196. // Server calls this version with player=2
  197. void mpcio_setup_server(boost::asio::io_context &io_context,
  198. const char *p0addr, const char *p1addr,
  199. tcp::socket &p0sock, tcp::socket &p1sock);
  200. #endif