mpcio.hpp 7.9 KB

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