aboutsummaryrefslogtreecommitdiff
path: root/src/setu/gnunet-service-setu.c
blob: 339d347f83cc777270553282bafc4cd26ca4b8d9 (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
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
/*
      This file is part of GNUnet
      Copyright (C) 2013-2017, 2020 GNUnet e.V.

      GNUnet is free software: you can redistribute it and/or modify it
      under the terms of the GNU Affero General Public License as published
      by the Free Software Foundation, either version 3 of the License,
      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
      Affero General Public License for more details.

      You should have received a copy of the GNU Affero General Public License
      along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
 */
/**
 * @file setu/gnunet-service-setu.c
 * @brief set union operation
 * @author Florian Dold
 * @author Christian Grothoff
 * @author Elias Summermatter
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "ibf.h"
#include "gnunet_protocols.h"
#include "gnunet_applications.h"
#include "gnunet_cadet_service.h"
#include "gnunet-service-setu_strata_estimator.h"
#include "gnunet-service-setu_protocol.h"
#include "gnunet_statistics_service.h"
#include <gcrypt.h>
#include "gnunet_setu_service.h"
#include "setu.h"

#define LOG(kind, ...) GNUNET_log_from (kind, "setu", __VA_ARGS__)

/**
 * How long do we hold on to an incoming channel if there is
 * no local listener before giving up?
 */
#define INCOMING_CHANNEL_TIMEOUT GNUNET_TIME_UNIT_MINUTES

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


/**
 * Primes for all 4 different strata estimators 61,67,71,73,79,83,89,97 348
 * Based on the bsc thesis of Elias Summermatter (2021)
 */
#define SE_IBFS_TOTAL_SIZE 632

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

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

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


/**
 * Minimal size of an ibf
 * Based on the bsc thesis of Elias Summermatter (2021)
 */
#define IBF_MIN_SIZE 37

/**
 * AVG RTT for differential sync when k=2 and Factor = 2
 * Based on the bsc thesis of Elias Summermatter (2021)
 */
#define DIFFERENTIAL_RTT_MEAN 3.65145

/**
 * Security level used for byzantine checks (2^80)
 */

#define SECURITY_LEVEL 80

/**
 * Is the estimated probability for a new round this values
 * is based on the bsc thesis of Elias Summermatter (2021)
 */

#define PROBABILITY_FOR_NEW_ROUND 0.15

/**
 * Measure the performance in a csv
 */

#define MEASURE_PERFORMANCE 0


/**
 * 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.
   * XXX: repurposed to also expect a "request full set" message, should be renamed
   *
   * After receiving the complete IBF, we enter #PHASE_EXPECT_ELEMENTS
   */
  PHASE_EXPECT_IBF,

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

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

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

  /**
   * 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_FINISHED,

  /**
   * After sending the full set, wait for responses with the elements
   * that the local peer is missing.
   */
  PHASE_FULL_SENDING,

  /**
   * Phase that receives full set first and then sends elements that are
   * the local peer missing
   */
  PHASE_FULL_RECEIVING
};

/**
 * Different modes of operations
 */

enum MODE_OF_OPERATION
{
  /**
   * Mode just synchronizes the difference between sets
   */
  DIFFERENTIAL_SYNC,

  /**
  * Mode send full set sending local set first
  */
  FULL_SYNC_LOCAL_SENDING_FIRST,

  /**
  * Mode request full set from remote peer
  */
  FULL_SYNC_REMOTE_SENDING_FIRST
};


/**
 * Information about an element element in the set.  All elements are
 * stored in a hash-table from their hash-code to their `struct
 * Element`, so that the remove and add operations are reasonably
 * fast.
 */
struct ElementEntry
{
  /**
   * The actual element. The data for the element
   * should be allocated at the end of this struct.
   */
  struct GNUNET_SETU_Element element;

  /**
   * Hash of the element.  For set union: Will be used to derive the
   * different IBF keys for different salts.
   */
  struct GNUNET_HashCode element_hash;

  /**
   * First generation that includes this element.
   */
  unsigned int generation;

  /**
   * #GNUNET_YES if the element is a remote element, and does not belong
   * to the operation's set.
   */
  int remote;
};


/**
 * A listener is inhabited by a client, and waits for evaluation
 * requests from remote peers.
 */
struct Listener;


/**
 * A set that supports a specific operation with other peers.
 */
struct Set;


/**
 * State we keep per client.
 */
struct ClientState
{
  /**
   * Set, if associated with the client, otherwise NULL.
   */
  struct Set *set;

  /**
   * Listener, if associated with the client, otherwise NULL.
   */
  struct Listener *listener;

  /**
   * Client handle.
   */
  struct GNUNET_SERVICE_Client *client;

  /**
   * Message queue.
   */
  struct GNUNET_MQ_Handle *mq;
};


/**
 * Operation context used to execute a set operation.
 */
struct Operation
{

  /**
   * The identity of the requesting peer.  Needs to
   * be stored here as the op spec might not have been created yet.
   */
  struct GNUNET_PeerIdentity peer;

  /**
   * Initial size of our set, just before the operation started.
   */
  uint64_t initial_size;

  /**
   * Kept in a DLL of the listener, if @e listener is non-NULL.
   */
  struct Operation *next;

  /**
   * Kept in a DLL of the listener, if @e listener is non-NULL.
   */
  struct Operation *prev;

  /**
   * Channel to the peer.
   */
  struct GNUNET_CADET_Channel *channel;

  /**
   * Port this operation runs on.
   */
  struct Listener *listener;

  /**
   * Message queue for the channel.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Context message, may be NULL.
   */
  struct GNUNET_MessageHeader *context_msg;

  /**
   * Set associated with the operation, NULL until the spec has been
   * associated with a set.
   */
  struct Set *set;

  /**
   * Copy of the set's strata estimator at the time of
   * creation of this operation.
   */
  struct MultiStrataEstimator *se;

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

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

  /**
   * Maps unsalted IBF-Keys 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;

  /**
   * Timeout task, if the incoming peer has not been accepted
   * after the timeout, it will be disconnected.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;

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

  /**
   * 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.
   */
  uint64_t ibf_buckets_received;

  /**
   * 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;

  /**
   * Number of elements we received from the other peer
   * that were not in the local set yet.
   */
  uint32_t received_fresh;

  /**
   * Total number of elements received from the other peer.
   */
  uint32_t received_total;

  /**
   * Salt to use for the operation.
   */
  uint32_t salt;

  /**
   * Remote peers element count
   */
  uint32_t remote_element_count;

  /**
   * ID used to identify an operation between service and client
   */
  uint32_t client_request_id;

  /**
   * Always use delta operation instead of sending full sets,
   * even it it's less efficient.
   */
  int force_delta;

  /**
   * Always send full sets, even if delta operations would
   * be more efficient.
   */
  int force_full;

  /**
   * #GNUNET_YES to fail operations where Byzantine faults
   * are suspected
   */
  int byzantine;

  /**
   * #GNUNET_YES to also send back set elements we are sending to
   * the remote peer.
   */
  int symmetric;

  /**
   * Lower bound for the set size, used only when
   * byzantine mode is enabled.
   */
  uint64_t byzantine_lower_bound;

  /**
   * Unique request id for the request from a remote peer, sent to the
   * client, which will accept or reject the request.  Set to '0' iff
   * the request has not been suggested yet.
   */
  uint32_t suggest_id;

  /**
   * Generation in which the operation handle
   * was created.
   */
  unsigned int generation_created;


  /**
  * User defined Bandwidth Round Trips Tradeoff
  */
  uint64_t rtt_bandwidth_tradeoff;


  /**
  * Number of Element per bucket  in IBF
  */
  uint8_t ibf_number_buckets_per_element;


  /**
   * Set difference is multiplied with this factor
   * to gennerate large enough IBF
   */
  uint8_t ibf_bucket_number_factor;

  /**
   *  Defines which site a client is
   *  0 = Initiating peer
   *  1 = Receiving peer
   */
  uint8_t peer_site;


  /**
   * Local peer element count
   */
  uint64_t local_element_count;

  /**
   * Mode of operation that was chosen by the algorithm
   */
  uint8_t mode_of_operation;

  /**
   * Hashmap to keep track of the send/received messages
   */
  struct GNUNET_CONTAINER_MultiHashMap *message_control_flow;

  /**
  * Hashmap to keep track of the send/received inquiries (ibf keys)
  */
  struct GNUNET_CONTAINER_MultiHashMap *inquiries_sent;


  /**
  * Total size of local set
  */
  uint64_t total_elements_size_local;

  /**
   * Limit of number of elements in set
   */
  uint64_t byzantine_upper_bound;

  /**
   * is the count of already passed differential sync iterations
   */
  uint8_t differential_sync_iterations;

  /**
   * Estimated or committed set difference at the start
  */
  uint64_t remote_set_diff;

  /**
  * Estimated or committed set difference at the start
  */
  uint64_t local_set_diff;

  /**
   * Boolean to enforce an active passive switch
   */
  bool active_passive_switch_required;
};


/**
 * SetContent stores the actual set elements, which may be shared by
 * multiple generations derived from one set.
 */
struct SetContent
{
  /**
   * Maps `struct GNUNET_HashCode *` to `struct ElementEntry *`.
   */
  struct GNUNET_CONTAINER_MultiHashMap *elements;

  /**
   * Maps `struct GNUNET_HashCode *` to `struct ElementEntry *` randomized.
   */
  struct GNUNET_CONTAINER_MultiHashMap *elements_randomized;

  /**
   * Salt to construct the randomized element map
   */
  uint64_t elements_randomized_salt;

  /**
   * Number of references to the content.
   */
  unsigned int refcount;

  /**
   * FIXME: document!
   */
  unsigned int latest_generation;

  /**
   * Number of concurrently active iterators.
   */
  int iterator_count;
};


/**
 * A set that supports a specific operation with other peers.
 */
struct Set
{
  /**
   * Sets are held in a doubly linked list (in `sets_head` and `sets_tail`).
   */
  struct Set *next;

  /**
   * Sets are held in a doubly linked list.
   */
  struct Set *prev;

  /**
   * Client that owns the set.  Only one client may own a set,
   * and there can only be one set per client.
   */
  struct ClientState *cs;

  /**
   * Content, possibly shared by multiple sets,
   * and thus reference counted.
   */
  struct SetContent *content;

  /**
   * The strata estimator is only generated once for each set.  The IBF keys
   * are derived from the element hashes with salt=0.
   */
  struct MultiStrataEstimator *se;

  /**
   * Evaluate operations are held in a linked list.
   */
  struct Operation *ops_head;

  /**
   * Evaluate operations are held in a linked list.
   */
  struct Operation *ops_tail;

  /**
   * Current generation, that is, number of previously executed
   * operations and lazy copies on the underlying set content.
   */
  unsigned int current_generation;

};


/**
 * 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;

  /**
   * Did we receive this element?  Even if element->is_foreign is false, we
   * might have received the element, so this indicates that the other peer
   * has it.
   */
  int received;
};


/**
 * 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;
};


/**
 * A listener is inhabited by a client, and waits for evaluation
 * requests from remote peers.
 */
struct Listener
{
  /**
   * Listeners are held in a doubly linked list.
   */
  struct Listener *next;

  /**
   * Listeners are held in a doubly linked list.
   */
  struct Listener *prev;

  /**
   * Head of DLL of operations this listener is responsible for.
   * Once the client has accepted/declined the operation, the
   * operation is moved to the respective set's operation DLLS.
   */
  struct Operation *op_head;

  /**
   * Tail of DLL of operations this listener is responsible for.
   * Once the client has accepted/declined the operation, the
   * operation is moved to the respective set's operation DLLS.
   */
  struct Operation *op_tail;

  /**
   * Client that owns the listener.
   * Only one client may own a listener.
   */
  struct ClientState *cs;

  /**
   * The port we are listening on with CADET.
   */
  struct GNUNET_CADET_Port *open_port;

  /**
   * Application ID for the operation, used to distinguish
   * multiple operations of the same type with the same peer.
   */
  struct GNUNET_HashCode app_id;

};


/**
 * Handle to the cadet service, used to listen for and connect to
 * remote peers.
 */
static struct GNUNET_CADET_Handle *cadet;

/**
 * Statistics handle.
 */
static struct GNUNET_STATISTICS_Handle *_GSS_statistics;

/**
 * Listeners are held in a doubly linked list.
 */
static struct Listener *listener_head;

/**
 * Listeners are held in a doubly linked list.
 */
static struct Listener *listener_tail;

/**
 * Number of active clients.
 */
static unsigned int num_clients;

/**
 * Are we in shutdown? if #GNUNET_YES and the number of clients
 * drops to zero, disconnect from CADET.
 */
static int in_shutdown;

/**
 * Counter for allocating unique IDs for clients, used to identify incoming
 * operation requests from remote peers, that the client can choose to accept
 * or refuse.  0 must not be used (reserved for uninitialized).
 */
static uint32_t suggest_id;

#if MEASURE_PERFORMANCE
/**
 * Handles configuration file for setu performance test
 *
 */
static const struct GNUNET_CONFIGURATION_Handle *setu_cfg;


/**
 * Stores the performance data for induvidual message
 */


struct perf_num_send_received_msg
{
  uint64_t sent;
  uint64_t sent_var_bytes;
  uint64_t received;
  uint64_t received_var_bytes;
};

/**
 *  Main struct to measure performance (data/rtts)
 */
struct per_store_struct
{
  struct perf_num_send_received_msg operation_request;
  struct perf_num_send_received_msg se;
  struct perf_num_send_received_msg request_full;
  struct perf_num_send_received_msg element_full;
  struct perf_num_send_received_msg full_done;
  struct perf_num_send_received_msg ibf;
  struct perf_num_send_received_msg inquery;
  struct perf_num_send_received_msg element;
  struct perf_num_send_received_msg demand;
  struct perf_num_send_received_msg offer;
  struct perf_num_send_received_msg done;
  struct perf_num_send_received_msg over;
  uint64_t se_diff;
  uint64_t se_diff_remote;
  uint64_t se_diff_local;
  uint64_t active_passive_switches;
  uint8_t mode_of_operation;
};

struct per_store_struct perf_store;
#endif

/**
 * Different states to control the messages flow in differential mode
 */

enum MESSAGE_CONTROL_FLOW_STATE
{
  /**
   *  Initial message state
   */
  MSG_CFS_UNINITIALIZED,

  /**
   *  Track that a message has been sent
   */
  MSG_CFS_SENT,

  /**
   *  Track that receiving this message is expected
   */
  MSG_CFS_EXPECTED,

  /**
   * Track that message has been received
   */
  MSG_CFS_RECEIVED,
};

/**
 * Message types to track in message control flow
 */

enum MESSAGE_TYPE
{
  /**
   * Offer message type
   */
  OFFER_MESSAGE,

  /**
   * Demand message type
   */
  DEMAND_MESSAGE,

  /**
   * Element message type
   */
  ELEMENT_MESSAGE,
};


/**
 * Struct to tracked messages in message control flow
 */
