aboutsummaryrefslogtreecommitdiff
path: root/src/set/gnunet-service-set_union.c
blob: c7f30a741411ea5b7d87febffad867c3ec051668 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
/*
      This file is part of GNUnet
      Copyright (C) 2013-2015 GNUnet e.V.

      GNUnet is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
      by the Free Software Foundation; either version 3, or (at your
      option) any later version.

      GNUnet is distributed in the hope that it will be useful, but
      WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with GNUnet; see the file COPYING.  If not, write to the
      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
      Boston, MA 02110-1301, USA.
*/
/**
 * @file set/gnunet-service-set_union.c

 * @brief two-peer set operations
 * @author Florian Dold
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "gnunet-service-set.h"
#include "ibf.h"
#include "gnunet-service-set_union_strata_estimator.h"
#include "gnunet-service-set_protocol.h"
#include <gcrypt.h>


#define LOG(kind,...) GNUNET_log_from (kind, "set-union",__VA_ARGS__)


/**
 * Number of IBFs in a strata estimator.
 */
#define SE_STRATA_COUNT 32

/**
 * Size of the IBFs in the strata estimator.
 */
#define SE_IBF_SIZE 80

/**
 * The hash num parameter for the difference digests and strata estimators.
 */
#define SE_IBF_HASH_NUM 4

/**
 * Number of buckets that can be transmitted in one message.
 */
#define MAX_BUCKETS_PER_MESSAGE ((1<<15) / IBF_BUCKET_SIZE)

/**
 * The maximum size of an ibf we use is 2^(MAX_IBF_ORDER).
 * Choose this value so that computing the IBF is still cheaper
 * than transmitting all values.
 */
#define MAX_IBF_ORDER (20)

/**
 * Number of buckets used in the ibf per estimated
 * difference.
 */
#define IBF_ALPHA 4


/**
 * Current phase we are in for a union operation.
 */
enum UnionOperationPhase
{
  /**
   * We sent the request message, and expect a strata estimator.
   */
  PHASE_EXPECT_SE,

  /**
   * We sent the strata estimator, and expect an IBF. This phase is entered once
   * upon initialization and later via #PHASE_EXPECT_ELEMENTS_AND_REQUESTS.
   *
   * XXX: could use better wording.
   *
   * After receiving the complete IBF, we enter #PHASE_EXPECT_ELEMENTS
   */
  PHASE_EXPECT_IBF,

  /**
   * Continuation for multi part IBFs.
   */
  PHASE_EXPECT_IBF_CONT,

  /**
   * We are decoding an IBF.
   */
  PHASE_INVENTORY_ACTIVE,

  /**
   * The other peer is decoding the IBF we just sent.
   */
  PHASE_INVENTORY_PASSIVE,

  /**
   * The protocol is almost finished, but we still have to flush our message
   * queue and/or expect some elements.
   */
  PHASE_FINISH_CLOSING,

  /**
   * In the penultimate phase,
   * we wait until all our demands
   * are satisfied.  Then we send a done
   * message, and wait for another done message.*/
  PHASE_FINISH_WAITING,

  /**
   * In the ultimate phase, we wait until
   * our demands are satisfied and then
   * quit (sending another DONE message). */
  PHASE_DONE
};


/**
 * State of an evaluate operation with another peer.
 */
struct OperationState
{
  /**
   * Copy of the set's strata estimator at the time of
   * creation of this operation.
   */
  struct StrataEstimator *se;

  /**
   * The IBF we currently receive.
   */
  struct InvertibleBloomFilter *remote_ibf;

  /**
   * The IBF with the local set's element.
   */
  struct InvertibleBloomFilter *local_ibf;

  /**
   * Maps IBF-Keys (specific to the current salt) to elements.
   * Used as a multihashmap, the keys being the lower 32bit of the IBF-Key.
   * Colliding IBF-Keys are linked.
   */
  struct GNUNET_CONTAINER_MultiHashMap32 *key_to_element;

  /**
   * Current state of the operation.
   */
  enum UnionOperationPhase phase;

  /**
   * Did we send the client that we are done?
   */
  int client_done_sent;

  /**
   * Number of ibf buckets already received into the @a remote_ibf.
   */
  unsigned int ibf_buckets_received;

  /**
   * Hashes for elements that we have demanded from the other peer.
   */
  struct GNUNET_CONTAINER_MultiHashMap *demanded_hashes;

  /**
   * Salt that we're using for sending IBFs
   */
  uint32_t salt_send;

  /**
   * Salt for the IBF we've received and that we're currently decoding.
   */
  uint32_t salt_receive;
};


/**
 * The key entry is used to associate an ibf key with an element.
 */
struct KeyEntry
{
  /**
   * IBF key for the entry, derived from the current salt.
   */
  struct IBF_Key ibf_key;

  /**
   * The actual element associated with the key.
   *
   * Only owned by the union operation if element->operation
   * is #GNUNET_YES.
   */
  struct ElementEntry *element;
};


/**
 * Used as a closure for sending elements
 * with a specific IBF key.
 */
struct SendElementClosure
{
  /**
   * The IBF key whose matching elements should be
   * sent.
   */
  struct IBF_Key ibf_key;

  /**
   * Operation for which the elements
   * should be sent.
   */
  struct Operation *op;
};


/**
 * Extra state required for efficient set union.
 */
struct SetState
{
  /**
   * The strata estimator is only generated once for
   * each set.
   * The IBF keys are derived from the element hashes with
   * salt=0.
   */
  struct StrataEstimator *se;
};


/**
 * Iterator over hash map entries, called to
 * destroy the linked list of colliding ibf key entries.
 *
 * @param cls closure
 * @param key current key code
 * @param value value in the hash map
 * @return #GNUNET_YES if we should continue to iterate,
 *         #GNUNET_NO if not.
 */
static int
destroy_key_to_element_iter (void *cls,
                             uint32_t key,
                             void *value)
{
  struct KeyEntry *k = value;

  GNUNET_assert (NULL != k);
  if (GNUNET_YES == k->element->remote)
  {
    GNUNET_free (k->element);
    k->element = NULL;
  }
  GNUNET_free (k);
  return GNUNET_YES;
}


