preproc.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <bsd/stdlib.h> // arc4random_buf
  2. #include "preproc.hpp"
  3. // Open a file for writing with name the given prefix, and ".pX" suffix,
  4. // where X is the (one-digit) player number
  5. static std::ofstream openfile(const char *prefix, unsigned player)
  6. {
  7. std::string filename(prefix);
  8. char suffix[4];
  9. sprintf(suffix, ".p%d", player%10);
  10. filename.append(suffix);
  11. std::ofstream f;
  12. f.open(filename);
  13. if (f.fail()) {
  14. std::cerr << "Failed to open " << filename << "\n";
  15. exit(1);
  16. }
  17. return f;
  18. }
  19. // The server-to-computational-peer protocol for sending precomputed
  20. // data is:
  21. //
  22. // One byte: type
  23. // 0x80: Multiplication triple
  24. // 0x81: Multiplication half-triple
  25. // 0x01 to 0x40: DPF of that depth
  26. // 0x00: End of preprocessing
  27. //
  28. // Four bytes: number of objects of that type (not sent for type == 0x00)
  29. //
  30. // Then that number of objects
  31. //
  32. // Repeat the whole thing until type == 0x00 is received
  33. void preprocessing_comp(MPCIO &mpcio, char **args)
  34. {
  35. while(1) {
  36. unsigned char type = 0;
  37. unsigned int num = 0;
  38. size_t res = mpcio.serverio.recv(&type, 1);
  39. if (res < 1 || type == 0) break;
  40. mpcio.serverio.recv(&num, 4);
  41. if (type == 0x80) {
  42. // Multiplication triples
  43. std::ofstream tripfile = openfile("triples", mpcio.player);
  44. MultTriple T;
  45. for (unsigned int i=0; i<num; ++i) {
  46. res = mpcio.serverio.recv(&T, sizeof(T));
  47. if (res < sizeof(T)) break;
  48. tripfile.write((const char *)&T, sizeof(T));
  49. }
  50. tripfile.close();
  51. }
  52. }
  53. }
  54. void preprocessing_server(MPCServerIO &mpcsrvio, char **args)
  55. {
  56. unsigned int numtriples = 100;
  57. if (*args) {
  58. numtriples = atoi(*args);
  59. ++args;
  60. }
  61. unsigned char type = 0x80;
  62. mpcsrvio.p0io.queue(&type, 1);
  63. mpcsrvio.p0io.queue(&numtriples, 4);
  64. mpcsrvio.p1io.queue(&type, 1);
  65. mpcsrvio.p1io.queue(&numtriples, 4);
  66. for (unsigned int i=0; i<numtriples; ++i) {
  67. uint64_t X0, Y0, Z0, X1, Y1, Z1;
  68. arc4random_buf(&X0, sizeof(X0));
  69. arc4random_buf(&Y0, sizeof(Y0));
  70. arc4random_buf(&Z0, sizeof(Z0));
  71. arc4random_buf(&X1, sizeof(X1));
  72. arc4random_buf(&Y1, sizeof(Y1));
  73. Z1 = X0 * Y1 + X1 * Y0 - Z0;
  74. MultTriple T0, T1;
  75. T0 = std::make_tuple(X0, Y0, Z0);
  76. T1 = std::make_tuple(X1, Y1, Z1);
  77. mpcsrvio.p0io.queue(&T0, sizeof(T0));
  78. mpcsrvio.p1io.queue(&T1, sizeof(T1));
  79. }
  80. // That's all
  81. type = 0x00;
  82. mpcsrvio.p0io.queue(&type, 1);
  83. mpcsrvio.p1io.queue(&type, 1);
  84. mpcsrvio.p0io.send();
  85. mpcsrvio.p1io.send();
  86. }