struct messageControlFlowElement
{
  /**
   * Track the message control state of the offer message
   */
  enum MESSAGE_CONTROL_FLOW_STATE offer;
  /**
   * Track the message control state of the demand message
   */
  enum MESSAGE_CONTROL_FLOW_STATE demand;
  /**
   * Track the message control state of the element message
   */
  enum MESSAGE_CONTROL_FLOW_STATE element;
};


#if MEASURE_PERFORMANCE

/**
 * Loads different configuration to perform performance tests
 *
 * @param op operation handle
 */
static void
load_config (struct Operation *op)
{
  long long number;
  float fl;

  setu_cfg = GNUNET_CONFIGURATION_create ();
  GNUNET_CONFIGURATION_load (setu_cfg,
                             "perf_setu.conf");
  GNUNET_CONFIGURATION_get_value_float (setu_cfg,
                                        "IBF",
                                        "BUCKET_NUMBER_FACTOR",
                                        &fl);
  op->ibf_bucket_number_factor = fl;
  GNUNET_CONFIGURATION_get_value_number (setu_cfg,
                                         "IBF",
                                         "NUMBER_PER_BUCKET",
                                         &number);
  op->ibf_number_buckets_per_element = number;
  GNUNET_CONFIGURATION_get_value_number (setu_cfg,
                                         "PERFORMANCE",
                                         "TRADEOFF",
                                         &number);
  op->rtt_bandwidth_tradeoff = number;
  GNUNET_CONFIGURATION_get_value_number (setu_cfg,
                                         "BOUNDARIES",
                                         "UPPER_ELEMENT",
                                         &number);
  op->byzantine_upper_bound = number;
  op->peer_site = 0;
}


/**
 * Function to calculate total bytes used for performance measurement
 * @param size
 * @param perf_num_send_received_msg
 * @return bytes used
 */
static int
sum_sent_received_bytes (uint64_t size,
                         struct perf_num_send_received_msg
                         perf_num_send_received_msg)
{
  return (size * perf_num_send_received_msg.sent)
         + (size * perf_num_send_received_msg.received)
         + perf_num_send_received_msg.sent_var_bytes
         + perf_num_send_received_msg.received_var_bytes;
}


/**
 * Function that calculates the perfmance values and writes them down
 */
static void
calculate_perf_store ()
{

  /**
   *  Calculate RTT of init phase normally always 1
   */
  float rtt = 1;
  int bytes_transmitted = 0;

  /**
   *  Calculate RGNUNET_SETU_AcceptMessageRT of Fullsync normally 1 or 1.5 depending
   */
  if ((perf_store.element_full.received != 0) ||
      (perf_store.element_full.sent != 0)
      )
    rtt += 1;

  if ((perf_store.request_full.received != 0) ||
      (perf_store.request_full.sent != 0)
      )
    rtt += 0.5;

  /**
   *  In case of a differential sync 3 rtt's are needed.
   *  for every active/passive switch additional 3.5 rtt's are used
   */
  if ((perf_store.element.received != 0) ||
      (perf_store.element.sent != 0))
  {
    int iterations = perf_store.active_passive_switches;

    if (iterations > 0)
      rtt += iterations * 0.5;
    rtt +=  2.5;
  }


  /**
   * Calculate data sended size
   */
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       GNUNET_SETU_ResultMessage),
                                                perf_store.request_full);

  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       GNUNET_SETU_ElementMessage),
                                                perf_store.element_full);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       GNUNET_SETU_ElementMessage),
                                                perf_store.element);
  // bytes_transmitted += sum_sent_received_bytes(sizeof(GNUNET_MESSAGE_TYPE_SETU_P2P_OPERATION_REQUEST), perf_store.operation_request);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       StrataEstimatorMessage),
                                                perf_store.se);
  bytes_transmitted += sum_sent_received_bytes (4, perf_store.full_done);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct IBFMessage),
                                                perf_store.ibf);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct InquiryMessage),
                                                perf_store.inquery);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       GNUNET_MessageHeader),
                                                perf_store.demand);
  bytes_transmitted += sum_sent_received_bytes (sizeof(struct
                                                       GNUNET_MessageHeader),
                                                perf_store.offer);
  bytes_transmitted += sum_sent_received_bytes (4, perf_store.done);

  /**
   * Write IBF failure rate for different BUCKET_NUMBER_FACTOR
   */
  float factor;
  GNUNET_CONFIGURATION_get_value_float (setu_cfg,"IBF", "BUCKET_NUMBER_FACTOR",
                                        &factor);
  long long num_per_bucket;
  GNUNET_CONFIGURATION_get_value_number (setu_cfg,"IBF", "NUMBER_PER_BUCKET",
                                         &num_per_bucket);


  int decoded = 0;
  if (perf_store.active_passive_switches == 0)
    decoded = 1;
  int ibf_bytes_transmitted = sum_sent_received_bytes (sizeof(struct
                                                              IBFMessage),
                                                       perf_store.ibf);

  FILE *out1 = fopen ("perf_data.csv", "a");
  fprintf (out1, "%d,%f,%d,%d,%f,%d,%d,%d,%d,%d\n",num_per_bucket,factor,
           decoded,ibf_bytes_transmitted,rtt,perf_store.se_diff,
           bytes_transmitted,
           perf_store.se_diff_local,perf_store.se_diff_remote,
           perf_store.mode_of_operation);
  fclose (out1);

}


#endif
/**
 * Function that chooses the optimal mode of operation depending on
 * operation parameters.
 * @param avg_element_size
 * @param local_set_size
 * @param remote_set_size
 * @param est_set_diff_remote
 * @param est_set_diff_local
 * @param bandwith_latency_tradeoff
 * @param ibf_bucket_number_factor
 * @return calcuated mode of operation
 */
static uint8_t
estimate_best_mode_of_operation (uint64_t avg_element_size,
                                 uint64_t local_set_size,
                                 uint64_t remote_set_size,
                                 uint64_t est_set_diff_remote,
                                 uint64_t est_set_diff_local,
                                 uint64_t bandwith_latency_tradeoff,
                                 uint64_t ibf_bucket_number_factor)
{

  /*
   * In case of initial sync fall to predefined states
   */

  if (0 == local_set_size)
    return FULL_SYNC_REMOTE_SENDING_FIRST;
  if (0 == remote_set_size)
    return FULL_SYNC_LOCAL_SENDING_FIRST;

  /*
  * Calculate bytes for full Sync
  */

  uint8_t sizeof_full_done_header = 4;
  uint8_t sizeof_done_header = 4;
  uint8_t rtt_min_full = 2;
  uint8_t sizeof_request_full = 4;
  uint64_t estimated_total_diff = (est_set_diff_remote + est_set_diff_local);

  /* Estimate byte required if we send first */
  uint64_t total_elements_to_send_local_send_first = est_set_diff_remote
                                                     + local_set_size;

  uint64_t total_bytes_full_local_send_first = (avg_element_size
                                                *
                                                total_elements_to_send_local_send_first)   \
                                               + (
    total_elements_to_send_local_send_first * sizeof(struct
                                                     GNUNET_SETU_ElementMessage))   \
                                               + (sizeof_full_done_header * 2)   \
                                               + rtt_min_full
                                               * bandwith_latency_tradeoff;

  /* Estimate bytes required if we request from remote peer */
  uint64_t total_elements_to_send_remote_send_first = est_set_diff_local
                                                      + remote_set_size;

  uint64_t total_bytes_full_remote_send_first = (avg_element_size
                                                 *
                                                 total_elements_to_send_remote_send_first)   \
                                                + (
    total_elements_to_send_remote_send_first * sizeof(struct
                                                      GNUNET_SETU_ElementMessage))   \
                                                + (sizeof_full_done_header * 2)   \
                                                + (rtt_min_full + 0.5)
                                                * bandwith_latency_tradeoff   \
                                                + sizeof_request_full;

  /*
  * Calculate bytes for differential Sync
  */

  /* Estimate bytes required by IBF transmission*/

  long double ibf_bucket_count = estimated_total_diff
                                 * ibf_bucket_number_factor;

  if (ibf_bucket_count <= IBF_MIN_SIZE)
  {
    ibf_bucket_count = IBF_MIN_SIZE;
  }
  uint64_t ibf_message_count = ceil ( ((float) ibf_bucket_count)
                                      / ((float) MAX_BUCKETS_PER_MESSAGE));

  uint64_t estimated_counter_size = ceil (
    MIN (2 * log2l (((float) local_set_size)
                    / ((float) ibf_bucket_count)),
         log2l (local_set_size)));

  long double counter_bytes = (float) estimated_counter_size / 8;

  uint64_t ibf_bytes = ceil ((sizeof (struct IBFMessage) * ibf_message_count)
                             * 1.2   \
                             + (ibf_bucket_count * sizeof(struct IBF_Key)) * 1.2   \
                             + (ibf_bucket_count * sizeof(struct IBF_KeyHash))
                             * 1.2   \
                             + (ibf_bucket_count * counter_bytes) * 1.2);

  /* Estimate full byte count for differential sync */
  uint64_t element_size = (avg_element_size
                           + sizeof (struct GNUNET_SETU_ElementMessage))   \
                          * estimated_total_diff;
  uint64_t done_size = sizeof_done_header;
  uint64_t inquery_size = (sizeof (struct IBF_Key)
                           + sizeof (struct InquiryMessage))
                          * estimated_total_diff;
  uint64_t demand_size =
    (sizeof(struct GNUNET_HashCode) + sizeof(struct GNUNET_MessageHeader))
    * estimated_total_diff;
  uint64_t offer_size = (sizeof (struct GNUNET_HashCode)
                         + sizeof (struct GNUNET_MessageHeader))
                        * estimated_total_diff;

  uint64_t total_bytes_diff = (element_size + done_size + inquery_size
                               + demand_size + offer_size + ibf_bytes)   \
                              + (DIFFERENTIAL_RTT_MEAN
                                 * bandwith_latency_tradeoff);

  uint64_t full_min = MIN (total_bytes_full_local_send_first,
                           total_bytes_full_remote_send_first);

  /* Decide between full and differential sync */

  if (full_min < total_bytes_diff)
  {
    /* Decide between sending all element first or receiving all elements */
    if (total_bytes_full_remote_send_first > total_bytes_full_local_send_first)
    {
      return FULL_SYNC_LOCAL_SENDING_FIRST;
    }
    else
    {
      return FULL_SYNC_REMOTE_SENDING_FIRST;
    }
  }
  else
  {
    return DIFFERENTIAL_SYNC;
  }
}


/**
 * Validates the if a message is received in a correct phase
 * @param allowed_phases
 * @param size_phases
 * @param op
 * @return #GNUNET_YES if message permitted in phase and #GNUNET_NO if not permitted in given
 * phase
 */
static enum GNUNET_GenericReturnValue
check_valid_phase (const uint8_t allowed_phases[],
                   size_t size_phases,
                   struct Operation *op)
{
  /**
   * Iterate over allowed phases
   */
  for (uint32_t phase_ctr = 0; phase_ctr < size_phases; phase_ctr++)
  {
    uint8_t phase = allowed_phases[phase_ctr];
    if (phase == op->phase)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Message received in valid phase\n");
      return GNUNET_YES;
    }
  }
  LOG (GNUNET_ERROR_TYPE_ERROR,
       "Received message in invalid phase: %u\n", op->phase);
  return GNUNET_NO;
}


/**
 * Function to update, track and validate message received in differential
 * sync. This function tracks states of messages and check it against different
 * constraints as described in Summermatter's BSc Thesis (2021)
 * @param hash_map: Hashmap to store message control flow
 * @param new_mcfs: The new message control flow state an given message type should be set to
 * @param hash_code: Hash code of the element
 * @param mt: The message type for which the message control flow state should be set
 * @return GNUNET_YES message is valid in message control flow GNUNET_NO when message is not valid
 * at this point in message flow
 */
static int
update_message_control_flow (struct GNUNET_CONTAINER_MultiHashMap *hash_map,
                             enum MESSAGE_CONTROL_FLOW_STATE new_mcfs,
                             const struct GNUNET_HashCode *hash_code,
                             enum MESSAGE_TYPE mt)
{
  struct messageControlFlowElement *cfe = NULL;
  enum MESSAGE_CONTROL_FLOW_STATE *mcfs;

  /**
   * Check logic for forbidden messages
   */

