bst.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. #include <functional>
  2. #include "types.hpp"
  3. #include "duoram.hpp"
  4. #include "cdpf.hpp"
  5. #include "bst.hpp"
  6. // This file demonstrates how to implement custom ORAM wide cell types.
  7. // Such types can be structures of arbitrary numbers of RegAS and RegXS
  8. // fields. The example here imagines a node of a binary search tree,
  9. // where you would want the key to be additively shared (so that you can
  10. // easily do comparisons), the pointers field to be XOR shared (so that
  11. // you can easily do bit operations to pack two pointers and maybe some
  12. // tree balancing information into one field) and the value doesn't
  13. // really matter, but XOR shared is usually slightly more efficient.
  14. struct Node {
  15. RegAS key;
  16. RegXS pointers;
  17. RegXS value;
  18. // Field-access macros so we can write A[i].NODE_KEY instead of
  19. // A[i].field(&Node::key)
  20. #define NODE_KEY field(&Node::key)
  21. #define NODE_POINTERS field(&Node::pointers)
  22. #define NODE_VALUE field(&Node::value)
  23. // For debugging and checking answers
  24. void dump() const {
  25. printf("[%016lx %016lx %016lx]", key.share(), pointers.share(),
  26. value.share());
  27. }
  28. // You'll need to be able to create a random element, and do the
  29. // operations +=, +, -=, - (binary and unary). Note that for
  30. // XOR-shared fields, + and - are both really XOR.
  31. inline void randomize() {
  32. key.randomize();
  33. pointers.randomize();
  34. value.randomize();
  35. }
  36. inline Node &operator+=(const Node &rhs) {
  37. this->key += rhs.key;
  38. this->pointers += rhs.pointers;
  39. this->value += rhs.value;
  40. return *this;
  41. }
  42. inline Node operator+(const Node &rhs) const {
  43. Node res = *this;
  44. res += rhs;
  45. return res;
  46. }
  47. inline Node &operator-=(const Node &rhs) {
  48. this->key -= rhs.key;
  49. this->pointers -= rhs.pointers;
  50. this->value -= rhs.value;
  51. return *this;
  52. }
  53. inline Node operator-(const Node &rhs) const {
  54. Node res = *this;
  55. res -= rhs;
  56. return res;
  57. }
  58. inline Node operator-() const {
  59. Node res;
  60. res.key = -this->key;
  61. res.pointers = -this->pointers;
  62. res.value = -this->value;
  63. return res;
  64. }
  65. // Multiply each field by the local share of the corresponding field
  66. // in the argument
  67. inline Node mulshare(const Node &rhs) const {
  68. Node res = *this;
  69. res.key.mulshareeq(rhs.key);
  70. res.pointers.mulshareeq(rhs.pointers);
  71. res.value.mulshareeq(rhs.value);
  72. return res;
  73. }
  74. // You need a method to turn a leaf node of a DPF into a share of a
  75. // unit element of your type. Typically set each RegAS to
  76. // dpf.unit_as(leaf) and each RegXS or RegBS to dpf.unit_bs(leaf).
  77. // Note that RegXS will extend a RegBS of 1 to the all-1s word, not
  78. // the word with value 1. This is used for ORAM reads, where the
  79. // same DPF is used for all the fields.
  80. inline void unit(const RDPF &dpf, DPFnode leaf) {
  81. key = dpf.unit_as(leaf);
  82. pointers = dpf.unit_bs(leaf);
  83. value = dpf.unit_bs(leaf);
  84. }
  85. // Perform an update on each of the fields, using field-specific
  86. // MemRefs constructed from the Shape shape and the index idx
  87. template <typename Sh, typename U>
  88. inline static void update(Sh &shape, yield_t &shyield, U idx,
  89. const Node &M) {
  90. run_coroutines(shyield,
  91. [&shape, &idx, &M] (yield_t &yield) {
  92. Sh Sh_coro = shape.context(yield);
  93. Sh_coro[idx].NODE_KEY += M.key;
  94. },
  95. [&shape, &idx, &M] (yield_t &yield) {
  96. Sh Sh_coro = shape.context(yield);
  97. Sh_coro[idx].NODE_POINTERS += M.pointers;
  98. },
  99. [&shape, &idx, &M] (yield_t &yield) {
  100. Sh Sh_coro = shape.context(yield);
  101. Sh_coro[idx].NODE_VALUE += M.value;
  102. });
  103. }
  104. };
  105. // I/O operations (for sending over the network)
  106. template <typename T>
  107. T& operator>>(T& is, Node &x)
  108. {
  109. is >> x.key >> x.pointers >> x.value;
  110. return is;
  111. }
  112. template <typename T>
  113. T& operator<<(T& os, const Node &x)
  114. {
  115. os << x.key << x.pointers << x.value;
  116. return os;
  117. }
  118. // This macro will define I/O on tuples of two or three of the cell type
  119. DEFAULT_TUPLE_IO(Node)
  120. std::tuple<RegBS, RegBS> compare_keys(Node n1, Node n2, MPCTIO tio, yield_t &yield) {
  121. CDPF cdpf = tio.cdpf(yield);
  122. auto [lt, eq, gt] = cdpf.compare(tio, yield, n2.key - n1.key, tio.aes_ops());
  123. RegBS lteq = lt^eq;
  124. return {lteq, gt};
  125. }
  126. RegBS check_ptr_zero(MPCTIO tio, yield_t &yield, RegXS ptr) {
  127. CDPF cdpf = tio.cdpf(yield);
  128. RegAS ptr_as;
  129. mpc_xs_to_as(tio, yield, ptr_as, ptr);
  130. RegAS zero;
  131. auto [lt, eq, gt] = cdpf.compare(tio, yield, ptr_as - zero, tio.aes_ops());
  132. return eq;
  133. }
  134. // Assuming pointer of 64 bits is split as:
  135. // - 32 bits Left ptr
  136. // - 32 bits Right ptr
  137. // < Left, Right>
  138. inline RegXS extractLeftPtr(RegXS pointer){
  139. return ((pointer&(0xFFFFFFFF00000000))>>32);
  140. }
  141. inline RegXS extractRightPtr(RegXS pointer){
  142. return (pointer&(0x00000000FFFFFFFF));
  143. }
  144. inline void setLeftPtr(RegXS &pointer, RegXS new_ptr){
  145. pointer&=(0x00000000FFFFFFFF);
  146. pointer+=(new_ptr<<32);
  147. }
  148. inline void setRightPtr(RegXS &pointer, RegXS new_ptr){
  149. pointer&=(0xFFFFFFFF00000000);
  150. pointer+=(new_ptr);
  151. }
  152. std::tuple<RegXS, RegBS> insert(MPCTIO &tio, yield_t &yield, RegXS ptr, const Node &new_node, Duoram<Node>::Flat &A, int TTL, RegBS isDummy) {
  153. if(TTL==0) {
  154. RegBS zero;
  155. return {ptr, zero};
  156. }
  157. RegBS isNotDummy = isDummy ^ (tio.player());
  158. Node cnode = A[ptr];
  159. // Compare key
  160. auto [lteq, gt] = compare_keys(cnode, new_node, tio, yield);
  161. // Depending on [lteq, gt] select the next ptr/index as
  162. // upper 32 bits of cnode.pointers if lteq
  163. // lower 32 bits of cnode.pointers if gt
  164. RegXS left = extractLeftPtr(cnode.pointers);
  165. RegXS right = extractRightPtr(cnode.pointers);
  166. RegXS next_ptr;
  167. mpc_select(tio, yield, next_ptr, gt, left, right, 32);
  168. CDPF dpf = tio.cdpf(yield);
  169. size_t &aes_ops = tio.aes_ops();
  170. // F_z: Check if this is last node on path
  171. RegBS F_z = dpf.is_zero(tio, yield, next_ptr, aes_ops);
  172. RegBS F_i;
  173. // F_i: If this was last node on path (F_z), and isNotDummy insert.
  174. mpc_and(tio, yield, F_i, (isNotDummy), F_z);
  175. isDummy^=F_i;
  176. auto [wptr, direction] = insert(tio, yield, next_ptr, new_node, A, TTL-1, isDummy);
  177. RegXS ret_ptr;
  178. RegBS ret_direction;
  179. // If we insert here (F_i), return the ptr to this node as wptr
  180. // and update direction to the direction taken by compare_keys
  181. mpc_select(tio, yield, ret_ptr, F_i, wptr, ptr);
  182. //ret_direction = direction + F_p(direction - gt)
  183. mpc_and(tio, yield, ret_direction, F_i, direction^gt);
  184. ret_direction^=direction;
  185. return {ret_ptr, ret_direction};
  186. }
  187. // Insert(root, ptr, key, TTL, isDummy) -> (new_ptr, wptr, wnode, f_p)
  188. void insert(MPCTIO &tio, yield_t &yield, RegXS &root, const Node &node, Duoram<Node>::Flat &A, size_t &num_items) {
  189. bool player0 = tio.player()==0;
  190. // If there are no items in tree. Make this new item the root.
  191. if(num_items==0) {
  192. Node zero;
  193. A[0] = zero;
  194. A[1] = node;
  195. (root).set(1*tio.player());
  196. num_items++;
  197. return;
  198. }
  199. else {
  200. // Insert node into next free slot in the ORAM
  201. int new_id = 1 + num_items;
  202. int TTL = num_items++;
  203. A[new_id] = node;
  204. RegXS new_addr;
  205. new_addr.set(new_id * tio.player());
  206. RegBS isDummy;
  207. //Do a recursive insert
  208. auto [wptr, direction] = insert(tio, yield, root, node, A, TTL, isDummy);
  209. //Complete the insertion by reading wptr and updating its pointers
  210. RegXS pointers = A[wptr].NODE_POINTERS;
  211. RegXS left_ptr = extractLeftPtr(pointers);
  212. RegXS right_ptr = extractRightPtr(pointers);
  213. RegXS new_right_ptr, new_left_ptr;
  214. mpc_select(tio, yield, new_right_ptr, direction, right_ptr, new_addr);
  215. if(player0) {
  216. direction^=1;
  217. }
  218. mpc_select(tio, yield, new_left_ptr, direction, left_ptr, new_addr);
  219. setLeftPtr(pointers, new_left_ptr);
  220. setRightPtr(pointers, new_right_ptr);
  221. A[wptr].NODE_POINTERS = pointers;
  222. }
  223. }
  224. // Pretty-print a reconstructed BST, rooted at node. is_left_child and
  225. // is_right_child indicate whether node is a left or right child of its
  226. // parent. They cannot both be true, but the root of the tree has both
  227. // of them false.
  228. void pretty_print(const std::vector<Node> &R, value_t node,
  229. const std::string &prefix, bool is_left_child, bool is_right_child)
  230. {
  231. if (node == 0) {
  232. // NULL pointer
  233. if (is_left_child) {
  234. printf("%s\xE2\x95\xA7\n", prefix.c_str()); // ╧
  235. } else if (is_right_child) {
  236. printf("%s\xE2\x95\xA4\n", prefix.c_str()); // ╤
  237. } else {
  238. printf("%s\xE2\x95\xA2\n", prefix.c_str()); // ╢
  239. }
  240. return;
  241. }
  242. const Node &n = R[node];
  243. value_t left_ptr = extractLeftPtr(n.pointers).xshare;
  244. value_t right_ptr = extractRightPtr(n.pointers).xshare;
  245. std::string rightprefix(prefix), leftprefix(prefix),
  246. nodeprefix(prefix);
  247. if (is_left_child) {
  248. rightprefix.append("\xE2\x94\x82"); // │
  249. leftprefix.append(" ");
  250. nodeprefix.append("\xE2\x94\x94"); // └
  251. } else if (is_right_child) {
  252. rightprefix.append(" ");
  253. leftprefix.append("\xE2\x94\x82"); // │
  254. nodeprefix.append("\xE2\x94\x8C"); // ┌
  255. } else {
  256. rightprefix.append(" ");
  257. leftprefix.append(" ");
  258. nodeprefix.append("\xE2\x94\x80"); // ─
  259. }
  260. pretty_print(R, right_ptr, rightprefix, false, true);
  261. printf("%s\xE2\x94\xA4", nodeprefix.c_str()); // ┤
  262. n.dump();
  263. printf("\n");
  264. pretty_print(R, left_ptr, leftprefix, true, false);
  265. }
  266. void newnode(Node &a) {
  267. a.key.randomize(8);
  268. a.pointers.set(0);
  269. a.value.randomize();
  270. }
  271. // Now we use the node in various ways. This function is called by
  272. // online.cpp.
  273. void bst(MPCIO &mpcio,
  274. const PRACOptions &opts, char **args)
  275. {
  276. nbits_t depth=5;
  277. if (*args) {
  278. depth = atoi(*args);
  279. ++args;
  280. }
  281. size_t items = (size_t(1)<<depth)-1;
  282. if (*args) {
  283. items = atoi(*args);
  284. ++args;
  285. }
  286. MPCTIO tio(mpcio, 0, opts.num_threads);
  287. run_coroutines(tio, [&tio, depth, items] (yield_t &yield) {
  288. size_t size = size_t(1)<<depth;
  289. Duoram<Node> oram(tio.player(), size);
  290. auto A = oram.flat(tio, yield);
  291. size_t num_items = 0;
  292. RegXS root;
  293. Node c;
  294. for(size_t i = 0; i<items; i++) {
  295. newnode(c);
  296. insert(tio, yield, root, c, A, num_items);
  297. }
  298. if (depth < 10) {
  299. oram.dump();
  300. auto R = A.reconstruct();
  301. // Reconstruct the root
  302. if (tio.player() == 1) {
  303. tio.queue_peer(&root, sizeof(root));
  304. } else {
  305. RegXS peer_root;
  306. tio.recv_peer(&peer_root, sizeof(peer_root));
  307. root += peer_root;
  308. }
  309. if (tio.player() == 0) {
  310. for(size_t i=0;i<R.size();++i) {
  311. printf("\n%04lx ", i);
  312. R[i].dump();
  313. }
  314. printf("\n");
  315. pretty_print(R, root.xshare, "", false, false);
  316. }
  317. }
  318. });
  319. }