/**
 * Destroy the union operation.  Only things specific to the union
 * operation are destroyed.
 *
 * @param op union operation to destroy
 */
static void
union_op_cancel (struct Operation *op)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "destroying union op\n");
  /* check if the op was canceled twice */
  GNUNET_assert (NULL != op->state);
  if (NULL != op->state->remote_ibf)
  {
    ibf_destroy (op->state->remote_ibf);
    op->state->remote_ibf = NULL;
  }
  if (NULL != op->state->demanded_hashes)
  {
    GNUNET_CONTAINER_multihashmap_destroy (op->state->demanded_hashes);
    op->state->demanded_hashes = NULL;
  }
  if (NULL != op->state->local_ibf)
  {
    ibf_destroy (op->state->local_ibf);
    op->state->local_ibf = NULL;
  }
  if (NULL != op->state->se)
  {
    strata_estimator_destroy (op->state->se);
    op->state->se = NULL;
  }
  if (NULL != op->state->key_to_element)
  {
    GNUNET_CONTAINER_multihashmap32_iterate (op->state->key_to_element,
                                             &destroy_key_to_element_iter,
                                             NULL);
    GNUNET_CONTAINER_multihashmap32_destroy (op->state->key_to_element);
    op->state->key_to_element = NULL;
  }
  GNUNET_free (op->state);
  op->state = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "destroying union op done\n");
}


/**
 * Inform the client that the union operation has failed,
 * and proceed to destroy the evaluate operation.
 *
 * @param op the union operation to fail
 */
static void
fail_union_operation (struct Operation *op)
{
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_SET_ResultMessage *msg;

  LOG (GNUNET_ERROR_TYPE_ERROR,
       "union operation failed\n");
  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SET_RESULT);
  msg->result_status = htons (GNUNET_SET_STATUS_FAILURE);
  msg->request_id = htonl (op->spec->client_request_id);
  msg->element_type = htons (0);
  GNUNET_MQ_send (op->spec->set->client_mq, ev);
  _GSS_operation_destroy (op, GNUNET_YES);
}


/**
 * Derive the IBF key from a hash code and
 * a salt.
 *
 * @param src the hash code
 * @return the derived IBF key
 */
static struct IBF_Key
get_ibf_key (const struct GNUNET_HashCode *src)
{
  struct IBF_Key key;
  uint16_t salt = 0;

  GNUNET_CRYPTO_kdf (&key, sizeof (key),
                     src, sizeof *src,
                     &salt, sizeof (salt),
                     NULL, 0);
  return key;
}


/**
 * Iterator over the mapping from IBF keys to element entries.  Checks if we
 * have an element with a given GNUNET_HashCode.
 *
 * @param cls closure
 * @param key current key code
 * @param value value in the hash map
 * @return #GNUNET_YES if we should search further,
 *         #GNUNET_NO if we've found the element.
 */
static int
op_has_element_iterator (void *cls,
                         uint32_t key,
                         void *value)
{
  struct GNUNET_HashCode *element_hash = cls;
  struct KeyEntry *k = value;

  GNUNET_assert (NULL != k);
  if (0 == GNUNET_CRYPTO_hash_cmp (&k->element->element_hash,
                                   element_hash))
    return GNUNET_NO;
  return GNUNET_YES;
}


/**
 * Determine whether the given element is already in the operation's element
 * set.
 *
 * @param op operation that should be tested for 'element_hash'
 * @param element_hash hash of the element to look for
 * @return #GNUNET_YES if the element has been found, #GNUNET_NO otherwise
 */
static int
op_has_element (struct Operation *op,
                const struct GNUNET_HashCode *element_hash)
{
  int ret;
  struct IBF_Key ibf_key;

  ibf_key = get_ibf_key (element_hash);
  ret = GNUNET_CONTAINER_multihashmap32_get_multiple (op->state->key_to_element,
                                                      (uint32_t) ibf_key.key_val,
                                                      op_has_element_iterator,
                                                      (void *) element_hash);

  /* was the iteration aborted because we found the element? */
  if (GNUNET_SYSERR == ret)
    return GNUNET_YES;
  return GNUNET_NO;
}


/**
 * Insert an element into the union operation's
 * key-to-element mapping. Takes ownership of 'ee'.
 * Note that this does not insert the element in the set,
 * only in the operation's key-element mapping.
 * This is done to speed up re-tried operations, if some elements
 * were transmitted, and then the IBF fails to decode.
 *
 * XXX: clarify ownership, doesn't sound right.
 *
 * @param op the union operation
 * @param ee the element entry
 */
static void
op_register_element (struct Operation *op,
                     struct ElementEntry *ee)
{
  struct IBF_Key ibf_key;
  struct KeyEntry *k;

  ibf_key = get_ibf_key (&ee->element_hash);
  k = GNUNET_new (struct KeyEntry);
  k->element = ee;
  k->ibf_key = ibf_key;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap32_put (op->state->key_to_element,
                                                      (uint32_t) ibf_key.key_val,
                                                      k,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
}


static void
salt_key (const struct IBF_Key *k_in,
          uint32_t salt,
          struct IBF_Key *k_out)
{
  int s = salt % 64;
  uint64_t x = k_in->key_val;
  /* rotate ibf key */
  x = (x >> s) | (x << (64 - s));
  k_out->key_val = x;
}


static void
unsalt_key (const struct IBF_Key *k_in,
            uint32_t salt,
            struct IBF_Key *k_out)
{
  int s = salt % 64;
  uint64_t x = k_in->key_val;
  x = (x << s) | (x >> (64 - s));
  k_out->key_val = x;
}


/**
 * Insert a key into an ibf.
 *
 * @param cls the ibf
 * @param key unused
 * @param value the key entry to get the key from
 */
static int
prepare_ibf_iterator (void *cls,
                      uint32_t key,
                      void *value)
{
  struct Operation *op = cls;
  struct KeyEntry *ke = value;
  struct IBF_Key salted_key;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "[OP %x] inserting %lx (hash %s) into ibf\n",
       (void *) op,
       (unsigned long) ke->ibf_key.key_val,
       GNUNET_h2s (&ke->element->element_hash));
  salt_key (&ke->ibf_key, op->state->salt_send, &salted_key);
  ibf_insert (op->state->local_ibf, salted_key);
  return GNUNET_YES;
}