  cfe = GNUNET_CONTAINER_multihashmap_get (hash_map, hash_code);
  if ((ELEMENT_MESSAGE == mt) && (cfe != NULL))
  {
    if ((new_mcfs != MSG_CFS_SENT) && (MSG_CFS_RECEIVED != cfe->offer))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Received an element without sent offer!\n");
      return GNUNET_NO;
    }
    /* Check that only requested elements are received! */
    if ((ELEMENT_MESSAGE == mt) && (new_mcfs != MSG_CFS_SENT) && (cfe->demand !=
                                                                  MSG_CFS_SENT))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Received an element that was not demanded\n");
      return GNUNET_NO;
    }
  }

  /**
   * In case the element hash is not in the hashmap create a new entry
   */

  if (NULL == cfe)
  {
    cfe = GNUNET_new (struct messageControlFlowElement);
    if (GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put (hash_map, hash_code,
                                                            cfe,
                                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
    {
      GNUNET_free (cfe);
      return GNUNET_SYSERR;
    }
  }

  /**
   * Set state of message
   */

  if (OFFER_MESSAGE == mt)
  {
    mcfs = &cfe->offer;
  }
  else if (DEMAND_MESSAGE == mt)
  {
    mcfs = &cfe->demand;
  }
  else if (ELEMENT_MESSAGE == mt)
  {
    mcfs = &cfe->element;
  }
  else
  {
    return GNUNET_SYSERR;
  }

  /**
   * Check if state is allowed
   */

  if (new_mcfs <= *mcfs)
  {
    return GNUNET_NO;
  }

  *mcfs = new_mcfs;
  return GNUNET_YES;
}


/**
 * Validate if a message in differential sync si already received before.
 * @param hash_map
 * @param hash_code
 * @param mt
 * @return GNUNET_YES when message is already in store if message is not in store return GNUNET_NO
 */
static int
is_message_in_message_control_flow (struct
                                    GNUNET_CONTAINER_MultiHashMap *hash_map,
                                    struct GNUNET_HashCode *hash_code,
                                    enum MESSAGE_TYPE mt)
{
  struct messageControlFlowElement *cfe = NULL;
  enum MESSAGE_CONTROL_FLOW_STATE *mcfs;

  cfe = GNUNET_CONTAINER_multihashmap_get (hash_map, hash_code);

  /**
  * Set state of message
  */

  if (cfe != NULL)
  {
    if (OFFER_MESSAGE == mt)
    {
      mcfs = &cfe->offer;
    }
    else if (DEMAND_MESSAGE == mt)
    {
      mcfs = &cfe->demand;
    }
    else if (ELEMENT_MESSAGE == mt)
    {
      mcfs = &cfe->element;
    }
    else
    {
      return GNUNET_SYSERR;
    }

    /**
     * Evaluate if set is in message
     */
    if (*mcfs != MSG_CFS_UNINITIALIZED)
    {
      return GNUNET_YES;
    }
  }
  return GNUNET_NO;
}


/**
 * Iterator for determining if all demands have been
 * satisfied
 *
 * @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
determinate_done_message_iterator (void *cls,
                                   const struct GNUNET_HashCode *key,
                                   void *value)
{
  struct messageControlFlowElement *mcfe = value;

  if (((mcfe->element == MSG_CFS_SENT) || (mcfe->element == MSG_CFS_RECEIVED) ))
  {
    return GNUNET_YES;
  }
  return GNUNET_NO;
}


/**
 * Iterator for determining average size
 *
 * @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
determinate_avg_element_size_iterator (void *cls,
                                       const struct GNUNET_HashCode *key,
                                       void *value)
{
  struct Operation *op = cls;
  struct GNUNET_SETU_Element *element = value;
  op->total_elements_size_local += element->size;
  return GNUNET_YES;
}


/**
 * Create randomized element hashmap for full sending
 *
 * @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
create_randomized_element_iterator (void *cls,
                                    const struct GNUNET_HashCode *key,
                                    void *value)
{
  struct Operation *op = cls;

  struct GNUNET_HashContext *hashed_key_context =
    GNUNET_CRYPTO_hash_context_start ();
  struct GNUNET_HashCode new_key;

  /**
   * Hash element with new salt to randomize hashmap
   */
  GNUNET_CRYPTO_hash_context_read (hashed_key_context,
                                   &key,
                                   sizeof(struct IBF_Key));
  GNUNET_CRYPTO_hash_context_read (hashed_key_context,
                                   &op->set->content->elements_randomized_salt,
                                   sizeof(uint32_t));
  GNUNET_CRYPTO_hash_context_finish (hashed_key_context,
                                     &new_key);
  GNUNET_CONTAINER_multihashmap_put (op->set->content->elements_randomized,
                                     &new_key,value,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
  return GNUNET_YES;
}


/**
 * 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;
}


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

  if (GNUNET_YES == op->client_done_sent)
    return;
  if (PHASE_FINISHED != op->phase)
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "Union operation failed\n");
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# Union operations failed",
                              1,
                              GNUNET_NO);
    ev = GNUNET_MQ_msg (rm, GNUNET_MESSAGE_TYPE_SETU_RESULT);
    rm->result_status = htons (GNUNET_SETU_STATUS_FAILURE);
    rm->request_id = htonl (op->client_request_id);
    rm->element_type = htons (0);
    GNUNET_MQ_send (op->set->cs->mq,
                    ev);
    return;
  }

  op->client_done_sent = GNUNET_YES;

  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# Union operations succeeded",
                            1,
                            GNUNET_NO);
  LOG (GNUNET_ERROR_TYPE_INFO,
       "Signalling client that union operation is done\n");
  ev = GNUNET_MQ_msg (rm,
                      GNUNET_MESSAGE_TYPE_SETU_RESULT);
  rm->request_id = htonl (op->client_request_id);
  rm->result_status = htons (GNUNET_SETU_STATUS_DONE);
  rm->element_type = htons (0);
  rm->current_size = GNUNET_htonll (GNUNET_CONTAINER_multihashmap32_size (
                                      op->key_to_element));
  GNUNET_MQ_send (op->set->cs->mq,
                  ev);
}


/**
 * Check if all given byzantine parameters are in given boundaries
 * @param op
 * @return indicator if all given byzantine parameters are in given boundaries
 */

static int
check_byzantine_bounds (struct Operation *op)
{
  if (op->byzantine != GNUNET_YES)
    return GNUNET_OK;

  /**
   * Check  upper byzantine bounds
   */
  if (op->remote_element_count + op->remote_set_diff >
      op->byzantine_upper_bound)
    return GNUNET_SYSERR;
  if (op->local_element_count + op->local_set_diff > op->byzantine_upper_bound)
    return GNUNET_SYSERR;

  /**
  * Check lower byzantine bounds
  */
  if (op->remote_element_count < op->byzantine_lower_bound)
    return GNUNET_SYSERR;
  return GNUNET_OK;
}


/* FIXME: the destroy logic is a mess and should be cleaned up! */

/**
 * Destroy the given operation.  Used for any operation where both
 * peers were known and that thus actually had a vt and channel.  Must
 * not be used for operations where 'listener' is still set and we do
 * not know the other peer.
 *
 * Call the implementation-specific cancel function of the operation.
 * Disconnects from the remote peer.  Does not disconnect the client,
 * as there may be multiple operations per set.
 *
 * @param op operation to destroy
 */
static void
_GSS_operation_destroy (struct Operation *op)
{
  struct Set *set = op->set;
  struct GNUNET_CADET_Channel *channel;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Destroying union operation %p\n",
              op);
  GNUNET_assert (NULL == op->listener);
  /* check if the op was canceled twice */
  if (NULL != op->remote_ibf)
  {
    ibf_destroy (op->remote_ibf);
    op->remote_ibf = NULL;
  }
  if (NULL != op->demanded_hashes)
  {
    GNUNET_CONTAINER_multihashmap_destroy (op->demanded_hashes);
    op->demanded_hashes = NULL;
  }
  if (NULL != op->local_ibf)
  {
    ibf_destroy (op->local_ibf);
    op->local_ibf = NULL;
  }
  if (NULL != op->se)
  {
    strata_estimator_destroy (op->se);
    op->se = NULL;
  }
  if (NULL != op->key_to_element)
  {
    GNUNET_CONTAINER_multihashmap32_iterate (op->key_to_element,
                                             &destroy_key_to_element_iter,
                                             NULL);
    GNUNET_CONTAINER_multihashmap32_destroy (op->key_to_element);
    op->key_to_element = NULL;
  }
  if (NULL != set)
  {
    GNUNET_CONTAINER_DLL_remove (set->ops_head,
                                 set->ops_tail,
                                 op);
    op->set = NULL;
  }
  if (NULL != op->context_msg)
  {
    GNUNET_free (op->context_msg);
    op->context_msg = NULL;
  }
  if (NULL != (channel = op->channel))
  {
    /* This will free op; called conditionally as this helper function
       is also called from within the channel disconnect handler. */
    op->channel = NULL;
    GNUNET_CADET_channel_destroy (channel);
  }
  /* We rely on the channel end handler to free 'op'. When 'op->channel' was NULL,
   * there was a channel end handler that will free 'op' on the call stack. */
}


/**
 * This function probably should not exist
 * and be replaced by inlining more specific
 * logic in the various places where it is called.
 */
static void
_GSS_operation_destroy2 (struct Operation *op);


/**
 * Destroy an incoming request from a remote peer
 *
 * @param op remote request to destroy
 */
static void
incoming_destroy (struct Operation *op)
{
  struct Listener *listener;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Destroying incoming operation %p\n",
              op);
  if (NULL != (listener = op->listener))
  {
    GNUNET_CONTAINER_DLL_remove (listener->op_head,
                                 listener->op_tail,
                                 op);
    op->listener = NULL;
  }
  if (NULL != op->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (op->timeout_task);
    op->timeout_task = NULL;
  }
  _GSS_operation_destroy2 (op);
}


/**
 * This function probably should not exist
 * and be replaced by inlining more specific
 * logic in the various places where it is called.
 */
static void
_GSS_operation_destroy2 (struct Operation *op)
{
  struct GNUNET_CADET_Channel *channel;

  if (NULL != (channel = op->channel))
  {
    /* This will free op; called conditionally as this helper function
       is also called from within the channel disconnect handler. */
    op->channel = NULL;
    GNUNET_CADET_channel_destroy (channel);
  }
  if (NULL != op->listener)
  {
    incoming_destroy (op);
    return;
  }
  if (NULL != op->set)
    send_client_done (op);
  _GSS_operation_destroy (op);
  GNUNET_free (op);
}


/**
 * 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_SETU_ResultMessage *msg;

  LOG (GNUNET_ERROR_TYPE_WARNING,
       "union operation failed\n");
  ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SETU_RESULT);
  msg->result_status = htons (GNUNET_SETU_STATUS_FAILURE);
  msg->request_id = htonl (op->client_request_id);
  msg->element_type = htons (0);
  GNUNET_MQ_send (op->set->cs->mq,
                  ev);
  _GSS_operation_destroy (op);
}


/**
 * Function that checks if full sync is plausible
 * @param initial_local_elements_in_set
 * @param estimated_set_difference
 * @param repeated_elements
 * @param fresh_elements
 * @param op
 * @return GNUNET_OK if
 */

static void
full_sync_plausibility_check (struct Operation *op)
{
  if (GNUNET_YES != op->byzantine)
    return;

  int security_level_lb = -1 * SECURITY_LEVEL;
  uint64_t duplicates = op->received_fresh - op->received_total;

  /*
   * Protect full sync from receiving double element when in FULL SENDING
   */
  if (PHASE_FULL_SENDING == op->phase)
  {
    if (duplicates > 0)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "PROTOCOL VIOLATION: Received duplicate element in full receiving "
           "mode of operation this is not allowed! Duplicates: %llu\n",
           (unsigned long long) duplicates);
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }

  }

  /*
   * Protect full sync with probabilistic algorithm
   */
  if (PHASE_FULL_RECEIVING == op->phase)
  {
    if (0 == op->remote_set_diff)
      op->remote_set_diff = 1;

    long double base = (1 - (long double) (op->remote_set_diff
                                           / (long double) (op->initial_size
                                                            + op->
                                                            remote_set_diff)));
    long double exponent = (op->received_total - (op->received_fresh * ((long
                                                                         double)
                                                                        op->
                                                                        initial_size
                                                                        / (long
                                                                           double)
                                                                        op->
                                                                        remote_set_diff)));
    long double value = exponent * (log2l (base) / log2l (2));
    if ((value < security_level_lb) || (value > SECURITY_LEVEL) )
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "PROTOCOL VIOLATION: Other peer violated probabilistic rule for receiving "
           "to many duplicated full element : %LF\n",
           value);
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }
  }
}


/**
 * Limit active passive switches in differential sync to configured security level
 * @param op
 */
static void
check_max_differential_rounds (struct Operation *op)
{
  double probability = op->differential_sync_iterations * (log2l (
                                                             PROBABILITY_FOR_NEW_ROUND)
                                                           / log2l (2));
  if ((-1 * SECURITY_LEVEL) > probability)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Other peer violated probabilistic rule for to many active passive "
         "switches in differential sync: %u\n",
         op->differential_sync_iterations);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
}


/**
 * 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_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_kdf (&key, sizeof(key),
                                    src, sizeof *src,
                                    &salt, sizeof(salt),
                                    NULL, 0));
  return key;
}


/**
 * Context for #op_get_element_iterator
 */
struct GetElementContext
{
  /**
   * Gnunet hash code in context
   */
  struct GNUNET_HashCode hash;

  /**
   * Pointer to the key entry
   */
  struct KeyEntry *k;
};


/**
 * 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_get_element_iterator (void *cls,
                         uint32_t key,
                         void *value)
{
  struct GetElementContext *ctx = cls;
  struct KeyEntry *k = value;

  GNUNET_assert (NULL != k);
  if (0 == GNUNET_CRYPTO_hash_cmp (&k->element->element_hash,
                                   &ctx->hash))
  {
    ctx->k = k;
    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 struct KeyEntry *
op_get_element (struct Operation *op,
                const struct GNUNET_HashCode *element_hash)
{
  int ret;
  struct IBF_Key ibf_key;
  struct GetElementContext ctx = { { { 0 } }, 0 };

  ctx.hash = *element_hash;

  ibf_key = get_ibf_key (element_hash);
  ret = GNUNET_CONTAINER_multihashmap32_get_multiple (op->key_to_element,
                                                      (uint32_t) ibf_key.key_val,
                                                      &op_get_element_iterator,
                                                      &ctx);

  /* was the iteration aborted because we found the element? */
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_assert (NULL != ctx.k);
    return ctx.k;
  }
  return NULL;
}


/**
 * 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
 * @param received was this element received from the remote peer?
 */
static void
op_register_element (struct Operation *op,
                     struct ElementEntry *ee,
                     int received)
{
  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;
  k->received = received;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap32_put (op->key_to_element,
                                                      (uint32_t) ibf_key.key_val,
                                                      k,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
}


/**
 * Modify an IBF key @a k_in based on the @a salt, returning a
 * salted key in @a k_out.
 */
static void
salt_key (const struct IBF_Key *k_in,
          uint32_t salt,
          struct IBF_Key *k_out)
{
  int s = (salt * 7) % 64;
  uint64_t x = k_in->key_val;

  /* rotate ibf key */
  x = (x >> s) | (x << (64 - s));
  k_out->key_val = x;
}


/**
 * Reverse modification done in the salt_key function
 */
static void
unsalt_key (const struct IBF_Key *k_in,
            uint32_t salt,
            struct IBF_Key *k_out)
{
  int s = (salt * 7) % 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 %p] inserting %lx (hash %s) into ibf\n",
       op,
       (unsigned long) ke->ibf_key.key_val,
       GNUNET_h2s (&ke->element->element_hash));
  salt_key (&ke->ibf_key,
            op->salt_send,
            &salted_key);
  ibf_insert (op->local_ibf, salted_key);
  return GNUNET_YES;
}


/**
 * Is element @a ee part of the set used by @a op?
 *
 * @param ee element to test
 * @param op operation the defines the set and its generation
 * @return #GNUNET_YES if the element is in the set, #GNUNET_NO if not
 */
static int
_GSS_is_element_of_operation (struct ElementEntry *ee,
                              struct Operation *op)
{
  return ee->generation >= op->generation_created;
}


/**
 * 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,
                       GNUNET_NO);
  return GNUNET_YES;
}


/**
 * Initialize the IBF key to element mapping local to this set operation.
 *
 * @param op the set union operation
 */
static void
initialize_key_to_element (struct Operation *op)
{
  unsigned int len;

  GNUNET_assert (NULL == op->key_to_element);
  len = GNUNET_CONTAINER_multihashmap_size (op->set->content->elements);
  op->key_to_element = GNUNET_CONTAINER_multihashmap32_create (len + 1);
  GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                         &init_key_to_element_iterator,
                                         op);
}


/**
 * 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)
{
  GNUNET_assert (NULL != op->key_to_element);

  if (NULL != op->local_ibf)
    ibf_destroy (op->local_ibf);
  // op->local_ibf = ibf_create (size, SE_IBF_HASH_NUM);
  op->local_ibf = ibf_create (size,
                              ((uint8_t) op->ibf_number_buckets_per_element));
  if (NULL == op->local_ibf)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to allocate local IBF\n");
    return GNUNET_SYSERR;
  }
  GNUNET_CONTAINER_multihashmap32_iterate (op->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,
          uint32_t ibf_size)
{
  uint64_t buckets_sent = 0;
  struct InvertibleBloomFilter *ibf;
  op->differential_sync_iterations++;

  /**
   * Enforce min size of IBF
   */
  uint32_t ibf_min_size = IBF_MIN_SIZE;

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

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sending ibf of size %u\n",
       (unsigned int) ibf_size);

  {
    char name[64];

    GNUNET_snprintf (name,
                     sizeof(name),
                     "# sent IBF (order %u)",
                     ibf_size);
    GNUNET_STATISTICS_update (_GSS_statistics, name, 1, GNUNET_NO);
  }

  ibf = op->local_ibf;

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

    buckets_in_message = ibf_size - buckets_sent;
    /* limit to maximum */
    if (buckets_in_message > MAX_BUCKETS_PER_MESSAGE)
      buckets_in_message = MAX_BUCKETS_PER_MESSAGE;

