mpcio.hpp 7.2 KB

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