/**
 * Iterator for initializing the
 * key-to-element mapping of a union operation
 *
 * @param cls the union operation `struct Operation *`
 * @param key unused
 * @param value the `struct ElementEntry *` to insert
 *        into the key-to-element mapping
 * @return #GNUNET_YES (to continue iterating)
 */
static int
init_key_to_element_iterator (void *cls,
                              const struct GNUNET_HashCode *key,
                              void *value)
{
  struct Operation *op = cls;
  struct ElementEntry *ee = value;

  /* make sure that the element belongs to the set at the time
   * of creating the operation */
  if (GNUNET_NO == _GSS_is_element_of_operation (ee, op))
    return GNUNET_YES;

  GNUNET_assert (GNUNET_NO == ee->remote);

  op_register_element (op, ee);
  return GNUNET_YES;
}


/**
 * Create an ibf with the operation's elements
 * of the specified size
 *
 * @param op the union operation
 * @param size size of the ibf to create
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
static int
prepare_ibf (struct Operation *op,
             uint32_t size)
{
  if (NULL == op->state->key_to_element)
  {
    unsigned int len;

    len = GNUNET_CONTAINER_multihashmap_size (op->spec->set->content->elements);
    op->state->key_to_element = GNUNET_CONTAINER_multihashmap32_create (len + 1);
    GNUNET_CONTAINER_multihashmap_iterate (op->spec->set->content->elements,
                                           init_key_to_element_iterator, op);
  }
  if (NULL != op->state->local_ibf)
    ibf_destroy (op->state->local_ibf);
  op->state->local_ibf = ibf_create (size, SE_IBF_HASH_NUM);
  if (NULL == op->state->local_ibf)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to allocate local IBF\n");
    return GNUNET_SYSERR;
  }
  GNUNET_CONTAINER_multihashmap32_iterate (op->state->key_to_element,
                                           &prepare_ibf_iterator,
                                           op);
  return GNUNET_OK;
}


/**
 * Send an ibf of appropriate size.
 *
 * Fragments the IBF into multiple messages if necessary.
 *
 * @param op the union operation
 * @param ibf_order order of the ibf to send, size=2^order
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
static int
send_ibf (struct Operation *op,
          uint16_t ibf_order)
{
  unsigned int buckets_sent = 0;
  struct InvertibleBloomFilter *ibf;

  if (GNUNET_OK !=
      prepare_ibf (op, 1<<ibf_order))
  {
    /* allocation failed */
    return GNUNET_SYSERR;
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sending ibf of size %u\n",
       1<<ibf_order);

  {
    char name[64] = { 0 };
    snprintf (name, sizeof (name), "# sent IBF (order %u)", ibf_order);
    GNUNET_STATISTICS_update (_GSS_statistics, name, 1, GNUNET_NO);
  }

  ibf = op->state->local_ibf;

  while (buckets_sent < (1 << ibf_order))
  {
    unsigned int buckets_in_message;
    struct GNUNET_MQ_Envelope *ev;
    struct IBFMessage *msg;

    buckets_in_message = (1 << ibf_order) - buckets_sent;
    /* limit to maximum */
    if (buckets_in_message > MAX_BUCKETS_PER_MESSAGE)
      buckets_in_message = MAX_BUCKETS_PER_MESSAGE;

    ev = GNUNET_MQ_msg_extra (msg,
                              buckets_in_message * IBF_BUCKET_SIZE,
                              GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF);
    msg->reserved1 = 0;
    msg->reserved2 = 0;
    msg->order = ibf_order;
    msg->offset = htonl (buckets_sent);
    msg->salt = htonl (op->state->salt_send);
    ibf_write_slice (ibf, buckets_sent,
                     buckets_in_message, &msg[1]);
    buckets_sent += buckets_in_message;
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "ibf chunk size %u, %u/%u sent\n",
         buckets_in_message,
         buckets_sent,
         1<<ibf_order);
    GNUNET_MQ_send (op->mq, ev);
  }

  /* The other peer must decode the IBF, so
   * we're passive. */
  op->state->phase = PHASE_INVENTORY_PASSIVE;
  return GNUNET_OK;
}


/**
 * Send a strata estimator to the remote peer.
 *
 * @param op the union operation with the remote peer
 */
static void
send_strata_estimator (struct Operation *op)
{
  const struct StrataEstimator *se = op->state->se;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_MessageHeader *strata_msg;
  char *buf;
  size_t len;
  uint16_t type;

  buf = GNUNET_malloc (se->strata_count * IBF_BUCKET_SIZE * se->ibf_size);
  len = strata_estimator_write (op->state->se,
                                buf);
  if (len < se->strata_count * IBF_BUCKET_SIZE * se->ibf_size)
    type = GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SEC;
  else
    type = GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE;
  ev = GNUNET_MQ_msg_header_extra (strata_msg,
                                   len,
                                   type);
  memcpy (&strata_msg[1],
          buf,
          len);
  GNUNET_free (buf);
  GNUNET_MQ_send (op->mq,
                  ev);
  op->state->phase = PHASE_EXPECT_IBF;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sent SE, expecting IBF\n");
}


/**
 * Compute the necessary order of an ibf
 * from the size of the symmetric set difference.
 *
 * @param diff the difference
 * @return the required size of the ibf
 */
static unsigned int
get_order_from_difference (unsigned int diff)
{
  unsigned int ibf_order;

  ibf_order = 2;
  while ( (1<<ibf_order) < (IBF_ALPHA * diff) ||
          ((1<<ibf_order) < SE_IBF_HASH_NUM) )
    ibf_order++;
  if (ibf_order > MAX_IBF_ORDER)
    ibf_order = MAX_IBF_ORDER;
  return ibf_order;
}