#if MEASURE_PERFORMANCE
    perf_store.ibf.sent += 1;
    perf_store.ibf.sent_var_bytes += (buckets_in_message * IBF_BUCKET_SIZE);
#endif
    ev = GNUNET_MQ_msg_extra (msg,
                              buckets_in_message * IBF_BUCKET_SIZE,
                              GNUNET_MESSAGE_TYPE_SETU_P2P_IBF);
    msg->ibf_size = ibf_size;
    msg->offset = htonl (buckets_sent);
    msg->salt = htonl (op->salt_send);
    msg->ibf_counter_bit_length = ibf_get_max_counter (ibf);


    ibf_write_slice (ibf, buckets_sent,
                     buckets_in_message, &msg[1], msg->ibf_counter_bit_length);
    buckets_sent += buckets_in_message;
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "ibf chunk size %u, %llu/%u sent\n",
         (unsigned int) buckets_in_message,
         (unsigned long long) buckets_sent,
         (unsigned int) ibf_size);
    GNUNET_MQ_send (op->mq, ev);
  }

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


/**
 * 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_size_from_difference (unsigned int diff, int number_buckets_per_element,
                          float ibf_bucket_number_factor)
{
  /** Make ibf estimation size odd reasoning can be found in BSc Thesis of
   * Elias Summermatter (2021) in section 3.11 **/
  return (((int) (diff * ibf_bucket_number_factor)) | 1);

}


static unsigned int
get_next_ibf_size (float ibf_bucket_number_factor, unsigned int
                   decoded_elements, unsigned int last_ibf_size)
{
  unsigned int next_size = (unsigned int) ((last_ibf_size * 2)
                                           - (ibf_bucket_number_factor
                                              * decoded_elements));
  /** Make ibf estimation size odd reasoning can be found in BSc Thesis of
  * Elias Summermatter (2021) in section 3.11 **/
  return next_size | 1;
}


/**
 * Send a set element.
 *
 * @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
send_full_element_iterator (void *cls,
                            const struct GNUNET_HashCode *key,
                            void *value)
{
  struct Operation *op = cls;
  struct GNUNET_SETU_ElementMessage *emsg;
  struct ElementEntry *ee = value;
  struct GNUNET_SETU_Element *el = &ee->element;
  struct GNUNET_MQ_Envelope *ev;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending element %s\n",
       GNUNET_h2s (key));
#if MEASURE_PERFORMANCE
  perf_store.element_full.received += 1;
  perf_store.element_full.received_var_bytes += el->size;
#endif
  ev = GNUNET_MQ_msg_extra (emsg,
                            el->size,
                            GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_ELEMENT);
  emsg->element_type = htons (el->element_type);
  GNUNET_memcpy (&emsg[1],
                 el->data,
                 el->size);
  GNUNET_MQ_send (op->mq,
                  ev);
  return GNUNET_YES;
}


/**
 * Switch to full set transmission for @a op.
 *
 * @param op operation to switch to full set transmission.
 */
static void
send_full_set (struct Operation *op)
{
  struct GNUNET_MQ_Envelope *ev;

  op->phase = PHASE_FULL_SENDING;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Dedicing to transmit the full set\n");
  /* FIXME: use a more memory-friendly way of doing this with an
     iterator, just as we do in the non-full case! */

  // Randomize Elements to send
  op->set->content->elements_randomized = GNUNET_CONTAINER_multihashmap_create (
    32,GNUNET_NO);
  op->set->content->elements_randomized_salt = GNUNET_CRYPTO_random_u64 (
    GNUNET_CRYPTO_QUALITY_NONCE,
    UINT64_MAX);
  (void) GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                                &
                                                create_randomized_element_iterator,
                                                op);

  (void) GNUNET_CONTAINER_multihashmap_iterate (
    op->set->content->elements_randomized,
    &send_full_element_iterator,
    op);
#if MEASURE_PERFORMANCE
  perf_store.full_done.sent += 1;
#endif
  ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_DONE);
  GNUNET_MQ_send (op->mq,
                  ev);
}


/**
 * Handle a strata estimator from a remote peer
 *
 * @param cls the union operation
 * @param msg the message
 */
static int
check_union_p2p_strata_estimator (void *cls,
                                  const struct StrataEstimatorMessage *msg)
{
  struct Operation *op = cls;
  int is_compressed;
  size_t len;

  if (op->phase != PHASE_EXPECT_SE)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  is_compressed = (GNUNET_MESSAGE_TYPE_SETU_P2P_SEC == htons (
                     msg->header.type));
  len = ntohs (msg->header.size) - sizeof(struct StrataEstimatorMessage);
  if ((GNUNET_NO == is_compressed) &&
      (len != SE_STRATA_COUNT * SE_IBFS_TOTAL_SIZE * IBF_BUCKET_SIZE))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handle a strata estimator from a remote peer
 *
 * @param cls the union operation
 * @param msg the message
 */
static void
handle_union_p2p_strata_estimator (void *cls,
                                   const struct StrataEstimatorMessage *msg)
{
#if MEASURE_PERFORMANCE
  perf_store.se.received += 1;
  perf_store.se.received_var_bytes += ntohs (msg->header.size) - sizeof(struct
                                                                        StrataEstimatorMessage);
#endif
  struct Operation *op = cls;
  struct MultiStrataEstimator *remote_se;
  unsigned int diff;
  uint64_t other_size;
  size_t len;
  int is_compressed;
  op->local_element_count = GNUNET_CONTAINER_multihashmap_size (
    op->set->content->elements);
  // Setting peer site to receiving peer
  op->peer_site = 1;

  /**
   * Check that the message is received only in supported phase
   */
  uint8_t allowed_phases[] = {PHASE_EXPECT_SE};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  /** Only allow 1,2,4,8 SEs **/
  if ((msg->se_count > 8) || (__builtin_popcount ((int) msg->se_count) != 1))
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Invalid number of se transmitted by other peer %u\n",
         msg->se_count);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  is_compressed = (GNUNET_MESSAGE_TYPE_SETU_P2P_SEC == htons (
                     msg->header.type));
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# bytes of SE received",
                            ntohs (msg->header.size),
                            GNUNET_NO);
  len = ntohs (msg->header.size) - sizeof(struct StrataEstimatorMessage);
  other_size = GNUNET_ntohll (msg->set_size);
  op->remote_element_count = other_size;

  if (op->byzantine_upper_bound < op->remote_element_count)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Exceeded configured upper bound <%lu> of element: %u\n",
         op->byzantine_upper_bound,
         op->remote_element_count);
    fail_union_operation (op);
    return;
  }

  remote_se = strata_estimator_create (SE_STRATA_COUNT,
                                       SE_IBFS_TOTAL_SIZE,
                                       SE_IBF_HASH_NUM);
  if (NULL == remote_se)
  {
    /* insufficient resources, fail */
    fail_union_operation (op);
    return;
  }
  if (GNUNET_OK !=
      strata_estimator_read (&msg[1],
                             len,
                             is_compressed,
                             msg->se_count,
                             SE_IBFS_TOTAL_SIZE,
                             remote_se))
  {
    /* decompression failed */
    strata_estimator_destroy (remote_se);
    fail_union_operation (op);
    return;
  }
  GNUNET_assert (NULL != op->se);
  strata_estimator_difference (remote_se,
                               op->se);

  /* Calculate remote local diff */
  long diff_remote = remote_se->stratas[0]->strata[0]->remote_decoded_count;
  long diff_local = remote_se->stratas[0]->strata[0]->local_decoded_count;

  /* Prevent estimations from overshooting max element */
  if (diff_remote + op->remote_element_count > op->byzantine_upper_bound)
    diff_remote = op->byzantine_upper_bound - op->remote_element_count;
  if (diff_local + op->local_element_count > op->byzantine_upper_bound)
    diff_local = op->byzantine_upper_bound - op->local_element_count;
  if ((diff_remote < 0) || (diff_local < 0))
  {
    strata_estimator_destroy (remote_se);
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: More element is set as upper boundary or other peer is "
         "malicious: remote diff %ld, local diff: %ld\n",
         diff_remote, diff_local);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  /* Make estimation more precise in initial sync cases */
  if (0 == op->remote_element_count)
  {
    diff_remote = 0;
    diff_local = op->local_element_count;
  }
  if (0 == op->local_element_count)
  {
    diff_local = 0;
    diff_remote = op->remote_element_count;
  }

  diff = diff_remote + diff_local;
  op->remote_set_diff = diff_remote;

  /** Calculate avg element size if not initial sync **/
  uint64_t avg_element_size = 0;
  if (0 < op->local_element_count)
  {
    op->total_elements_size_local = 0;
    GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                           &
                                           determinate_avg_element_size_iterator,
                                           op);
    avg_element_size = op->total_elements_size_local / op->local_element_count;
  }

  op->mode_of_operation = estimate_best_mode_of_operation (avg_element_size,
                                                           GNUNET_CONTAINER_multihashmap_size (
                                                             op->set->content->
                                                             elements),
                                                           op->
                                                           remote_element_count,
                                                           diff_remote,
                                                           diff_local,
                                                           op->
                                                           rtt_bandwidth_tradeoff,
                                                           op->
                                                           ibf_bucket_number_factor);

#if MEASURE_PERFORMANCE
  perf_store.se_diff_local = diff_local;
  perf_store.se_diff_remote = diff_remote;
  perf_store.se_diff = diff;
  perf_store.mode_of_operation = op->mode_of_operation;
#endif

  strata_estimator_destroy (remote_se);
  strata_estimator_destroy (op->se);
  op->se = NULL;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "got se diff=%d, using ibf size %d\n",
       diff,
       1U << get_size_from_difference (diff, op->ibf_number_buckets_per_element,
                                       op->ibf_bucket_number_factor));

  {
    char *set_debug;

    set_debug = getenv ("GNUNET_SETU_BENCHMARK");
    if ((NULL != set_debug) &&
        (0 == strcmp (set_debug, "1")))
    {
      FILE *f = fopen ("set.log", "a");
      fprintf (f, "%llu\n", (unsigned long long) diff);
      fclose (f);
    }
  }

  if ((GNUNET_YES == op->byzantine) &&
      (other_size < op->byzantine_lower_bound))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  if ((GNUNET_YES == op->force_full) ||
      (op->mode_of_operation != DIFFERENTIAL_SYNC))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Deciding to go for full set transmission (diff=%d, own set=%llu)\n",
         diff,
         (unsigned long long) op->initial_size);
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# of full sends",
                              1,
                              GNUNET_NO);
    if (FULL_SYNC_LOCAL_SENDING_FIRST == op->mode_of_operation)
    {
      struct TransmitFullMessage *signal_msg;
      struct GNUNET_MQ_Envelope *ev;
      ev = GNUNET_MQ_msg_extra (signal_msg,sizeof(struct TransmitFullMessage),
                                GNUNET_MESSAGE_TYPE_SETU_P2P_SEND_FULL);
      signal_msg->remote_set_difference = htonl (diff_local);
      signal_msg->remote_set_size = htonl (op->local_element_count);
      signal_msg->local_set_difference = htonl (diff_remote);
      GNUNET_MQ_send (op->mq,
                      ev);
      send_full_set (op);
    }
    else
    {
      struct GNUNET_MQ_Envelope *ev;

      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Telling other peer that we expect its full set\n");
      op->phase = PHASE_FULL_RECEIVING;
#if MEASURE_PERFORMANCE
      perf_store.request_full.sent += 1;
#endif
      struct TransmitFullMessage *signal_msg;
      ev = GNUNET_MQ_msg_extra (signal_msg,sizeof(struct TransmitFullMessage),
                                GNUNET_MESSAGE_TYPE_SETU_P2P_REQUEST_FULL);
      signal_msg->remote_set_difference = htonl (diff_local);
      signal_msg->remote_set_size = htonl (op->local_element_count);
      signal_msg->local_set_difference = htonl (diff_remote);
      GNUNET_MQ_send (op->mq,
                      ev);
    }
  }
  else
  {
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# of ibf sends",
                              1,
                              GNUNET_NO);
    if (GNUNET_OK !=
        send_ibf (op,
                  get_size_from_difference (diff,
                                            op->ibf_number_buckets_per_element,
                                            op->ibf_bucket_number_factor)))
    {
      /* 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_CADET_receive_done (op->channel);
}


/**
 * 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)
  {
    op->active_passive_switch_required = true;
    return GNUNET_YES;
  }

  /* Prevent implementation from sending a offer multiple times in case of roll switch */
  if (GNUNET_YES ==
      is_message_in_message_control_flow (
        op->message_control_flow,
        &ke->element->element_hash,
        OFFER_MESSAGE)
      )
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Skipping already sent processed element offer!\n");
    return GNUNET_YES;
  }

  /* Save send offer message for message control */
  if (GNUNET_YES !=
      update_message_control_flow (
        op->message_control_flow,
        MSG_CFS_SENT,
        &ke->element->element_hash,
        OFFER_MESSAGE)
      )
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Double offer message sent found!\n");
    GNUNET_break (0);
    fail_union_operation (op);
    return GNUNET_NO;
  }
  ;

  /* Mark element to be expected to received */
  if (GNUNET_YES !=
      update_message_control_flow (
        op->message_control_flow,
        MSG_CFS_EXPECTED,
        &ke->element->element_hash,
        DEMAND_MESSAGE)
      )
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Double demand received found!\n");
    GNUNET_break (0);
    fail_union_operation (op);
    return GNUNET_NO;
  }
  ;
#if MEASURE_PERFORMANCE
  perf_store.offer.sent += 1;
  perf_store.offer.sent_var_bytes += sizeof(struct GNUNET_HashCode);
#endif
  ev = GNUNET_MQ_msg_header_extra (mh,
                                   sizeof(struct GNUNET_HashCode),
                                   GNUNET_MESSAGE_TYPE_SETU_P2P_OFFER);
  GNUNET_assert (NULL != ev);
  *(struct GNUNET_HashCode *) &mh[1] = ke->element->element_hash;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "[OP %p] sending element offer (%s) to peer\n",
       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
 */
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->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_ACTIVE_DECODING == op->phase);

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

  diff_ibf = ibf_dup (op->local_ibf);
  ibf_subtract (diff_ibf,
                op->remote_ibf);

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

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

  num_decoded = 0;
  key.key_val = 0;   /* just to avoid compiler thinking we use undef'ed variable */

  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))
    {
      uint32_t next_size;
      /** Enforce odd ibf size **/

      next_size = get_next_ibf_size (op->ibf_bucket_number_factor, num_decoded,
                                     diff_ibf->size);
      /** Make ibf estimation size odd reasoning can be found in BSc Thesis of
        * Elias Summermatter (2021) in section 3.11 **/
      uint32_t ibf_min_size = IBF_MIN_SIZE | 1;

      if (next_size<ibf_min_size)
        next_size = ibf_min_size;


      if (next_size <= MAX_IBF_SIZE)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
             "decoding failed, sending larger ibf (size %u)\n",
             next_size);
        GNUNET_STATISTICS_update (_GSS_statistics,
                                  "# of IBF retries",
                                  1,
                                  GNUNET_NO);