/**
 * Handle a strata estimator from a remote peer
 *
 * @param cls the union operation
 * @param mh the message
 * @param is_compressed #GNUNET_YES if the estimator is compressed
 * @return #GNUNET_SYSERR if the tunnel should be disconnected,
 *         #GNUNET_OK otherwise
 */
static int
handle_p2p_strata_estimator (void *cls,
                             const struct GNUNET_MessageHeader *mh,
                             int is_compressed)
{
  struct Operation *op = cls;
  struct StrataEstimator *remote_se;
  int diff;
  size_t len;

  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# bytes of SE received",
                            ntohs (mh->size),
                            GNUNET_NO);

  if (op->state->phase != PHASE_EXPECT_SE)
  {
    fail_union_operation (op);
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  len = ntohs (mh->size) - sizeof (struct GNUNET_MessageHeader);
  if ( (GNUNET_NO == is_compressed) &&
       (len != SE_STRATA_COUNT * SE_IBF_SIZE * IBF_BUCKET_SIZE) )
  {
    fail_union_operation (op);
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  remote_se = strata_estimator_create (SE_STRATA_COUNT,
                                       SE_IBF_SIZE,
                                       SE_IBF_HASH_NUM);
  if (NULL == remote_se)
  {
    /* insufficient resources, fail */
    fail_union_operation (op);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      strata_estimator_read (&mh[1],
                             len,
                             is_compressed,
                             remote_se))
  {
    /* decompression failed */
    fail_union_operation (op);
    strata_estimator_destroy (remote_se);
    return GNUNET_SYSERR;
  }
  GNUNET_assert (NULL != op->state->se);
  diff = strata_estimator_difference (remote_se,
                                      op->state->se);
  strata_estimator_destroy (remote_se);
  strata_estimator_destroy (op->state->se);
  op->state->se = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "got se diff=%d, using ibf size %d\n",
       diff,
       1<<get_order_from_difference (diff));
  if (GNUNET_OK !=
      send_ibf (op,
                get_order_from_difference (diff)))
  {
    /* Internal error, best we can do is shut the connection */
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to send IBF, closing connection\n");
    fail_union_operation (op);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Iterator to send elements to a remote peer
 *
 * @param cls closure with the element key and the union operation
 * @param key ignored
 * @param value the key entry
 */
static int
send_offers_iterator (void *cls,
                      uint32_t key,
                      void *value)
{
  struct SendElementClosure *sec = cls;
  struct Operation *op = sec->op;
  struct KeyEntry *ke = value;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_MessageHeader *mh;

  /* Detect 32-bit key collision for the 64-bit IBF keys. */
  if (ke->ibf_key.key_val != sec->ibf_key.key_val)
    return GNUNET_YES;

  ev = GNUNET_MQ_msg_header_extra (mh,
                                   sizeof (struct GNUNET_HashCode),
                                   GNUNET_MESSAGE_TYPE_SET_UNION_P2P_OFFER);

  GNUNET_assert (NULL != ev);
  *(struct GNUNET_HashCode *) &mh[1] = ke->element->element_hash;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "[OP %x] sending element offer (%s) to peer\n",
       (void *) op,
       GNUNET_h2s (&ke->element->element_hash));
  GNUNET_MQ_send (op->mq, ev);
  return GNUNET_YES;
}


/**
 * Send offers (in the form of GNUNET_Hash-es) to the remote peer for the given IBF key.
 *
 * @param op union operation
 * @param ibf_key IBF key of interest
 */
static void
send_offers_for_key (struct Operation *op,
                     struct IBF_Key ibf_key)
{
  struct SendElementClosure send_cls;

  send_cls.ibf_key = ibf_key;
  send_cls.op = op;
  (void) GNUNET_CONTAINER_multihashmap32_get_multiple (op->state->key_to_element,
                                                       (uint32_t) ibf_key.key_val,
                                                       &send_offers_iterator,
                                                       &send_cls);
}


/**
 * Decode which elements are missing on each side, and
 * send the appropriate offers and inquiries.
 *
 * @param op union operation
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
static int
decode_and_send (struct Operation *op)
{
  struct IBF_Key key;
  struct IBF_Key last_key;
  int side;
  unsigned int num_decoded;
  struct InvertibleBloomFilter *diff_ibf;

  GNUNET_assert (PHASE_INVENTORY_ACTIVE == op->state->phase);

  if (GNUNET_OK !=
      prepare_ibf (op, op->state->remote_ibf->size))
  {
    GNUNET_break (0);
    /* allocation failed */
    return GNUNET_SYSERR;
  }
  diff_ibf = ibf_dup (op->state->local_ibf);
  ibf_subtract (diff_ibf, op->state->remote_ibf);

  ibf_destroy (op->state->remote_ibf);
  op->state->remote_ibf = NULL;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "decoding IBF (size=%u)\n",
       diff_ibf->size);

  num_decoded = 0;
  last_key.key_val = 0;

  while (1)
  {
    int res;
    int cycle_detected = GNUNET_NO;

    last_key = key;

    res = ibf_decode (diff_ibf, &side, &key);
    if (res == GNUNET_OK)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "decoded ibf key %lx\n",
           (unsigned long) key.key_val);
      num_decoded += 1;
      if ( (num_decoded > diff_ibf->size) ||
           (num_decoded > 1 && last_key.key_val == key.key_val) )
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "detected cyclic ibf (decoded %u/%u)\n",
             num_decoded,
             diff_ibf->size);
        cycle_detected = GNUNET_YES;
      }
    }
    if ( (GNUNET_SYSERR == res) ||
         (GNUNET_YES == cycle_detected) )
    {
      int next_order;
      next_order = 0;
      while (1<<next_order < diff_ibf->size)
        next_order++;
      next_order++;
      if (next_order <= MAX_IBF_ORDER)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "decoding failed, sending larger ibf (size %u)\n",
             1<<next_order);
        GNUNET_STATISTICS_update (_GSS_statistics,
                                  "# of IBF retries",
                                  1,
                                  GNUNET_NO);
        op->state->salt_send++;
        if (GNUNET_OK !=
            send_ibf (op, next_order))
        {
          /* Internal error, best we can do is shut the connection */
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      "Failed to send IBF, closing connection\n");
          fail_union_operation (op);
          ibf_destroy (diff_ibf);
          return GNUNET_SYSERR;
        }
      }
      else
      {
        GNUNET_STATISTICS_update (_GSS_statistics,
                                  "# of failed union operations (too large)",
                                  1,
                                  GNUNET_NO);
        // XXX: Send the whole set, element-by-element
        LOG (GNUNET_ERROR_TYPE_ERROR,
             "set union failed: reached ibf limit\n");
        fail_union_operation (op);
        ibf_destroy (diff_ibf);
        return GNUNET_SYSERR;
      }
      break;
    }
    if (GNUNET_NO == res)
    {
      struct GNUNET_MQ_Envelope *ev;

      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "transmitted all values, sending DONE\n");
      ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE);
      GNUNET_MQ_send (op->mq, ev);
      /* We now wait until we get a DONE message back
       * and then wait for our MQ to be flushed and all our
       * demands be delivered. */
      break;
    }
    if (1 == side)
    {
      struct IBF_Key unsalted_key;
      unsalt_key (&key, op->state->salt_receive, &unsalted_key);
      send_offers_for_key (op, unsalted_key);
    }
    else if (-1 == side)
    {
      struct GNUNET_MQ_Envelope *ev;
      struct InquiryMessage *msg;

      /* It may be nice to merge multiple requests, but with CADET's corking it is not worth
       * the effort additional complexity. */
      ev = GNUNET_MQ_msg_extra (msg,
                                sizeof (struct IBF_Key),
                                GNUNET_MESSAGE_TYPE_SET_UNION_P2P_INQUIRY);
      msg->salt = htonl (op->state->salt_receive);
      memcpy (&msg[1],
              &key,
              sizeof (struct IBF_Key));
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "sending element inquiry for IBF key %lx\n",
           (unsigned long) key.key_val);
      GNUNET_MQ_send (op->mq, ev);
    }
    else
    {
      GNUNET_assert (0);
    }
  }
  ibf_destroy (diff_ibf);
  return GNUNET_OK;
}


/**
 * Handle an IBF message from a remote peer.
 *
 * Reassemble the IBF from multiple pieces, and
 * process the whole IBF once possible.
 *
 * @param cls the union operation
 * @param mh the header of the message
 * @return #GNUNET_SYSERR if the tunnel should be disconnected,
 *         #GNUNET_OK otherwise
 */
static int
handle_p2p_ibf (void *cls,
                const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  const struct IBFMessage *msg;
  unsigned int buckets_in_message;

  if (ntohs (mh->size) < sizeof (struct IBFMessage))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return GNUNET_SYSERR;
  }
  msg = (const struct IBFMessage *) mh;
  if ( (op->state->phase == PHASE_INVENTORY_PASSIVE) ||
       (op->state->phase == PHASE_EXPECT_IBF) )
  {
    op->state->phase = PHASE_EXPECT_IBF_CONT;
    GNUNET_assert (NULL == op->state->remote_ibf);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Creating new ibf of size %u\n",
         1 << msg->order);
    op->state->remote_ibf = ibf_create (1<<msg->order, SE_IBF_HASH_NUM);
    op->state->salt_receive = ntohl (msg->salt);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Receiving new IBF with salt %u\n", op->state->salt_receive);
    if (NULL == op->state->remote_ibf)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to parse remote IBF, closing connection\n");
      fail_union_operation (op);
      return GNUNET_SYSERR;
    }
    op->state->ibf_buckets_received = 0;
    if (0 != ntohl (msg->offset))
    {
      GNUNET_break_op (0);
      fail_union_operation (op);
      return GNUNET_SYSERR;
    }
  }
  else if (op->state->phase == PHASE_EXPECT_IBF_CONT)
  {
    if (ntohl (msg->offset) != op->state->ibf_buckets_received)
    {
      GNUNET_break_op (0);
      fail_union_operation (op);
      return GNUNET_SYSERR;
    }
    if (1<<msg->order != op->state->remote_ibf->size)
    {
      GNUNET_break_op (0);
      fail_union_operation (op);
      return GNUNET_SYSERR;
    }
    if (ntohl (msg->salt) != op->state->salt_receive)
    {
      GNUNET_break_op (0);
      fail_union_operation (op);
      return GNUNET_SYSERR;
    }
  }
  else
  {
    GNUNET_assert (0);
  }

  buckets_in_message = (ntohs (msg->header.size) - sizeof *msg) / IBF_BUCKET_SIZE;

  if (0 == buckets_in_message)
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return GNUNET_SYSERR;
  }

  if ((ntohs (msg->header.size) - sizeof *msg) != buckets_in_message * IBF_BUCKET_SIZE)
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return GNUNET_SYSERR;
  }

  GNUNET_assert (NULL != op->state->remote_ibf);

  ibf_read_slice (&msg[1],
                  op->state->ibf_buckets_received,
                  buckets_in_message,
                  op->state->remote_ibf);
  op->state->ibf_buckets_received += buckets_in_message;

  if (op->state->ibf_buckets_received == op->state->remote_ibf->size)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "received full ibf\n");
    op->state->phase = PHASE_INVENTORY_ACTIVE;
    if (GNUNET_OK !=
        decode_and_send (op))
    {
      /* Internal error, best we can do is shut down */
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to decode IBF, closing connection\n");
      return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


/**
 * Send a result message to the client indicating
 * that there is a new element.
 *
 * @param op union operation
 * @param element element to send
 * @param status status to send with the new element
 */
static void
send_client_element (struct Operation *op,
                     struct GNUNET_SET_Element *element,
                     int status)
{
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_SET_ResultMessage *rm;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sending element (size %u) to client\n",
       element->size);
  GNUNET_assert (0 != op->spec->client_request_id);
  ev = GNUNET_MQ_msg_extra (rm, element->size, GNUNET_MESSAGE_TYPE_SET_RESULT);
  if (NULL == ev)
  {
    GNUNET_MQ_discard (ev);
    GNUNET_break (0);
    return;
  }
  rm->result_status = htons (status);
  rm->request_id = htonl (op->spec->client_request_id);
  rm->element_type = element->element_type;
  memcpy (&rm[1], element->data, element->size);
  GNUNET_MQ_send (op->spec->set->client_mq, ev);
}