#if MEASURE_PERFORMANCE
        perf_store.active_passive_switches += 1;
#endif

        op->salt_send = op->salt_receive++;

        if (GNUNET_OK !=
            send_ibf (op, next_size))
        {
          /* 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");

#if MEASURE_PERFORMANCE
      perf_store.done.sent += 1;
#endif
      ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SETU_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->salt_receive,
                  &unsalted_key);
      send_offers_for_key (op,
                           unsalted_key);
    }
    else if (-1 == side)
    {
      struct GNUNET_MQ_Envelope *ev;
      struct InquiryMessage *msg;

#if MEASURE_PERFORMANCE
      perf_store.inquery.sent += 1;
      perf_store.inquery.sent_var_bytes += sizeof(struct IBF_Key);
#endif

      /** Add sent inquiries to hashmap for flow control **/
      struct GNUNET_HashContext *hashed_key_context =
        GNUNET_CRYPTO_hash_context_start ();
      struct GNUNET_HashCode *hashed_key = (struct
                                            GNUNET_HashCode*) GNUNET_malloc (
        sizeof(struct GNUNET_HashCode));
      enum MESSAGE_CONTROL_FLOW_STATE mcfs = MSG_CFS_SENT;
      GNUNET_CRYPTO_hash_context_read (hashed_key_context,
                                       &key,
                                       sizeof(struct IBF_Key));
      GNUNET_CRYPTO_hash_context_finish (hashed_key_context,
                                         hashed_key);
      GNUNET_CONTAINER_multihashmap_put (op->inquiries_sent,
                                         hashed_key,
                                         &mcfs,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE
                                         );

      /* 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_SETU_P2P_INQUIRY);
      msg->salt = htonl (op->salt_receive);
      GNUNET_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;
}


/**
 * Check send full message received from other peer
 * @param cls
 * @param msg
 * @return
 */

static int
check_union_p2p_send_full (void *cls,
                           const struct TransmitFullMessage *msg)
{
  return GNUNET_OK;
}


/**
 * Handle send full message received from other peer
 *
 * @param cls
 * @param msg
 */
static void
handle_union_p2p_send_full (void *cls,
                            const struct TransmitFullMessage *msg)
{
  struct Operation *op = cls;

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_EXPECT_IBF};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  /** write received values to operator**/
  op->remote_element_count = ntohl (msg->remote_set_size);
  op->remote_set_diff = ntohl (msg->remote_set_difference);
  op->local_set_diff = ntohl (msg->local_set_difference);

  /** Check byzantine limits **/
  if (check_byzantine_bounds (op) != GNUNET_OK)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Parameters transmitted from other peer do not satisfie byzantine "
         "criteria\n");
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  /** Calculate avg element size if not initial sync **/
  op->local_element_count = GNUNET_CONTAINER_multihashmap_size (
    op->set->content->elements);
  uint64_t avg_element_size = 0;
  if (0 < op->local_element_count)
  {
    op->total_elements_size_local = 0;
    GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                           &
                                           determinate_avg_element_size_iterator,
                                           op);
    avg_element_size = op->total_elements_size_local / op->local_element_count;
  }

  /** Validate mode of operation **/
  int mode_of_operation = estimate_best_mode_of_operation (avg_element_size,
                                                           op->
                                                           remote_element_count,
                                                           op->
                                                           local_element_count,
                                                           op->local_set_diff,
                                                           op->remote_set_diff,
                                                           op->
                                                           rtt_bandwidth_tradeoff,
                                                           op->
                                                           ibf_bucket_number_factor);
  if (FULL_SYNC_LOCAL_SENDING_FIRST != mode_of_operation)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Remote peer choose to send his full set first but correct mode would have been"
         " : %d\n", mode_of_operation);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  op->phase = PHASE_FULL_RECEIVING;
}


/**
 * Check 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 msg the header of the message
 * @return #GNUNET_OK if @a msg is well-formed
 */
static int
check_union_p2p_ibf (void *cls,
                     const struct IBFMessage *msg)
{
  struct Operation *op = cls;
  unsigned int buckets_in_message;

  buckets_in_message = (ntohs (msg->header.size) - sizeof *msg)
                       / IBF_BUCKET_SIZE;
  if (0 == buckets_in_message)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if ((ntohs (msg->header.size) - sizeof *msg) != buckets_in_message
      * IBF_BUCKET_SIZE)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (op->phase == PHASE_EXPECT_IBF_LAST)
  {
    if (ntohl (msg->offset) != op->ibf_buckets_received)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }

    if (msg->ibf_size != op->remote_ibf->size)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    if (ntohl (msg->salt) != op->salt_receive)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
  }
  else if ((op->phase != PHASE_PASSIVE_DECODING) &&
           (op->phase != PHASE_EXPECT_IBF))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  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 msg the header of the message
 */
static void
handle_union_p2p_ibf (void *cls,
                      const struct IBFMessage *msg)
{
  struct Operation *op = cls;
  unsigned int buckets_in_message;
  /**
 * Check that the message is received only in supported phase
 */
  uint8_t allowed_phases[] = {PHASE_EXPECT_IBF, PHASE_EXPECT_IBF_LAST,
                              PHASE_PASSIVE_DECODING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }
  op->differential_sync_iterations++;
  check_max_differential_rounds (op);
  op->active_passive_switch_required = false;

#if MEASURE_PERFORMANCE
  perf_store.ibf.received += 1;
  perf_store.ibf.received_var_bytes += (ntohs (msg->header.size) - sizeof *msg);
#endif

  buckets_in_message = (ntohs (msg->header.size) - sizeof *msg)
                       / IBF_BUCKET_SIZE;
  if ((op->phase == PHASE_PASSIVE_DECODING) ||
      (op->phase == PHASE_EXPECT_IBF))
  {
    op->phase = PHASE_EXPECT_IBF_LAST;
    GNUNET_assert (NULL == op->remote_ibf);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Creating new ibf of size %u\n",
         ntohl (msg->ibf_size));
    // op->remote_ibf = ibf_create (1 << msg->order, SE_IBF_HASH_NUM);
    op->remote_ibf = ibf_create (msg->ibf_size,
                                 ((uint8_t) op->ibf_number_buckets_per_element));
    op->salt_receive = ntohl (msg->salt);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Receiving new IBF with salt %u\n",
         op->salt_receive);
    if (NULL == op->remote_ibf)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to parse remote IBF, closing connection\n");
      fail_union_operation (op);
      return;
    }
    op->ibf_buckets_received = 0;
    if (0 != ntohl (msg->offset))
    {
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }
  }
  else
  {
    GNUNET_assert (op->phase == PHASE_EXPECT_IBF_LAST);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received more of IBF\n");
  }
  GNUNET_assert (NULL != op->remote_ibf);

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

  if (op->ibf_buckets_received == op->remote_ibf->size)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "received full ibf\n");
    op->phase = PHASE_ACTIVE_DECODING;
    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");
      fail_union_operation (op);
      return;
    }
  }
  GNUNET_CADET_receive_done (op->channel);
}


/**
 * 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,
                     const struct GNUNET_SETU_Element *element,
                     enum GNUNET_SETU_Status status)
{
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_SETU_ResultMessage *rm;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "sending element (size %u) to client\n",
       element->size);
  GNUNET_assert (0 != op->client_request_id);
  ev = GNUNET_MQ_msg_extra (rm,
                            element->size,
                            GNUNET_MESSAGE_TYPE_SETU_RESULT);
  if (NULL == ev)
  {
    GNUNET_MQ_discard (ev);
    GNUNET_break (0);
    return;
  }
  rm->result_status = htons (status);
  rm->request_id = htonl (op->client_request_id);
  rm->element_type = htons (element->element_type);
  rm->current_size = GNUNET_htonll (GNUNET_CONTAINER_multihashmap32_size (
                                      op->key_to_element));
  GNUNET_memcpy (&rm[1],
                 element->data,
                 element->size);
  GNUNET_MQ_send (op->set->cs->mq,
                  ev);
}


/**
 * Tests if the operation is finished, and if so notify.
 *
 * @param op operation to check
 */
static void
maybe_finish (struct Operation *op)
{
  unsigned int num_demanded;

  num_demanded = GNUNET_CONTAINER_multihashmap_size (
    op->demanded_hashes);
  int send_done  =  GNUNET_CONTAINER_multihashmap_iterate (
    op->message_control_flow,
    &
    determinate_done_message_iterator,
    op);
  if (PHASE_FINISH_WAITING == op->phase)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "In PHASE_FINISH_WAITING, pending %u demands -> %d\n",
         num_demanded, op->peer_site);
    if (-1 != send_done)
    {
      struct GNUNET_MQ_Envelope *ev;

      op->phase = PHASE_FINISHED;
#if MEASURE_PERFORMANCE
      perf_store.done.sent += 1;
#endif
      ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SETU_P2P_DONE);
      GNUNET_MQ_send (op->mq,
                      ev);
      /* We now wait until the other peer sends P2P_OVER
       * after it got all elements from us. */
    }
  }
  if (PHASE_FINISH_CLOSING == op->phase)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "In PHASE_FINISH_CLOSING, pending %u demands %d\n",
         num_demanded, op->peer_site);
    if (-1 != send_done)
    {
      op->phase = PHASE_FINISHED;
      send_client_done (op);
      _GSS_operation_destroy2 (op);
    }
  }
}


/**
 * Check an element message from a remote peer.
 *
 * @param cls the union operation
 * @param emsg the message
 */
static int
check_union_p2p_elements (void *cls,
                          const struct GNUNET_SETU_ElementMessage *emsg)
{
  struct Operation *op = cls;

  if (0 == GNUNET_CONTAINER_multihashmap_size (op->demanded_hashes))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handle an element message from a remote peer.
 * Sent by the other peer either because we decoded an IBF and placed a demand,
 * or because the other peer switched to full set transmission.
 *
 * @param cls the union operation
 * @param emsg the message
 */
static void
handle_union_p2p_elements (void *cls,
                           const struct GNUNET_SETU_ElementMessage *emsg)
{
  struct Operation *op = cls;
  struct ElementEntry *ee;
  struct KeyEntry *ke;
  uint16_t element_size;

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_ACTIVE_DECODING, PHASE_PASSIVE_DECODING,
                              PHASE_FINISH_WAITING, PHASE_FINISH_CLOSING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  element_size = ntohs (emsg->header.size) - sizeof(struct
                                                    GNUNET_SETU_ElementMessage);
#if MEASURE_PERFORMANCE
  perf_store.element.received += 1;
  perf_store.element.received_var_bytes += element_size;
#endif

  ee = GNUNET_malloc (sizeof(struct ElementEntry) + element_size);
  GNUNET_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_SETU_element_hash (&ee->element,
                            &ee->element_hash);
  if (GNUNET_NO ==
      GNUNET_CONTAINER_multihashmap_remove (op->demanded_hashes,
                                            &ee->element_hash,
                                            NULL))
  {
    /* We got something we didn't demand, since it's not in our map. */
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  if (GNUNET_OK !=
      update_message_control_flow (
        op->message_control_flow,
        MSG_CFS_RECEIVED,
        &ee->element_hash,
        ELEMENT_MESSAGE)
      )
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "An element has been received more than once!\n");
    GNUNET_break (0);
    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);

  op->received_total++;

  ke = op_get_element (op,
                       &ee->element_hash);
  if (NULL != ke)
  {
    /* Got repeated element.  Should not happen since
     * we track demands. */
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# repeated elements",
                              1,
                              GNUNET_NO);
    ke->received = GNUNET_YES;
    GNUNET_free (ee);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Registering new element from remote peer\n");
    op->received_fresh++;
    op_register_element (op, ee, GNUNET_YES);
    /* only send results immediately if the client wants it */
    send_client_element (op,
                         &ee->element,
                         GNUNET_SETU_STATUS_ADD_LOCAL);
  }

  if ((op->received_total > 8) &&
      (op->received_fresh < op->received_total / 3))
  {
    /* The other peer gave us lots of old elements, there's something wrong. */
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  GNUNET_CADET_receive_done (op->channel);
  maybe_finish (op);
}


/**
 * Check a full element message from a remote peer.
 *
 * @param cls the union operation
 * @param emsg the message
 */
static int
check_union_p2p_full_element (void *cls,
                              const struct GNUNET_SETU_ElementMessage *emsg)
{
  struct Operation *op = cls;

  (void) op;

  // FIXME: check that we expect full elements here?
  return GNUNET_OK;
}


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

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_FULL_RECEIVING, PHASE_FULL_SENDING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  element_size = ntohs (emsg->header.size)
                 - sizeof(struct GNUNET_SETU_ElementMessage);

#if MEASURE_PERFORMANCE
  perf_store.element_full.received += 1;
  perf_store.element_full.received_var_bytes += element_size;
#endif

  ee = GNUNET_malloc (sizeof(struct ElementEntry) + element_size);
  GNUNET_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_SETU_element_hash (&ee->element,
                            &ee->element_hash);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got element (full diff, 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);

  op->received_total++;
  ke = op_get_element (op,
                       &ee->element_hash);
  if (NULL != ke)
  {
    GNUNET_STATISTICS_update (_GSS_statistics,
                              "# repeated elements",
                              1,
                              GNUNET_NO);
    full_sync_plausibility_check (op);
    ke->received = GNUNET_YES;
    GNUNET_free (ee);
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Registering new element from remote peer\n");
    op->received_fresh++;
    op_register_element (op, ee, GNUNET_YES);
    /* only send results immediately if the client wants it */
    send_client_element (op,
                         &ee->element,
                         GNUNET_SETU_STATUS_ADD_LOCAL);
  }


  if ((GNUNET_YES == op->byzantine) &&
      (op->received_total > op->remote_element_count) )
  {
    /* The other peer gave us lots of old elements, there's something wrong. */
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Other peer sent %llu elements while pretending to have %llu elements, failing operation\n",
         (unsigned long long) op->received_total,
         (unsigned long long) op->remote_element_count);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  GNUNET_CADET_receive_done (op->channel);
}


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

  if (op->phase != PHASE_PASSIVE_DECODING)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  num_keys = (ntohs (msg->header.size) - sizeof(struct InquiryMessage))
             / sizeof(struct IBF_Key);
  if ((ntohs (msg->header.size) - sizeof(struct InquiryMessage))
      != num_keys * sizeof(struct IBF_Key))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


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

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_ACTIVE_DECODING, PHASE_PASSIVE_DECODING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

#if MEASURE_PERFORMANCE
  perf_store.inquery.received += 1;
  perf_store.inquery.received_var_bytes += (ntohs (msg->header.size)
                                            - sizeof(struct InquiryMessage));