/**
 * Signal to the client that the operation has finished and
 * destroy the operation.
 *
 * @param cls operation to destroy
 */
static void
send_done_and_destroy (void *cls)
{
  struct Operation *op = cls;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_SET_ResultMessage *rm;

  ev = GNUNET_MQ_msg (rm, GNUNET_MESSAGE_TYPE_SET_RESULT);
  rm->request_id = htonl (op->spec->client_request_id);
  rm->result_status = htons (GNUNET_SET_STATUS_DONE);
  rm->element_type = htons (0);
  GNUNET_MQ_send (op->spec->set->client_mq, ev);
  /* Will also call the union-specific cancel function. */
  _GSS_operation_destroy (op, GNUNET_YES);
}


static void
maybe_finish (struct Operation *op)
{
  unsigned int num_demanded;

  num_demanded = GNUNET_CONTAINER_multihashmap_size (op->state->demanded_hashes);

  if (PHASE_FINISH_WAITING == op->state->phase)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "In PHASE_FINISH_WAITING, pending %u demands\n",
         num_demanded);
    if (0 == num_demanded)
    {
      struct GNUNET_MQ_Envelope *ev;

      op->state->phase = PHASE_DONE;
      ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE);
      GNUNET_MQ_send (op->mq, ev);

      /* We now wait until the other peer closes the channel
       * after it got all elements from us. */
    }
  }
  if (PHASE_FINISH_CLOSING == op->state->phase)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "In PHASE_FINISH_CLOSING, pending %u demands\n",
         num_demanded);
    if (0 == num_demanded)
    {
      op->state->phase = PHASE_DONE;
      send_done_and_destroy (op);
    }
  }
}


/**
 * Handle an element message from a remote peer.
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_p2p_elements (void *cls,
                     const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  struct ElementEntry *ee;
  const struct GNUNET_SET_ElementMessage *emsg;
  uint16_t element_size;

  if (0 == GNUNET_CONTAINER_multihashmap_size (op->state->demanded_hashes))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  if (ntohs (mh->size) < sizeof (struct GNUNET_SET_ElementMessage))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  emsg = (const struct GNUNET_SET_ElementMessage *) mh;

  element_size = ntohs (mh->size) - sizeof (struct GNUNET_SET_ElementMessage);
  ee = GNUNET_malloc (sizeof (struct ElementEntry) + element_size);
  memcpy (&ee[1], &emsg[1], element_size);
  ee->element.size = element_size;
  ee->element.data = &ee[1];
  ee->element.element_type = ntohs (emsg->element_type);
  ee->remote = GNUNET_YES;
  GNUNET_SET_element_hash (&ee->element, &ee->element_hash);

  if (GNUNET_NO ==
      GNUNET_CONTAINER_multihashmap_remove (op->state->demanded_hashes,
                                            &ee->element_hash,
                                            NULL))
  {
    /* We got something we didn't demand, since it's not in our map. */
    GNUNET_break_op (0);
    GNUNET_free (ee);
    fail_union_operation (op);
    return;
  }

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got element (size %u, hash %s) from peer\n",
       (unsigned int) element_size,
       GNUNET_h2s (&ee->element_hash));

  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# received elements",
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# exchanged elements",
                            1,
                            GNUNET_NO);

  if (GNUNET_YES == op_has_element (op, &ee->element_hash))
  {
    /* Got repeated element.  Should not happen since
     * we track demands. */
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# repeated elements",
                              1,
                              GNUNET_NO);
    GNUNET_free (ee);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Registering new element from remote peer\n");
    op_register_element (op, ee);
    /* only send results immediately if the client wants it */
    switch (op->spec->result_mode)
    {
      case GNUNET_SET_RESULT_ADDED:
        send_client_element (op, &ee->element, GNUNET_SET_STATUS_OK);
        break;
      case GNUNET_SET_RESULT_SYMMETRIC:
        send_client_element (op, &ee->element, GNUNET_SET_STATUS_ADD_LOCAL);
        break;
      default:
        /* Result mode not supported, should have been caught earlier. */
        GNUNET_break (0);
        break;
    }
  }

  maybe_finish (op);
}


/**
 * Send offers (for GNUNET_Hash-es) in response
 * to inquiries (for IBF_Key-s).
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_p2p_inquiry (void *cls,
                    const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  const struct IBF_Key *ibf_key;
  unsigned int num_keys;
  struct InquiryMessage *msg;

  /* look up elements and send them */
  if (op->state->phase != PHASE_INVENTORY_PASSIVE)
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  num_keys = (ntohs (mh->size) - sizeof (struct InquiryMessage))
      / sizeof (struct IBF_Key);
  if ((ntohs (mh->size) - sizeof (struct InquiryMessage))
      != num_keys * sizeof (struct IBF_Key))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  msg = (struct InquiryMessage *) mh;

  ibf_key = (const struct IBF_Key *) &msg[1];
  while (0 != num_keys--)
  {
    struct IBF_Key unsalted_key;
    unsalt_key (ibf_key, ntohl (msg->salt), &unsalted_key);
    send_offers_for_key (op, unsalted_key);
    ibf_key++;
  }
}


/**
 * FIXME
 */
static void
handle_p2p_demand (void *cls,
                   const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  struct ElementEntry *ee;
  struct GNUNET_SET_ElementMessage *emsg;
  const struct GNUNET_HashCode *hash;
  unsigned int num_hashes;
  struct GNUNET_MQ_Envelope *ev;

  num_hashes = (ntohs (mh->size) - sizeof (struct GNUNET_MessageHeader))
    / sizeof (struct GNUNET_HashCode);
  if ((ntohs (mh->size) - sizeof (struct GNUNET_MessageHeader))
      != num_hashes * sizeof (struct GNUNET_HashCode))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  for (hash = (const struct GNUNET_HashCode *) &mh[1];
       num_hashes > 0;
       hash++, num_hashes--)
  {
    ee = GNUNET_CONTAINER_multihashmap_get (op->spec->set->content->elements, hash);
    if (NULL == ee)
    {
      /* Demand for non-existing element. */
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }
    if (GNUNET_NO == _GSS_is_element_of_operation (ee, op))
    {
      /* Probably confused lazily copied sets. */
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }
    ev = GNUNET_MQ_msg_extra (emsg, ee->element.size, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS);
    memcpy (&emsg[1], ee->element.data, ee->element.size);
    emsg->reserved = htons (0);
    emsg->element_type = htons (ee->element.element_type);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "[OP %x] Sending demanded element (size %u, hash %s) to peer\n",
         (void *) op,
         (unsigned int) ee->element.size,
         GNUNET_h2s (&ee->element_hash));
    GNUNET_MQ_send (op->mq, ev);
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# exchanged elements",
                              1,
                              GNUNET_NO);

    switch (op->spec->result_mode)
    {
      case GNUNET_SET_RESULT_ADDED:
        /* Nothing to do. */
        break;
      case GNUNET_SET_RESULT_SYMMETRIC:
        send_client_element (op, &ee->element, GNUNET_SET_STATUS_ADD_REMOTE);
        break;
      default:
        /* Result mode not supported, should have been caught earlier. */
        GNUNET_break (0);
        break;
    }
  }
}


/**
 * Handle offers (of GNUNET_HashCode-s) and
 * respond with demands (of GNUNET_HashCode-s).
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_p2p_offer (void *cls,
                    const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  const struct GNUNET_HashCode *hash;
  unsigned int num_hashes;

  /* look up elements and send them */
  if ( (op->state->phase != PHASE_INVENTORY_PASSIVE) &&
       (op->state->phase != PHASE_INVENTORY_ACTIVE))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  num_hashes = (ntohs (mh->size) - sizeof (struct GNUNET_MessageHeader))
    / sizeof (struct GNUNET_HashCode);
  if ((ntohs (mh->size) - sizeof (struct GNUNET_MessageHeader))
      != num_hashes * sizeof (struct GNUNET_HashCode))
  {
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  for (hash = (const struct GNUNET_HashCode *) &mh[1];
       num_hashes > 0;
       hash++, num_hashes--)
  {
    struct ElementEntry *ee;
    struct GNUNET_MessageHeader *demands;
    struct GNUNET_MQ_Envelope *ev;

    ee = GNUNET_CONTAINER_multihashmap_get (op->spec->set->content->elements,
                                            hash);
    if (NULL != ee)
      if (GNUNET_YES == _GSS_is_element_of_operation (ee, op))
        continue;

    if (GNUNET_YES ==
        GNUNET_CONTAINER_multihashmap_contains (op->state->demanded_hashes,
                                                hash))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Skipped sending duplicate demand\n");
      continue;
    }

    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CONTAINER_multihashmap_put (op->state->demanded_hashes,
                                                      hash,
                                                      NULL,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "[OP %x] Requesting element (hash %s)\n",
         (void *) op, GNUNET_h2s (hash));
    ev = GNUNET_MQ_msg_header_extra (demands,
                                     sizeof (struct GNUNET_HashCode),
                                     GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DEMAND);
    *(struct GNUNET_HashCode *) &demands[1] = *hash;
    GNUNET_MQ_send (op->mq, ev);
  }
}


/**
 * Handle a done message from a remote peer
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_p2p_done (void *cls,
                 const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;

  if (op->state->phase == PHASE_INVENTORY_PASSIVE)
  {
    /* We got all requests, but still have to send our elements in response. */

    op->state->phase = PHASE_FINISH_WAITING;

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "got DONE (as passive partner), waiting for our demands to be satisfied\n");
    /* The active peer is done sending offers
     * and inquiries.  This means that all
     * our responses to that (demands and offers)
     * must be in flight (queued or in mesh).
     *
     * We should notify the active peer once
     * all our demands are satisfied, so that the active
     * peer can quit if we gave him everything.
     */
    maybe_finish (op);
    return;
  }
  if (op->state->phase == PHASE_INVENTORY_ACTIVE)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "got DONE (as active partner), waiting to finish\n");
    /* All demands of the other peer are satisfied,
     * and we processed all offers, thus we know
     * exactly what our demands must be.
     *
     * We'll close the channel
     * to the other peer once our demands are met.
     */
    op->state->phase = PHASE_FINISH_CLOSING;
    maybe_finish (op);
    return;
  }
  GNUNET_break_op (0);
  fail_union_operation (op);
}


/**
 * Initiate operation to evaluate a set union with a remote peer.
 *
 * @param op operation to perform (to be initialized)
 * @param opaque_context message to be transmitted to the listener
 *        to convince him to accept, may be NULL
 */
static void
union_evaluate (struct Operation *op,
                const struct GNUNET_MessageHeader *opaque_context)
{
  struct GNUNET_MQ_Envelope *ev;
  struct OperationRequestMessage *msg;

  GNUNET_assert (NULL == op->state);
  op->state = GNUNET_new (struct OperationState);
  op->state->demanded_hashes = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
  /* copy the current generation's strata estimator for this operation */
  op->state->se = strata_estimator_dup (op->spec->set->state->se);
  /* we started the operation, thus we have to send the operation request */
  op->state->phase = PHASE_EXPECT_SE;
  op->state->salt_receive = op->state->salt_send = 42;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Initiating union operation evaluation\n");
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of total union operations",
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of initiated union operations",
                            1,
                            GNUNET_NO);
  ev = GNUNET_MQ_msg_nested_mh (msg,
                                GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST,
                                opaque_context);
  if (NULL == ev)
  {
    /* the context message is too large */
    GNUNET_break (0);
    GNUNET_SERVER_client_disconnect (op->spec->set->client);
    return;
  }
  msg->operation = htonl (GNUNET_SET_OPERATION_UNION);
  msg->app_id = op->spec->app_id;
  GNUNET_MQ_send (op->mq,
                  ev);

  if (NULL != opaque_context)
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "sent op request with context message\n");
  else
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "sent op request without context message\n");
}