#endif

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received union inquiry\n");
  num_keys = (ntohs (msg->header.size) - sizeof(struct InquiryMessage))
             / sizeof(struct IBF_Key);
  ibf_key = (const struct IBF_Key *) &msg[1];

  /** Add received inquiries to hashmap for flow control **/
  struct GNUNET_HashContext *hashed_key_context =
    GNUNET_CRYPTO_hash_context_start ();
  struct GNUNET_HashCode *hashed_key = (struct GNUNET_HashCode*) GNUNET_malloc (
    sizeof(struct GNUNET_HashCode));;
  enum MESSAGE_CONTROL_FLOW_STATE mcfs = MSG_CFS_RECEIVED;
  GNUNET_CRYPTO_hash_context_read (hashed_key_context,
                                   &ibf_key,
                                   sizeof(struct IBF_Key));
  GNUNET_CRYPTO_hash_context_finish (hashed_key_context,
                                     hashed_key);
  GNUNET_CONTAINER_multihashmap_put (op->inquiries_sent,
                                     hashed_key,
                                     &mcfs,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE
                                     );

  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++;
  }
  GNUNET_CADET_receive_done (op->channel);
}


/**
 * 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
send_missing_full_elements_iter (void *cls,
                                 uint32_t key,
                                 void *value)
{
  struct Operation *op = cls;
  struct KeyEntry *ke = value;
  struct GNUNET_MQ_Envelope *ev;
  struct GNUNET_SETU_ElementMessage *emsg;
  struct ElementEntry *ee = ke->element;

  if (GNUNET_YES == ke->received)
    return GNUNET_YES;
#if MEASURE_PERFORMANCE
  perf_store.element_full.received += 1;
#endif
  ev = GNUNET_MQ_msg_extra (emsg,
                            ee->element.size,
                            GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_ELEMENT);
  GNUNET_memcpy (&emsg[1],
                 ee->element.data,
                 ee->element.size);
  emsg->element_type = htons (ee->element.element_type);
  GNUNET_MQ_send (op->mq,
                  ev);
  return GNUNET_YES;
}


/**
 * Handle a request for full set transmission.
 *
 * @param cls closure, a set union operation
 * @param mh the demand message
 */
static int
check_union_p2p_request_full (void *cls,
                              const struct TransmitFullMessage *mh)
{
  return GNUNET_OK;
}


static void
handle_union_p2p_request_full (void *cls,
                               const struct TransmitFullMessage *msg)
{
  struct Operation *op = cls;

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_EXPECT_IBF};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  op->remote_element_count = ntohl (msg->remote_set_size);
  op->remote_set_diff = ntohl (msg->remote_set_difference);
  op->local_set_diff = ntohl (msg->local_set_difference);


  if (check_byzantine_bounds (op) != GNUNET_OK)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Parameters transmitted from other peer do not satisfie byzantine "
         "criteria\n");
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

#if MEASURE_PERFORMANCE
  perf_store.request_full.received += 1;
#endif

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received request for full set transmission\n");

  /** Calculate avg element size if not initial sync **/
  op->local_element_count = GNUNET_CONTAINER_multihashmap_size (
    op->set->content->elements);
  uint64_t avg_element_size = 0;
  if (0 < op->local_element_count)
  {
    op->total_elements_size_local = 0;
    GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                           &
                                           determinate_avg_element_size_iterator,
                                           op);
    avg_element_size = op->total_elements_size_local / op->local_element_count;
  }

  int mode_of_operation = estimate_best_mode_of_operation (avg_element_size,
                                                           op->
                                                           remote_element_count,
                                                           op->
                                                           local_element_count,
                                                           op->local_set_diff,
                                                           op->remote_set_diff,
                                                           op->
                                                           rtt_bandwidth_tradeoff,
                                                           op->
                                                           ibf_bucket_number_factor);
  if (FULL_SYNC_REMOTE_SENDING_FIRST != mode_of_operation)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Remote peer choose to request the full set first but correct mode would have been"
         " : %d\n", mode_of_operation);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }

  // FIXME: we need to check that our set is larger than the
  // byzantine_lower_bound by some threshold
  send_full_set (op);
  GNUNET_CADET_receive_done (op->channel);
}


/**
 * Handle a "full done" message.
 *
 * @param cls closure, a set union operation
 * @param mh the demand message
 */
static void
handle_union_p2p_full_done (void *cls,
                            const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_FULL_SENDING, PHASE_FULL_RECEIVING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

#if MEASURE_PERFORMANCE
  perf_store.full_done.received += 1;
#endif

  switch (op->phase)
  {
  case PHASE_FULL_RECEIVING:
    {
      struct GNUNET_MQ_Envelope *ev;

      if ((GNUNET_YES == op->byzantine) &&
          (op->received_total != op->remote_element_count) )
      {
        /* The other peer gave not enough elements before sending full done, there's something wrong. */
        LOG (GNUNET_ERROR_TYPE_ERROR,
             "Other peer sent only %llu/%llu fresh elements, failing operation\n",
             (unsigned long long) op->received_total,
             (unsigned long long) op->remote_element_count);
        GNUNET_break_op (0);
        fail_union_operation (op);
        return;
      }

      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "got FULL DONE, sending elements that other peer is missing\n");

      /* send all the elements that did not come from the remote peer */
      GNUNET_CONTAINER_multihashmap32_iterate (op->key_to_element,
                                               &send_missing_full_elements_iter,
                                               op);
#if MEASURE_PERFORMANCE
      perf_store.full_done.sent += 1;
#endif
      ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_DONE);
      GNUNET_MQ_send (op->mq,
                      ev);
      op->phase = PHASE_FINISHED;
      /* we now wait until the other peer sends us the OVER message*/
    }
    break;

  case PHASE_FULL_SENDING:
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "got FULL DONE, finishing\n");
      /* We sent the full set, and got the response for that.  We're done. */
      op->phase = PHASE_FINISHED;
      GNUNET_CADET_receive_done (op->channel);
      send_client_done (op);
      _GSS_operation_destroy2 (op);
      return;
    }

  default:
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Handle full done phase is %u\n",
                (unsigned) op->phase);
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
  GNUNET_CADET_receive_done (op->channel);
}


/**
 * Check a demand by the other peer for elements based on a list
 * of `struct GNUNET_HashCode`s.
 *
 * @param cls closure, a set union operation
 * @param mh the demand message
 * @return #GNUNET_OK if @a mh is well-formed
 */
static int
check_union_p2p_demand (void *cls,
                        const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  unsigned int num_hashes;

  (void) op;
  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);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handle a demand by the other peer for elements based on a list
 * of `struct GNUNET_HashCode`s.
 *
 * @param cls closure, a set union operation
 * @param mh the demand message
 */
static void
handle_union_p2p_demand (void *cls,
                         const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  struct ElementEntry *ee;
  struct GNUNET_SETU_ElementMessage *emsg;
  const struct GNUNET_HashCode *hash;
  unsigned int num_hashes;
  struct GNUNET_MQ_Envelope *ev;

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_ACTIVE_DECODING, PHASE_PASSIVE_DECODING,
                              PHASE_FINISH_WAITING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }
#if MEASURE_PERFORMANCE
  perf_store.demand.received += 1;
  perf_store.demand.received_var_bytes += (ntohs (mh->size) - sizeof(struct
                                                                     GNUNET_MessageHeader));
#endif

  num_hashes = (ntohs (mh->size) - sizeof(struct GNUNET_MessageHeader))
               / sizeof(struct GNUNET_HashCode);
  for (hash = (const struct GNUNET_HashCode *) &mh[1];
       num_hashes > 0;
       hash++, num_hashes--)
  {
    ee = GNUNET_CONTAINER_multihashmap_get (op->set->content->elements,
                                            hash);
    if (NULL == ee)
    {
      /* Demand for non-existing element. */
      GNUNET_break_op (0);
      fail_union_operation (op);
      return;
    }

    /* Save send demand message for message control */
    if (GNUNET_YES !=
        update_message_control_flow (
          op->message_control_flow,
          MSG_CFS_RECEIVED,
          &ee->element_hash,
          DEMAND_MESSAGE)
        )
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Double demand message received found!\n");
      GNUNET_break (0);
      fail_union_operation (op);
      return;
    }
    ;

    /* Mark element to be expected to received */
    if (GNUNET_YES !=
        update_message_control_flow (
          op->message_control_flow,
          MSG_CFS_SENT,
          &ee->element_hash,
          ELEMENT_MESSAGE)
        )
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Double element message sent found!\n");
      GNUNET_break (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;
    }
#if MEASURE_PERFORMANCE
    perf_store.element.sent += 1;
    perf_store.element.sent_var_bytes += ee->element.size;
#endif
    ev = GNUNET_MQ_msg_extra (emsg,
                              ee->element.size,
                              GNUNET_MESSAGE_TYPE_SETU_P2P_ELEMENTS);
    GNUNET_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 %p] Sending demanded element (size %u, hash %s) to peer\n",
         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);
    if (op->symmetric)
      send_client_element (op,
                           &ee->element,
                           GNUNET_SETU_STATUS_ADD_REMOTE);
  }
  GNUNET_CADET_receive_done (op->channel);
  maybe_finish (op);
}


/**
 * Check offer (of `struct GNUNET_HashCode`s).
 *
 * @param cls the union operation
 * @param mh the message
 * @return #GNUNET_OK if @a mh is well-formed
 */
static int
check_union_p2p_offer (void *cls,
                       const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  unsigned int num_hashes;

  /* look up elements and send them */
  if ((op->phase != PHASE_PASSIVE_DECODING) &&
      (op->phase != PHASE_ACTIVE_DECODING))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  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);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handle offers (of `struct GNUNET_HashCode`s) and
 * respond with demands (of `struct GNUNET_HashCode`s).
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_union_p2p_offer (void *cls,
                        const struct GNUNET_MessageHeader *mh)
{
  struct Operation *op = cls;
  const struct GNUNET_HashCode *hash;
  unsigned int num_hashes;
  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_ACTIVE_DECODING, PHASE_PASSIVE_DECODING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

#if MEASURE_PERFORMANCE
  perf_store.offer.received += 1;
  perf_store.offer.received_var_bytes += (ntohs (mh->size) - sizeof(struct
                                                                    GNUNET_MessageHeader));
#endif

  num_hashes = (ntohs (mh->size) - sizeof(struct GNUNET_MessageHeader))
               / sizeof(struct GNUNET_HashCode);
  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->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->demanded_hashes,
                                                hash))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Skipped sending duplicate demand\n");
      continue;
    }

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

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "[OP %p] Requesting element (hash %s)\n",
         op, GNUNET_h2s (hash));

#if MEASURE_PERFORMANCE
    perf_store.demand.sent += 1;
    perf_store.demand.sent_var_bytes += sizeof(struct GNUNET_HashCode);
#endif
    /* Save send demand message for message control */
    if (GNUNET_YES !=
        update_message_control_flow (
          op->message_control_flow,
          MSG_CFS_SENT,
          hash,
          DEMAND_MESSAGE))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Double demand message sent found!\n");
      GNUNET_break (0);
      fail_union_operation (op);
      return;
    }

    /* Mark offer as received received */
    if (GNUNET_YES !=
        update_message_control_flow (
          op->message_control_flow,
          MSG_CFS_RECEIVED,
          hash,
          OFFER_MESSAGE))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Double offer message received found!\n");
      GNUNET_break (0);
      fail_union_operation (op);
      return;
    }
    /* Mark element to be expected to received */
    if (GNUNET_YES !=
        update_message_control_flow (
          op->message_control_flow,
          MSG_CFS_EXPECTED,
          hash,
          ELEMENT_MESSAGE))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           "Element already expected!\n");
      GNUNET_break (0);
      fail_union_operation (op);
      return;
    }
    ev = GNUNET_MQ_msg_header_extra (demands,
                                     sizeof(struct GNUNET_HashCode),
                                     GNUNET_MESSAGE_TYPE_SETU_P2P_DEMAND);
    GNUNET_memcpy (&demands[1],
                   hash,
                   sizeof(struct GNUNET_HashCode));
    GNUNET_MQ_send (op->mq, ev);
  }
  GNUNET_CADET_receive_done (op->channel);
}


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

  /**
  * Check that the message is received only in supported phase
  */
  uint8_t allowed_phases[] = {PHASE_ACTIVE_DECODING, PHASE_PASSIVE_DECODING};
  if (GNUNET_OK !=
      check_valid_phase (allowed_phases,sizeof(allowed_phases),op))
  {
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

  if (op->active_passive_switch_required)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "PROTOCOL VIOLATION: Received done but role change is necessary\n");
    GNUNET_break (0);
    fail_union_operation (op);
    return;
  }

#if MEASURE_PERFORMANCE
  perf_store.done.received += 1;
#endif
  switch (op->phase)
  {
  case PHASE_PASSIVE_DECODING:
    /* We got all requests, but still have to send our elements in response. */
    op->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 it everything.
         */GNUNET_CADET_receive_done (op->channel);
    maybe_finish (op);
    return;
  case PHASE_ACTIVE_DECODING:
    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->phase = PHASE_FINISH_CLOSING;
    GNUNET_CADET_receive_done (op->channel);
    maybe_finish (op);
    return;
  default:
    GNUNET_break_op (0);
    fail_union_operation (op);
    return;
  }
}


/**
 * Handle a over message from a remote peer
 *
 * @param cls the union operation
 * @param mh the message
 */
static void
handle_union_p2p_over (void *cls,
                       const struct GNUNET_MessageHeader *mh)
{
#if MEASURE_PERFORMANCE
  perf_store.over.received += 1;
#endif
  send_client_done (cls);
}


/**
 * Get the incoming socket associated with the given id.
 *
 * @param listener the listener to look in
 * @param id id to look for
 * @return the incoming socket associated with the id,
 *         or NULL if there is none
 */
static struct Operation *
get_incoming (uint32_t id)
{
  for (struct Listener *listener = listener_head;
       NULL != listener;
       listener = listener->next)
  {
    for (struct Operation *op = listener->op_head;
         NULL != op;
         op = op->next)
      if (op->suggest_id == id)
        return op;
  }
  return NULL;
}


/**
 * Callback called when a client connects to the service.
 *
 * @param cls closure for the service
 * @param c the new client that connected to the service
 * @param mq the message queue used to send messages to the client
 * @return @a `struct ClientState`
 */
static void *
client_connect_cb (void *cls,
                   struct GNUNET_SERVICE_Client *c,
                   struct GNUNET_MQ_Handle *mq)
{
  struct ClientState *cs;

  num_clients++;
  cs = GNUNET_new (struct ClientState);
  cs->client = c;
  cs->mq = mq;
  return cs;
}


/**
 * Iterator over hash map entries to free element entries.
 *
 * @param cls closure
 * @param key current key code
 * @param value a `struct ElementEntry *` to be free'd
 * @return #GNUNET_YES (continue to iterate)
 */
static int
destroy_elements_iterator (void *cls,
                           const struct GNUNET_HashCode *key,
                           void *value)
{
  struct ElementEntry *ee = value;

  GNUNET_free (ee);
  return GNUNET_YES;
}


/**
 * Clean up after a client has disconnected
 *
 * @param cls closure, unused
 * @param client the client to clean up after
 * @param internal_cls the `struct ClientState`
 */