/**
 * Accept an union operation request from a remote peer.
 * Only initializes the private operation state.
 *
 * @param op operation that will be accepted as a union operation
 */
static void
union_accept (struct Operation *op)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "accepting set union operation\n");
  GNUNET_assert (NULL == op->state);

  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of accepted union operations",
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of total union operations",
                            1,
                            GNUNET_NO);

  op->state = GNUNET_new (struct OperationState);
  op->state->se = strata_estimator_dup (op->spec->set->state->se);
  op->state->demanded_hashes = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
  op->state->salt_receive = op->state->salt_send = 42;
  /* kick off the operation */
  send_strata_estimator (op);
}


/**
 * Create a new set supporting the union operation
 *
 * We maintain one strata estimator per set and then manipulate it over the
 * lifetime of the set, as recreating a strata estimator would be expensive.
 *
 * @return the newly created set, NULL on error
 */
static struct SetState *
union_set_create (void)
{
  struct SetState *set_state;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "union set created\n");
  set_state = GNUNET_new (struct SetState);
  set_state->se = strata_estimator_create (SE_STRATA_COUNT,
                                           SE_IBF_SIZE, SE_IBF_HASH_NUM);
  if (NULL == set_state->se)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to allocate strata estimator\n");
    GNUNET_free (set_state);
    return NULL;
  }
  return set_state;
}


/**
 * Add the element from the given element message to the set.
 *
 * @param set_state state of the set want to add to
 * @param ee the element to add to the set
 */
static void
union_add (struct SetState *set_state, struct ElementEntry *ee)
{
  strata_estimator_insert (set_state->se,
                           get_ibf_key (&ee->element_hash));
}


/**
 * Remove the element given in the element message from the set.
 * Only marks the element as removed, so that older set operations can still exchange it.
 *
 * @param set_state state of the set to remove from
 * @param ee set element to remove
 */
static void
union_remove (struct SetState *set_state, struct ElementEntry *ee)
{
  strata_estimator_remove (set_state->se,
                           get_ibf_key (&ee->element_hash));
}


/**
 * Destroy a set that supports the union operation.
 *
 * @param set_state the set to destroy
 */
static void
union_set_destroy (struct SetState *set_state)
{
  if (NULL != set_state->se)
  {
    strata_estimator_destroy (set_state->se);
    set_state->se = NULL;
  }
  GNUNET_free (set_state);
}


/**
 * Dispatch messages for a union operation.
 *
 * @param op the state of the union evaluate operation
 * @param mh the received message
 * @return #GNUNET_SYSERR if the tunnel should be disconnected,
 *         #GNUNET_OK otherwise
 */
int
union_handle_p2p_message (struct Operation *op,
                          const struct GNUNET_MessageHeader *mh)
{
  //LOG (GNUNET_ERROR_TYPE_DEBUG,
  //            "received p2p message (t: %u, s: %u)\n",
  //            ntohs (mh->type),
  //            ntohs (mh->size));
  switch (ntohs (mh->type))
  {
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF:
      return handle_p2p_ibf (op, mh);
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE:
      return handle_p2p_strata_estimator (op, mh, GNUNET_NO);
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SEC:
      return handle_p2p_strata_estimator (op, mh, GNUNET_YES);
    case GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS:
      handle_p2p_elements (op, mh);
      break;
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_INQUIRY:
      handle_p2p_inquiry (op, mh);
      break;
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE:
      handle_p2p_done (op, mh);
      break;
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_OFFER:
      handle_p2p_offer (op, mh);
      break;
    case GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DEMAND:
      handle_p2p_demand (op, mh);
      break;
    default:
      /* Something wrong with cadet's message handlers? */
      GNUNET_assert (0);
  }
  return GNUNET_OK;
}


/**
 * Handler for peer-disconnects, notifies the client
 * about the aborted operation in case the op was not concluded.
 *
 * @param op the destroyed operation
 */
static void
union_peer_disconnect (struct Operation *op)
{
  if (PHASE_DONE != op->state->phase)
  {
    struct GNUNET_MQ_Envelope *ev;
    struct GNUNET_SET_ResultMessage *msg;

    ev = GNUNET_MQ_msg (msg,
                        GNUNET_MESSAGE_TYPE_SET_RESULT);
    msg->request_id = htonl (op->spec->client_request_id);
    msg->result_status = htons (GNUNET_SET_STATUS_FAILURE);
    msg->element_type = htons (0);
    GNUNET_MQ_send (op->spec->set->client_mq,
                    ev);
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "other peer disconnected prematurely, phase %u\n",
         op->state->phase);
    _GSS_operation_destroy (op,
                            GNUNET_YES);
    return;
  }
  // else: the session has already been concluded
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "other peer disconnected (finished)\n");
  if (GNUNET_NO == op->state->client_done_sent)
    send_done_and_destroy (op);
}


/**
 * Copy union-specific set state.
 *
 * @param set source set for copying the union state
 * @return a copy of the union-specific set state
 */
static struct SetState *
union_copy_state (struct Set *set)
{
  struct SetState *new_state;

  new_state = GNUNET_new (struct SetState);
  GNUNET_assert ( (NULL != set->state) && (NULL != set->state->se) );
  new_state->se = strata_estimator_dup (set->state->se);

  return new_state;
}


/**
 * Get the table with implementing functions for
 * set union.
 *
 * @return the operation specific VTable
 */
const struct SetVT *
_GSS_union_vt ()
{
  static const struct SetVT union_vt = {
    .create = &union_set_create,
    .msg_handler = &union_handle_p2p_message,
    .add = &union_add,
    .remove = &union_remove,
    .destroy_set = &union_set_destroy,
    .evaluate = &union_evaluate,
    .accept = &union_accept,
    .peer_disconnect = &union_peer_disconnect,
    .cancel = &union_op_cancel,
    .copy_state = &union_copy_state,
  };

  return &union_vt;
}