static void
client_disconnect_cb (void *cls,
                      struct GNUNET_SERVICE_Client *client,
                      void *internal_cls)
{
  struct ClientState *cs = internal_cls;
  struct Operation *op;
  struct Listener *listener;
  struct Set *set;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Client disconnected, cleaning up\n");
  if (NULL != (set = cs->set))
  {
    struct SetContent *content = set->content;

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Destroying client's set\n");
    /* Destroy pending set operations */
    while (NULL != set->ops_head)
      _GSS_operation_destroy (set->ops_head);

    /* Destroy operation-specific state */
    if (NULL != set->se)
    {
      strata_estimator_destroy (set->se);
      set->se = NULL;
    }
    /* free set content (or at least decrement RC) */
    set->content = NULL;
    GNUNET_assert (0 != content->refcount);
    content->refcount--;
    if (0 == content->refcount)
    {
      GNUNET_assert (NULL != content->elements);
      GNUNET_CONTAINER_multihashmap_iterate (content->elements,
                                             &destroy_elements_iterator,
                                             NULL);
      GNUNET_CONTAINER_multihashmap_destroy (content->elements);
      content->elements = NULL;
      GNUNET_free (content);
    }
    GNUNET_free (set);
  }

  if (NULL != (listener = cs->listener))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Destroying client's listener\n");
    GNUNET_CADET_close_port (listener->open_port);
    listener->open_port = NULL;
    while (NULL != (op = listener->op_head))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Destroying incoming operation `%u' from peer `%s'\n",
                  (unsigned int) op->client_request_id,
                  GNUNET_i2s (&op->peer));
      incoming_destroy (op);
    }
    GNUNET_CONTAINER_DLL_remove (listener_head,
                                 listener_tail,
                                 listener);
    GNUNET_free (listener);
  }
  GNUNET_free (cs);
  num_clients--;
  if ( (GNUNET_YES == in_shutdown) &&
       (0 == num_clients) )
  {
    if (NULL != cadet)
    {
      GNUNET_CADET_disconnect (cadet);
      cadet = NULL;
    }
  }
}


/**
 * Check a request for a set operation from another peer.
 *
 * @param cls the operation state
 * @param msg the received message
 * @return #GNUNET_OK if the channel should be kept alive,
 *         #GNUNET_SYSERR to destroy the channel
 */
static int
check_incoming_msg (void *cls,
                    const struct OperationRequestMessage *msg)
{
  struct Operation *op = cls;
  struct Listener *listener = op->listener;
  const struct GNUNET_MessageHeader *nested_context;

  /* double operation request */
  if (0 != op->suggest_id)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  /* This should be equivalent to the previous condition, but can't hurt to check twice */
  if (NULL == listener)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  nested_context = GNUNET_MQ_extract_nested_mh (msg);
  if ((NULL != nested_context) &&
      (ntohs (nested_context->size) > GNUNET_SETU_CONTEXT_MESSAGE_MAX_SIZE))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handle a request for a set operation from another peer.  Checks if we
 * have a listener waiting for such a request (and in that case initiates
 * asking the listener about accepting the connection). If no listener
 * is waiting, we queue the operation request in hope that a listener
 * shows up soon (before timeout).
 *
 * This msg is expected as the first and only msg handled through the
 * non-operation bound virtual table, acceptance of this operation replaces
 * our virtual table and subsequent msgs would be routed differently (as
 * we then know what type of operation this is).
 *
 * @param cls the operation state
 * @param msg the received message
 */
static void
handle_incoming_msg (void *cls,
                     const struct OperationRequestMessage *msg)
{
  struct Operation *op = cls;
  struct Listener *listener = op->listener;
  const struct GNUNET_MessageHeader *nested_context;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_SETU_RequestMessage *cmsg;

  nested_context = GNUNET_MQ_extract_nested_mh (msg);
  /* Make a copy of the nested_context (application-specific context
     information that is opaque to set) so we can pass it to the
     listener later on */
  if (NULL != nested_context)
    op->context_msg = GNUNET_copy_message (nested_context);
  op->remote_element_count = ntohl (msg->element_count);
  GNUNET_log (
    GNUNET_ERROR_TYPE_DEBUG,
    "Received P2P operation request (port %s) for active listener\n",
    GNUNET_h2s (&op->listener->app_id));
  GNUNET_assert (0 == op->suggest_id);
  if (0 == suggest_id)
    suggest_id++;
  op->suggest_id = suggest_id++;
  GNUNET_assert (NULL != op->timeout_task);
  GNUNET_SCHEDULER_cancel (op->timeout_task);
  op->timeout_task = NULL;
  env = GNUNET_MQ_msg_nested_mh (cmsg,
                                 GNUNET_MESSAGE_TYPE_SETU_REQUEST,
                                 op->context_msg);
  GNUNET_log (
    GNUNET_ERROR_TYPE_DEBUG,
    "Suggesting incoming request with accept id %u to listener %p of client %p\n",
    op->suggest_id,
    listener,
    listener->cs);
  cmsg->accept_id = htonl (op->suggest_id);
  cmsg->peer_id = op->peer;
  GNUNET_MQ_send (listener->cs->mq,
                  env);
  /* NOTE: GNUNET_CADET_receive_done() will be called in
   #handle_client_accept() */
}


/**
 * Called when a client wants to create a new set.  This is typically
 * the first request from a client, and includes the type of set
 * operation to be performed.
 *
 * @param cls client that sent the message
 * @param m message sent by the client
 */
static void
handle_client_create_set (void *cls,
                          const struct GNUNET_SETU_CreateMessage *msg)
{
  struct ClientState *cs = cls;
  struct Set *set;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Client created new set for union operation\n");
  if (NULL != cs->set)
  {
    /* There can only be one set per client */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  set = GNUNET_new (struct Set);
  {
    struct MultiStrataEstimator *se;

    se = strata_estimator_create (SE_STRATA_COUNT,
                                  SE_IBFS_TOTAL_SIZE,
                                  SE_IBF_HASH_NUM);
    if (NULL == se)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Failed to allocate strata estimator\n");
      GNUNET_free (set);
      GNUNET_SERVICE_client_drop (cs->client);
      return;
    }
    set->se = se;
  }
  set->content = GNUNET_new (struct SetContent);
  set->content->refcount = 1;
  set->content->elements = GNUNET_CONTAINER_multihashmap_create (1,
                                                                 GNUNET_YES);
  set->cs = cs;
  cs->set = set;
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Timeout happens iff:
 *  - we suggested an operation to our listener,
 *    but did not receive a response in time
 *  - we got the channel from a peer but no #GNUNET_MESSAGE_TYPE_SETU_P2P_OPERATION_REQUEST
 *
 * @param cls channel context
 * @param tc context information (why was this task triggered now)
 */
static void
incoming_timeout_cb (void *cls)
{
  struct Operation *op = cls;

  op->timeout_task = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Remote peer's incoming request timed out\n");
  incoming_destroy (op);
}


/**
 * Method called whenever another peer has added us to a channel the
 * other peer initiated.  Only called (once) upon reception of data
 * from a channel we listen on.
 *
 * The channel context represents the operation itself and gets added
 * to a DLL, from where it gets looked up when our local listener
 * client responds to a proposed/suggested operation or connects and
 * associates with this operation.
 *
 * @param cls closure
 * @param channel new handle to the channel
 * @param source peer that started the channel
 * @return initial channel context for the channel
 *         returns NULL on error
 */
static void *
channel_new_cb (void *cls,
                struct GNUNET_CADET_Channel *channel,
                const struct GNUNET_PeerIdentity *source)
{
  struct Listener *listener = cls;
  struct Operation *op;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New incoming channel\n");
  op = GNUNET_new (struct Operation);
  op->listener = listener;
  op->peer = *source;
  op->channel = channel;
  op->mq = GNUNET_CADET_get_mq (op->channel);
  op->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
                                       UINT32_MAX);
  op->timeout_task = GNUNET_SCHEDULER_add_delayed (INCOMING_CHANNEL_TIMEOUT,
                                                   &incoming_timeout_cb,
                                                   op);
  GNUNET_CONTAINER_DLL_insert (listener->op_head,
                               listener->op_tail,
                               op);
  return op;
}


/**
 * Function called whenever a channel is destroyed.  Should clean up
 * any associated state.  It must NOT call
 * GNUNET_CADET_channel_destroy() on the channel.
 *
 * The peer_disconnect function is part of a a virtual table set initially either
 * when a peer creates a new channel with us, or once we create
 * a new channel ourselves (evaluate).
 *
 * Once we know the exact type of operation (union/intersection), the vt is
 * replaced with an operation specific instance (_GSS_[op]_vt).
 *
 * @param channel_ctx place where local state associated
 *                   with the channel is stored
 * @param channel connection to the other end (henceforth invalid)
 */
static void
channel_end_cb (void *channel_ctx,
                const struct GNUNET_CADET_Channel *channel)
{
  struct Operation *op = channel_ctx;

  op->channel = NULL;
  _GSS_operation_destroy2 (op);
}


/**
 * Function called whenever an MQ-channel's transmission window size changes.
 *
 * The first callback in an outgoing channel will be with a non-zero value
 * and will mean the channel is connected to the destination.
 *
 * For an incoming channel it will be called immediately after the
 * #GNUNET_CADET_ConnectEventHandler, also with a non-zero value.
 *
 * @param cls Channel closure.
 * @param channel Connection to the other end (henceforth invalid).
 * @param window_size New window size. If the is more messages than buffer size
 *                    this value will be negative..
 */
static void
channel_window_cb (void *cls,
                   const struct GNUNET_CADET_Channel *channel,
                   int window_size)
{
  /* FIXME: not implemented, we could do flow control here... */
}


/**
 * Called when a client wants to create a new listener.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 */

static void
handle_client_listen (void *cls,
                      const struct GNUNET_SETU_ListenMessage *msg)
{
  struct ClientState *cs = cls;
  struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
    GNUNET_MQ_hd_var_size (incoming_msg,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_OPERATION_REQUEST,
                           struct OperationRequestMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_ibf,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_IBF,
                           struct IBFMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_elements,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_ELEMENTS,
                           struct GNUNET_SETU_ElementMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_offer,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_OFFER,
                           struct GNUNET_MessageHeader,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_inquiry,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_INQUIRY,
                           struct InquiryMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_demand,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_DEMAND,
                           struct GNUNET_MessageHeader,
                           NULL),
    GNUNET_MQ_hd_fixed_size (union_p2p_done,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_DONE,
                             struct GNUNET_MessageHeader,
                             NULL),
    GNUNET_MQ_hd_fixed_size (union_p2p_over,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_OVER,
                             struct GNUNET_MessageHeader,
                             NULL),
    GNUNET_MQ_hd_fixed_size (union_p2p_full_done,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_DONE,
                             struct GNUNET_MessageHeader,
                             NULL),
    GNUNET_MQ_hd_var_size (union_p2p_request_full,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_REQUEST_FULL,
                           struct TransmitFullMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_strata_estimator,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SE,
                           struct StrataEstimatorMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_strata_estimator,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SEC,
                           struct StrataEstimatorMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_full_element,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_ELEMENT,
                           struct GNUNET_SETU_ElementMessage,
                           NULL),
    GNUNET_MQ_hd_var_size (union_p2p_send_full,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SEND_FULL,
                           struct TransmitFullMessage,
                           NULL),
    GNUNET_MQ_handler_end ()
  };
  struct Listener *listener;

  if (NULL != cs->listener)
  {
    /* max. one active listener per client! */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  listener = GNUNET_new (struct Listener);
  listener->cs = cs;
  cs->listener = listener;
  listener->app_id = msg->app_id;
  GNUNET_CONTAINER_DLL_insert (listener_head,
                               listener_tail,
                               listener);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "New listener created (port %s)\n",
              GNUNET_h2s (&listener->app_id));
  listener->open_port = GNUNET_CADET_open_port (cadet,
                                                &msg->app_id,
                                                &channel_new_cb,
                                                listener,
                                                &channel_window_cb,
                                                &channel_end_cb,
                                                cadet_handlers);
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Called when the listening client rejects an operation
 * request by another peer.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 */
static void
handle_client_reject (void *cls,
                      const struct GNUNET_SETU_RejectMessage *msg)
{
  struct ClientState *cs = cls;
  struct Operation *op;

  op = get_incoming (ntohl (msg->accept_reject_id));
  if (NULL == op)
  {
    /* no matching incoming operation for this reject;
       could be that the other peer already disconnected... */
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Client rejected unknown operation %u\n",
                (unsigned int) ntohl (msg->accept_reject_id));
    GNUNET_SERVICE_client_continue (cs->client);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Peer request (app %s) rejected by client\n",
              GNUNET_h2s (&cs->listener->app_id));
  _GSS_operation_destroy2 (op);
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Called when a client wants to add or remove an element to a set it inhabits.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 */
static int
check_client_set_add (void *cls,
                      const struct GNUNET_SETU_ElementMessage *msg)
{
  /* NOTE: Technically, we should probably check with the
     block library whether the element we are given is well-formed */
  return GNUNET_OK;
}


/**
 * Called when a client wants to add or remove an element to a set it inhabits.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 */
static void
handle_client_set_add (void *cls,
                       const struct GNUNET_SETU_ElementMessage *msg)
{
  struct ClientState *cs = cls;
  struct Set *set;
  struct GNUNET_SETU_Element el;
  struct ElementEntry *ee;
  struct GNUNET_HashCode hash;

  if (NULL == (set = cs->set))
  {
    /* client without a set requested an operation */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  GNUNET_SERVICE_client_continue (cs->client);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing mutation on set\n");
  el.size = ntohs (msg->header.size) - sizeof(*msg);
  el.data = &msg[1];
  el.element_type = ntohs (msg->element_type);
  GNUNET_SETU_element_hash (&el,
                            &hash);
  ee = GNUNET_CONTAINER_multihashmap_get (set->content->elements,
                                          &hash);
  if (NULL == ee)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Client inserts element %s of size %u\n",
                GNUNET_h2s (&hash),
                el.size);
    ee = GNUNET_malloc (el.size + sizeof(*ee));
    ee->element.size = el.size;
    GNUNET_memcpy (&ee[1], el.data, el.size);
    ee->element.data = &ee[1];
    ee->element.element_type = el.element_type;
    ee->remote = GNUNET_NO;
    ee->generation = set->current_generation;
    ee->element_hash = hash;
    GNUNET_break (GNUNET_YES ==
                  GNUNET_CONTAINER_multihashmap_put (
                    set->content->elements,
                    &ee->element_hash,
                    ee,
                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Client inserted element %s of size %u twice (ignored)\n",
                GNUNET_h2s (&hash),
                el.size);
    /* same element inserted twice */
    return;
  }
  strata_estimator_insert (set->se,
                           get_ibf_key (&ee->element_hash));
}


/**
 * Advance the current generation of a set,
 * adding exclusion ranges if necessary.
 *
 * @param set the set where we want to advance the generation
 */
static void
advance_generation (struct Set *set)
{
  set->content->latest_generation++;
  set->current_generation++;
}


/**
 * Called when a client wants to initiate a set operation with another
 * peer.  Initiates the CADET connection to the listener and sends the
 * request.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 * @return #GNUNET_OK if the message is well-formed
 */
static int
check_client_evaluate (void *cls,
                       const struct GNUNET_SETU_EvaluateMessage *msg)
{
  /* FIXME: suboptimal, even if the context below could be NULL,
     there are malformed messages this does not check for... */
  return GNUNET_OK;
}


/**
 * Called when a client wants to initiate a set operation with another
 * peer.  Initiates the CADET connection to the listener and sends the
 * request.
 *
 * @param cls client that sent the message
 * @param msg message sent by the client
 */
static void
handle_client_evaluate (void *cls,
                        const struct GNUNET_SETU_EvaluateMessage *msg)
{
  struct ClientState *cs = cls;
  struct Operation *op = GNUNET_new (struct Operation);

  const struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
    GNUNET_MQ_hd_var_size (incoming_msg,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_OPERATION_REQUEST,
                           struct OperationRequestMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_ibf,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_IBF,
                           struct IBFMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_elements,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_ELEMENTS,
                           struct GNUNET_SETU_ElementMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_offer,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_OFFER,
                           struct GNUNET_MessageHeader,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_inquiry,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_INQUIRY,
                           struct InquiryMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_demand,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_DEMAND,
                           struct GNUNET_MessageHeader,
                           op),
    GNUNET_MQ_hd_fixed_size (union_p2p_done,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_DONE,
                             struct GNUNET_MessageHeader,
                             op),
    GNUNET_MQ_hd_fixed_size (union_p2p_over,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_OVER,
                             struct GNUNET_MessageHeader,
                             op),
    GNUNET_MQ_hd_fixed_size (union_p2p_full_done,
                             GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_DONE,
                             struct GNUNET_MessageHeader,
                             op),
    GNUNET_MQ_hd_var_size (union_p2p_request_full,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_REQUEST_FULL,
                           struct TransmitFullMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_strata_estimator,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SE,
                           struct StrataEstimatorMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_strata_estimator,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SEC,
                           struct StrataEstimatorMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_full_element,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_FULL_ELEMENT,
                           struct GNUNET_SETU_ElementMessage,
                           op),
    GNUNET_MQ_hd_var_size (union_p2p_send_full,
                           GNUNET_MESSAGE_TYPE_SETU_P2P_SEND_FULL,
                           struct TransmitFullMessage,
                           NULL),
    GNUNET_MQ_handler_end ()
  };
  struct Set *set;
  const struct GNUNET_MessageHeader *context;

  if (NULL == (set = cs->set))
  {
    GNUNET_break (0);
    GNUNET_free (op);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  op->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
                                       UINT32_MAX);
  op->peer = msg->target_peer;
  op->client_request_id = ntohl (msg->request_id);
  op->byzantine = msg->byzantine;
  op->byzantine_lower_bound = ntohl (msg->byzantine_lower_bound);
  op->force_full = msg->force_full;
  op->force_delta = msg->force_delta;
  op->symmetric = msg->symmetric;
  op->rtt_bandwidth_tradeoff = msg->bandwidth_latency_tradeoff;
  op->ibf_bucket_number_factor = msg->ibf_bucket_number_factor;
  op->ibf_number_buckets_per_element = msg->ibf_number_of_buckets_per_element;
  op->byzantine_upper_bound = msg->byzantine_upper_bond;
  op->active_passive_switch_required = false;
  context = GNUNET_MQ_extract_nested_mh (msg);

  /* create hashmap for message control */
  op->message_control_flow = GNUNET_CONTAINER_multihashmap_create (32,
                                                                   GNUNET_NO);
  op->inquiries_sent = GNUNET_CONTAINER_multihashmap_create (32,GNUNET_NO);

#if MEASURE_PERFORMANCE
  /* load config */
  load_config (op);
#endif

  /* Advance generation values, so that
     mutations won't interfer with the running operation. */
  op->set = set;
  op->generation_created = set->current_generation;
  advance_generation (set);
  GNUNET_CONTAINER_DLL_insert (set->ops_head,
                               set->ops_tail,
                               op);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Creating new CADET channel to port %s for set union\n",
              GNUNET_h2s (&msg->app_id));
  op->channel = GNUNET_CADET_channel_create (cadet,
                                             op,
                                             &msg->target_peer,
                                             &msg->app_id,
                                             &channel_window_cb,
                                             &channel_end_cb,
                                             cadet_handlers);
  op->mq = GNUNET_CADET_get_mq (op->channel);
  {
    struct GNUNET_MQ_Envelope *ev;
    struct OperationRequestMessage *msg;

#if MEASURE_PERFORMANCE
    perf_store.operation_request.sent += 1;
#endif
    ev = GNUNET_MQ_msg_nested_mh (msg,
                                  GNUNET_MESSAGE_TYPE_SETU_P2P_OPERATION_REQUEST,
                                  context);
    if (NULL == ev)
    {
      /* the context message is too large */
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (cs->client);
      return;
    }
    op->demanded_hashes = GNUNET_CONTAINER_multihashmap_create (32,
                                                                GNUNET_NO);
    /* copy the current generation's strata estimator for this operation */
    op->se = strata_estimator_dup (op->set->se);
    /* we started the operation, thus we have to send the operation request */
    op->phase = PHASE_EXPECT_SE;

    op->salt_receive = (op->peer_site + 1) % 2;
    op->salt_send = op->peer_site;     // FIXME?????


    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);
    GNUNET_MQ_send (op->mq,
                    ev);
    if (NULL != 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");
    initialize_key_to_element (op);
    op->initial_size = GNUNET_CONTAINER_multihashmap32_size (
      op->key_to_element);

  }
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Handle a request from the client to cancel a running set operation.
 *
 * @param cls the client
 * @param msg the message
 */
static void
handle_client_cancel (void *cls,
                      const struct GNUNET_SETU_CancelMessage *msg)
{
  struct ClientState *cs = cls;
  struct Set *set;
  struct Operation *op;
  int found;

  if (NULL == (set = cs->set))
  {
    /* client without a set requested an operation */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  found = GNUNET_NO;
  for (op = set->ops_head; NULL != op; op = op->next)
  {
    if (op->client_request_id == ntohl (msg->request_id))
    {
      found = GNUNET_YES;
      break;
    }
  }
  if (GNUNET_NO == found)
  {
    /* It may happen that the operation was already destroyed due to
     * the other peer disconnecting.  The client may not know about this
     * yet and try to cancel the (just barely non-existent) operation.
     * So this is not a hard error.
     *///
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Client canceled non-existent op %u\n",
                (uint32_t) ntohl (msg->request_id));
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Client requested cancel for op %u\n",
                (uint32_t) ntohl (msg->request_id));
    _GSS_operation_destroy (op);
  }
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Handle a request from the client to accept a set operation that
 * came from a remote peer.  We forward the accept to the associated
 * operation for handling
 *
 * @param cls the client
 * @param msg the message
 */
static void
handle_client_accept (void *cls,
                      const struct GNUNET_SETU_AcceptMessage *msg)
{
  struct ClientState *cs = cls;
  struct Set *set;
  struct Operation *op;
  struct GNUNET_SETU_ResultMessage *result_message;
  struct GNUNET_MQ_Envelope *ev;
  struct Listener *listener;

  if (NULL == (set = cs->set))
  {
    /* client without a set requested to accept */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (cs->client);
    return;
  }
  op = get_incoming (ntohl (msg->accept_reject_id));
  if (NULL == op)
  {
    /* It is not an error if the set op does not exist -- it may
    * have been destroyed when the partner peer disconnected. */
    GNUNET_log (
      GNUNET_ERROR_TYPE_INFO,
      "Client %p accepted request %u of listener %p that is no longer active\n",
      cs,
      ntohl (msg->accept_reject_id),
      cs->listener);
    ev = GNUNET_MQ_msg (result_message,
                        GNUNET_MESSAGE_TYPE_SETU_RESULT);
    result_message->request_id = msg->request_id;
    result_message->result_status = htons (GNUNET_SETU_STATUS_FAILURE);
    GNUNET_MQ_send (set->cs->mq, ev);
    GNUNET_SERVICE_client_continue (cs->client);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Client accepting request %u\n",
              (uint32_t) ntohl (msg->accept_reject_id));
  listener = op->listener;
  op->listener = NULL;
  GNUNET_CONTAINER_DLL_remove (listener->op_head,
                               listener->op_tail,
                               op);
  op->set = set;
  GNUNET_CONTAINER_DLL_insert (set->ops_head,
                               set->ops_tail,
                               op);
  op->client_request_id = ntohl (msg->request_id);
  op->byzantine = msg->byzantine;
  op->byzantine_lower_bound = ntohl (msg->byzantine_lower_bound);
  op->force_full = msg->force_full;
  op->force_delta = msg->force_delta;
  op->symmetric = msg->symmetric;
  op->rtt_bandwidth_tradeoff = msg->bandwidth_latency_tradeoff;
  op->ibf_bucket_number_factor = msg->ibf_bucket_number_factor;
  op->ibf_number_buckets_per_element = msg->ibf_number_of_buckets_per_element;
  op->byzantine_upper_bound = msg->byzantine_upper_bond;
  op->active_passive_switch_required = false;
  /* create hashmap for message control */
  op->message_control_flow = GNUNET_CONTAINER_multihashmap_create (32,
                                                                   GNUNET_NO);
  op->inquiries_sent = GNUNET_CONTAINER_multihashmap_create (32,GNUNET_NO);

#if MEASURE_PERFORMANCE
  /* load config */
  load_config (op);
#endif

  /* Advance generation values, so that future mutations do not
     interfer with the running operation. */
  op->generation_created = set->current_generation;
  advance_generation (set);
  GNUNET_assert (NULL == op->se);

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "accepting set union operation\n");
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of accepted union operations",
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (_GSS_statistics,
                            "# of total union operations",
                            1,
                            GNUNET_NO);
  {
    struct MultiStrataEstimator *se;
    struct GNUNET_MQ_Envelope *ev;
    struct StrataEstimatorMessage *strata_msg;
    char *buf;
    size_t len;
    uint16_t type;

    op->se = strata_estimator_dup (op->set->se);
    op->demanded_hashes = GNUNET_CONTAINER_multihashmap_create (32,
                                                                GNUNET_NO);
    op->salt_receive = (op->peer_site + 1) % 2;
    op->salt_send = op->peer_site;     // FIXME?????
    initialize_key_to_element (op);
    op->initial_size = GNUNET_CONTAINER_multihashmap32_size (
      op->key_to_element);

    /* kick off the operation */
    se = op->se;

    uint8_t se_count = 1;
    if (op->initial_size > 0)
    {
      op->total_elements_size_local = 0;
      GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
                                             &
                                             determinate_avg_element_size_iterator,
                                             op);
      se_count = determine_strata_count (
        op->total_elements_size_local / op->initial_size,
        op->initial_size);
    }
    buf = GNUNET_malloc (se->stratas[0]->strata_count * IBF_BUCKET_SIZE
                         * ((SE_IBFS_TOTAL_SIZE / 8) * se_count));
    len = strata_estimator_write (se,
                                  SE_IBFS_TOTAL_SIZE,
                                  se_count,
                                  buf);
#if MEASURE_PERFORMANCE
    perf_store.se.sent += 1;
    perf_store.se.sent_var_bytes += len;
#endif

    if (len < se->stratas[0]->strata_count * IBF_BUCKET_SIZE
        * SE_IBFS_TOTAL_SIZE)
      type = GNUNET_MESSAGE_TYPE_SETU_P2P_SEC;
    else
      type = GNUNET_MESSAGE_TYPE_SETU_P2P_SE;
    ev = GNUNET_MQ_msg_extra (strata_msg,
                              len,
                              type);
    GNUNET_memcpy (&strata_msg[1],
                   buf,
                   len);
    GNUNET_free (buf);
    strata_msg->set_size
      = GNUNET_htonll (GNUNET_CONTAINER_multihashmap_size (
                         op->set->content->elements));
    strata_msg->se_count = se_count;
    GNUNET_MQ_send (op->mq,
                    ev);
    op->phase = PHASE_EXPECT_IBF;
  }
  /* Now allow CADET to continue, as we did not do this in
   #handle_incoming_msg (as we wanted to first see if the
     local client would accept the request). */
  GNUNET_CADET_receive_done (op->channel);
  GNUNET_SERVICE_client_continue (cs->client);
}


/**
 * Called to clean up, after a shutdown has been requested.
 *
 * @param cls closure, NULL
 */
static void
shutdown_task (void *cls)
{
  /* Delay actual shutdown to allow service to disconnect clients */
  in_shutdown = GNUNET_YES;
  if (0 == num_clients)
  {
    if (NULL != cadet)
    {
      GNUNET_CADET_disconnect (cadet);
      cadet = NULL;
    }
  }
  GNUNET_STATISTICS_destroy (_GSS_statistics,
                             GNUNET_YES);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "handled shutdown request\n");
#if MEASURE_PERFORMANCE
  calculate_perf_store ();
#endif
}


/**
 * Function called by the service's run
 * method to run service-specific setup code.
 *
 * @param cls closure
 * @param cfg configuration to use
 * @param service the initialized service
 */
static void
run (void *cls,
     const struct GNUNET_CONFIGURATION_Handle *cfg,
     struct GNUNET_SERVICE_Handle *service)
{
  /* FIXME: need to modify SERVICE (!) API to allow
     us to run a shutdown task *after* clients were
     forcefully disconnected! */
  GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
                                 NULL);
  _GSS_statistics = GNUNET_STATISTICS_create ("setu",
                                              cfg);
  cadet = GNUNET_CADET_connect (cfg);
  if (NULL == cadet)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _ ("Could not connect to CADET service\n"));
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * Define "main" method using service macro.
 */
GNUNET_SERVICE_MAIN (
  "set",
  GNUNET_SERVICE_OPTION_NONE,
  &run,
  &client_connect_cb,
  &client_disconnect_cb,
  NULL,
  GNUNET_MQ_hd_fixed_size (client_accept,
                           GNUNET_MESSAGE_TYPE_SETU_ACCEPT,
                           struct GNUNET_SETU_AcceptMessage,
                           NULL),
  GNUNET_MQ_hd_var_size (client_set_add,
                         GNUNET_MESSAGE_TYPE_SETU_ADD,
                         struct GNUNET_SETU_ElementMessage,
                         NULL),
  GNUNET_MQ_hd_fixed_size (client_create_set,
                           GNUNET_MESSAGE_TYPE_SETU_CREATE,
                           struct GNUNET_SETU_CreateMessage,
                           NULL),
  GNUNET_MQ_hd_var_size (client_evaluate,
                         GNUNET_MESSAGE_TYPE_SETU_EVALUATE,
                         struct GNUNET_SETU_EvaluateMessage,
                         NULL),
  GNUNET_MQ_hd_fixed_size (client_listen,
                           GNUNET_MESSAGE_TYPE_SETU_LISTEN,
                           struct GNUNET_SETU_ListenMessage,
                           NULL),
  GNUNET_MQ_hd_fixed_size (client_reject,
                           GNUNET_MESSAGE_TYPE_SETU_REJECT,
                           struct GNUNET_SETU_RejectMessage,
                           NULL),
  GNUNET_MQ_hd_fixed_size (client_cancel,
                           GNUNET_MESSAGE_TYPE_SETU_CANCEL,
                           struct GNUNET_SETU_CancelMessage,
                           NULL),
  GNUNET_MQ_handler_end ());


/* end of gnunet-service-setu.c */