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
// Copyright (c) 2022-2024 Niko Bonnieure, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! NextGraph network protocol types
//!
//! Corresponds to the BARE schema

use core::fmt;
use std::collections::HashSet;
use std::{
    any::{Any, TypeId},
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
};

use serde::{Deserialize, Serialize};
use web_time::SystemTime;

use ng_repo::errors::*;
use ng_repo::log::*;
use ng_repo::store::Store;
use ng_repo::types::*;
use ng_repo::utils::{sign, verify};

use crate::app_protocol::*;
use crate::utils::{
    get_domain_without_port_443, is_ipv4_private, is_ipv6_private, is_private_ip, is_public_ip,
    is_public_ipv4, is_public_ipv6,
};
use crate::WS_PORT_ALTERNATE;
use crate::{actor::EActor, actors::admin::*, actors::*};

#[derive(Debug, Clone, Serialize, Deserialize)]
/// used to initiate a session at a local broker V0
pub struct Credentials {
    pub user_key: PrivKey,
    pub read_cap: ReadCap,
    pub private_store: RepoId,
    pub protected_store: RepoId,
    pub public_store: RepoId,
    pub user_master_key: SymKey,
    pub peer_priv_key: PrivKey,
}

impl Credentials {
    pub fn new_partial(user_priv_key: &PrivKey) -> Self {
        Credentials {
            user_key: user_priv_key.clone(),
            read_cap: ReadCap::nil(),
            private_store: RepoId::nil(),
            protected_store: RepoId::nil(),
            public_store: RepoId::nil(),
            user_master_key: SymKey::random(),
            peer_priv_key: PrivKey::random_ed(),
        }
    }
}

//
//  Network common types
//

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InterfaceType {
    Loopback,
    Private,
    Public,
    Invalid,
}

impl InterfaceType {
    pub fn is_ip_valid_for_type(&self, ip: &IP) -> bool {
        self.is_ipaddr_valid_for_type(&ip.into())
    }
    pub fn is_ipaddr_valid_for_type(&self, ip: &IpAddr) -> bool {
        match ip {
            IpAddr::V4(v4) => self.is_ipv4_valid_for_type(v4),
            IpAddr::V6(v6) => self.is_ipv6_valid_for_type(v6),
        }
    }

    pub fn is_ipv4_valid_for_type(&self, ip: &Ipv4Addr) -> bool {
        match self {
            InterfaceType::Loopback => ip.is_loopback(),
            InterfaceType::Public => is_public_ipv4(ip),
            // we allow to bind to link-local for IPv4
            InterfaceType::Private => is_ipv4_private(ip),
            _ => false,
        }
    }
    pub fn is_ipv6_valid_for_type(&self, ip: &Ipv6Addr) -> bool {
        match self {
            InterfaceType::Loopback => ip.is_loopback(),
            InterfaceType::Public => is_public_ipv6(ip),
            // we do NOT allow to bind to link-local for IPv6
            InterfaceType::Private => is_ipv6_private(ip),
            _ => false,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
pub struct Interface {
    pub if_type: InterfaceType,
    pub name: String,
    pub mac_addr: Option<default_net::interface::MacAddr>,
    /// List of Ipv4Net for the network interface
    pub ipv4: Vec<default_net::ip::Ipv4Net>,
    /// List of Ipv6Net for the network interface
    pub ipv6: Vec<default_net::ip::Ipv6Net>,
}

/// Bind address
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct BindAddress {
    pub port: u16,
    pub ip: IP,
}

impl BindAddress {
    pub fn to_ws_url(&self) -> String {
        format!(
            "ws://{}:{}",
            self.ip,
            if self.port == 0 { 80 } else { self.port }
        )
    }
    pub fn new_localhost_with_port(port: u16) -> Self {
        BindAddress {
            ip: LOOPBACK_IPV4.clone(),
            port,
        }
    }
}

impl From<&SocketAddr> for BindAddress {
    #[inline]
    fn from(addr: &SocketAddr) -> BindAddress {
        let ip_addr = addr.ip();
        let ip = IP::try_from(&ip_addr).unwrap();
        let port = addr.port();
        BindAddress { ip, port }
    }
}

//
// BROKER common types
//

/// Core Broker connection details Version 0
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct BrokerCoreV0 {
    /// peerId of the server
    pub peer_id: PubKey,

    /// network addresses of the broker, typically an IpV4 and an optional IPV6 addr. core broker should not be multi-homed.
    pub addrs: Vec<BindAddress>,
}

/// Core Broker connection details
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Hash)]
pub enum BrokerCore {
    V0(BrokerCoreV0),
}

/// BrokerServerTypeV0 type
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum BrokerServerTypeV0 {
    Localhost(u16), // optional port number
    BoxPrivate(Vec<BindAddress>),
    Public(Vec<BindAddress>),
    BoxPublicDyn(Vec<BindAddress>), // can be empty
    Domain(String),                 // accepts an optional trailing ":port" number
                                    //Core(Vec<BindAddress>),
}

/// BrokerServer details Version 0
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct BrokerServerV0 {
    /// Network addresses
    pub server_type: BrokerServerTypeV0,

    /// is this server capable of running a verifier
    pub can_verify: bool,

    /// is this server capable of forwarding client connections to another broker
    pub can_forward: bool,

    /// peerId of the server
    pub peer_id: PubKey,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum BrokerServer {
    V0(BrokerServerV0),
}

impl BrokerServerV0 {
    pub fn new_localhost(peer_id: PubKey) -> Self {
        BrokerServerV0 {
            server_type: BrokerServerTypeV0::Localhost(WS_PORT_ALTERNATE[0]),
            can_verify: false,
            can_forward: true,
            peer_id,
        }
    }
}

#[doc(hidden)]
pub const APP_ACCOUNT_REGISTERED_SUFFIX: &str = "/#/user/registered";

#[doc(hidden)]
pub const NG_ONE_URL: &str = "https://nextgraph.one";

#[doc(hidden)]
pub const APP_NG_ONE_URL: &str = "https://app.nextgraph.one";

#[doc(hidden)]
pub const APP_NG_ONE_WS_URL: &str = "wss://app.nextgraph.one";

#[allow(dead_code)]
fn api_dyn_peer_url(peer_id: &PubKey) -> String {
    format!("https://nextgraph.one/api/v1/dynpeer/{}", peer_id)
}

#[doc(hidden)]
pub const LOCAL_HOSTS: [&str; 3] = ["localhost", "127.0.0.1", "[::1]"];

fn local_ws_url(port: &u16) -> String {
    format!("ws://localhost:{}", if *port == 0 { 80 } else { *port })
}
#[doc(hidden)]
pub(crate) fn local_http_url(port: &u16) -> String {
    format!("http://localhost:{}", if *port == 0 { 80 } else { *port })
}

#[doc(hidden)]
pub const LOCAL_URLS: [&str; 3] = ["http://localhost", "http://127.0.0.1", "http://[::1]"];
use url::{Host, Url};

impl BrokerServerTypeV0 {
    pub fn find_first_ipv4(&self) -> Option<&BindAddress> {
        match self {
            Self::BoxPrivate(addrs) => {
                for addr in addrs {
                    if addr.ip.is_v4() {
                        return Some(addr);
                    }
                }
                return None;
            }
            _ => None,
        }
    }
    pub fn find_first_ipv6(&self) -> Option<&BindAddress> {
        match self {
            Self::BoxPrivate(addrs) => {
                for addr in addrs {
                    if addr.ip.is_v6() {
                        return Some(addr);
                    }
                }
                return None;
            }
            _ => None,
        }
    }
}
impl BrokerServerV0 {
    fn first_ipv4(&self) -> Option<(String, Vec<BindAddress>)> {
        self.server_type.find_first_ipv4().map_or(None, |bindaddr| {
            Some((format!("ws://{}:{}", bindaddr.ip, bindaddr.port), vec![]))
        })
    }

    fn first_ipv6(&self) -> Option<(String, Vec<BindAddress>)> {
        self.server_type.find_first_ipv6().map_or(None, |bindaddr| {
            Some((format!("ws://{}:{}", bindaddr.ip, bindaddr.port), vec![]))
        })
    }

    pub fn first_ipv4_http(&self) -> Option<String> {
        self.server_type.find_first_ipv4().map_or(None, |bindaddr| {
            Some(format!("http://{}:{}", bindaddr.ip, bindaddr.port))
        })
    }

    pub fn first_ipv6_http(&self) -> Option<String> {
        self.server_type.find_first_ipv6().map_or(None, |bindaddr| {
            Some(format!("http://{}:{}", bindaddr.ip, bindaddr.port))
        })
    }

    fn first_ipv6_or_ipv4(
        ipv4: bool,
        ipv6: bool,
        addrs: &Vec<BindAddress>,
    ) -> Option<&BindAddress> {
        if ipv6 {
            for addr in addrs {
                if addr.ip.is_v6() {
                    return Some(addr);
                }
            }
        }
        if ipv4 {
            for addr in addrs {
                if addr.ip.is_v4() {
                    return Some(addr);
                }
            }
        }
        return None;
    }

    fn app_ng_one_bootstrap_url(addr: &BindAddress, key: PubKey) -> Option<String> {
        let payload = (addr, key);
        let payload_ser = serde_bare::to_vec(&payload).ok();
        if payload_ser.is_none() {
            return None;
        }
        Some(format!(
            "{}?b={}",
            APP_NG_ONE_URL,
            base64_url::encode(&payload_ser.unwrap())
        ))
    }

    fn app_ng_one_bootstrap_url_with_first_ipv6_or_ipv4(
        ipv4: bool,
        ipv6: bool,
        addrs: &Vec<BindAddress>,
        key: PubKey,
    ) -> Option<String> {
        if let Some(addr) = Self::first_ipv6_or_ipv4(ipv4, ipv6, addrs) {
            return Self::app_ng_one_bootstrap_url(addr, key);
        }
        None
    }

    /// set ipv6 only if the browser connected with a remote IPV6. always set ipv4 as a fallback (for now).
    pub async fn get_url_for_ngone(&self, ipv4: bool, ipv6: bool) -> Option<String> {
        match &self.server_type {
            BrokerServerTypeV0::Public(addrs) => {
                Self::app_ng_one_bootstrap_url_with_first_ipv6_or_ipv4(
                    ipv4,
                    ipv6,
                    addrs,
                    self.peer_id,
                )
            }
            BrokerServerTypeV0::BoxPublicDyn(addrs) => {
                // let resp = reqwest::get(api_dyn_peer_url(&self.peer_id)).await;
                // if resp.is_ok() {
                //     let resp = resp.unwrap().json::<Vec<BindAddress>>().await;
                //     if resp.is_ok() {
                //         return Self::app_ng_one_bootstrap_url_with_first_ipv6_or_ipv4(
                //             ipv4,
                //             ipv6,
                //             &resp.unwrap(),
                //             self.peer_id,
                //         );
                //     }
                // }
                if addrs.len() > 0 {
                    Self::app_ng_one_bootstrap_url_with_first_ipv6_or_ipv4(
                        ipv4,
                        ipv6,
                        &addrs,
                        self.peer_id,
                    )
                } else {
                    None
                }
            }
            BrokerServerTypeV0::Domain(domain) => Some(format!("https://{}", domain)),
            BrokerServerTypeV0::Localhost(port) => Some(local_http_url(&port)),
            BrokerServerTypeV0::BoxPrivate(_) => {
                if ipv6 {
                    let v6 = self.server_type.find_first_ipv6().map_or(None, |bindaddr| {
                        Some(format!("http://{}:{}", bindaddr.ip, bindaddr.port))
                    });
                    if v6.is_some() {
                        return v6;
                    }
                }
                if ipv4 {
                    self.server_type.find_first_ipv4().map_or(None, |bindaddr| {
                        Some(format!("http://{}:{}", bindaddr.ip, bindaddr.port))
                    })
                } else {
                    None
                }
            }
        }
    }

    pub fn is_public_server(&self) -> bool {
        match &self.server_type {
            BrokerServerTypeV0::Localhost(_) => false,
            BrokerServerTypeV0::BoxPrivate(_) => false,
            BrokerServerTypeV0::Public(_) => true,
            BrokerServerTypeV0::BoxPublicDyn(_) => true,
            BrokerServerTypeV0::Domain(_) => true,
        }
    }

    /// on web browser, returns the connection URL and an optional list of BindAddress if a relay is needed
    /// filtered by the current location url of the webpage
    /// on native apps (do not pass a location), returns or the connection URL without optional BindAddress or an empty string with
    /// several BindAddresses to try to connect to with .to_ws_url()
    pub async fn get_ws_url(
        &self,
        location: &Option<String>,
    ) -> Option<(String, Vec<BindAddress>)> {
        if location.is_some() {
            let location = location.as_ref().unwrap();
            if location.starts_with(APP_NG_ONE_URL) {
                match &self.server_type {
                    BrokerServerTypeV0::Public(addrs) => {
                        Some((APP_NG_ONE_WS_URL.to_string(), addrs.clone()))
                    }
                    BrokerServerTypeV0::BoxPublicDyn(addrs) => {
                        // let resp = reqwest::get(api_dyn_peer_url(&self.peer_id)).await;
                        // if resp.is_ok() {
                        //     let resp = resp.unwrap().json::<Vec<BindAddress>>().await;
                        //     if resp.is_ok() {
                        //         return Some((APP_NG_ONE_WS_URL.to_string(), resp.unwrap()));
                        //     }
                        // }
                        if addrs.len() > 0 {
                            Some((APP_NG_ONE_WS_URL.to_string(), addrs.clone()))
                        } else {
                            None
                        }
                    }
                    _ => None,
                }
            } else if let BrokerServerTypeV0::Domain(domain) = &self.server_type {
                let url = format!("https://{}", domain);
                if location.starts_with(&url) {
                    let wss_url = format!("wss://{}", domain);
                    Some((wss_url, vec![]))
                } else {
                    None
                }
            } else {
                // localhost
                if location.starts_with(LOCAL_URLS[0])
                    || location.starts_with(LOCAL_URLS[1])
                    || location.starts_with(LOCAL_URLS[2])
                {
                    if let BrokerServerTypeV0::Localhost(port) = self.server_type {
                        Some((local_ws_url(&port), vec![]))
                    } else {
                        None
                    }
                }
                // a private address
                else if location.starts_with("http://") {
                    let url = Url::parse(&location).unwrap();
                    match url.host() {
                        Some(Host::Ipv4(ip)) => {
                            if is_ipv4_private(&ip) {
                                self.first_ipv4()
                            } else {
                                None
                            }
                        }
                        Some(Host::Ipv6(ip)) => {
                            if is_ipv6_private(&ip) {
                                self.first_ipv6()
                            } else {
                                None
                            }
                        }
                        _ => None,
                    }
                } else {
                    None
                }
            }
        } else {
            // From native / tauri app
            match &self.server_type {
                //BrokerServerTypeV0::Core(_) => None,
                BrokerServerTypeV0::Localhost(port) => Some((local_ws_url(port), vec![])),
                BrokerServerTypeV0::BoxPrivate(addrs) => Some((String::new(), addrs.clone())),
                BrokerServerTypeV0::Public(addrs) => Some((String::new(), addrs.clone())),
                BrokerServerTypeV0::BoxPublicDyn(addrs) => {
                    // let resp = reqwest::get(api_dyn_peer_url(&self.peer_id)).await;
                    // if resp.is_ok() {
                    //     let resp = resp.unwrap().json::<Vec<BindAddress>>().await;
                    //     if resp.is_ok() {
                    //         return Some((String::new(), resp.unwrap()));
                    //     }
                    // }
                    if addrs.len() > 0 {
                        Some((String::new(), addrs.clone()))
                    } else {
                        None
                    }
                }
                BrokerServerTypeV0::Domain(domain) => Some((format!("wss://{}", domain), vec![])),
            }
        }
    }
}

/// Bootstrap content Version 0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BootstrapContentV0 {
    /// list of servers, in order of preference
    pub servers: Vec<BrokerServerV0>,
}

impl BootstrapContentV0 {
    pub fn new_localhost(peer_id: PubKey) -> Self {
        BootstrapContentV0 {
            servers: vec![BrokerServerV0::new_localhost(peer_id)],
        }
    }
    pub fn new_empty() -> Self {
        BootstrapContentV0 { servers: vec![] }
    }
    pub fn merge(&mut self, with: &BootstrapContentV0) {
        'outer: for server2 in &with.servers {
            for server1 in &self.servers {
                if *server1 == *server2 {
                    continue 'outer;
                }
            }
            self.servers.push(server2.clone());
        }
    }
    pub fn get_first_peer_id(&self) -> Option<PubKey> {
        self.servers.first().map(|s| s.peer_id)
    }

    pub fn get_domain(&self) -> Option<String> {
        for server in self.servers.iter() {
            if let BrokerServerTypeV0::Domain(name) = &server.server_type {
                return Some(name.clone());
            }
        }
        None
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BootstrapContent {
    V0(BootstrapContentV0),
}

impl BootstrapContent {
    pub fn servers(&self) -> &Vec<BrokerServerV0> {
        match self {
            Self::V0(v0) => &v0.servers,
        }
    }
}

/// Local Bootstrap info Version 0, served at /.ng_bootstrap
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocalBootstrapInfoV0 {
    /// list of servers, in order of preference
    pub bootstrap: BootstrapContentV0,

    /// optional registration_url for public server that accept to be BSP for new clients
    pub registration_url: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LocalBootstrapInfo {
    V0(LocalBootstrapInfoV0),
}

impl LocalBootstrapInfo {
    pub fn servers(&self) -> &Vec<BrokerServerV0> {
        match self {
            Self::V0(v0) => &v0.bootstrap.servers,
        }
    }
}

impl From<LocalBootstrapInfo> for Invitation {
    fn from(value: LocalBootstrapInfo) -> Self {
        let LocalBootstrapInfo::V0(info) = value;
        let name = info.bootstrap.get_domain();
        let url = info.registration_url.clone();
        Invitation::V0(InvitationV0 {
            bootstrap: info.bootstrap,
            code: None,
            name,
            url,
        })
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum InvitationCode {
    Unique(SymKey),
    Admin(SymKey),
    Multi(SymKey),
}

impl InvitationCode {
    pub fn get_symkey(&self) -> SymKey {
        match self {
            Self::Unique(s) | Self::Admin(s) | Self::Multi(s) => s.clone(),
        }
    }
}

impl fmt::Display for InvitationCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unique(k) => write!(f, "unique {}", k),
            Self::Admin(k) => write!(f, "admin {}", k),
            Self::Multi(k) => write!(f, "multi {}", k),
        }
    }
}

/// Invitation to create an account at a broker. Version 0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InvitationV0 {
    /// list of servers, in order of preference
    pub bootstrap: BootstrapContentV0,

    pub code: Option<SymKey>,

    /// an optional name to display to the invitee
    pub name: Option<String>,

    // an optional url to redirect the user to, for accepting ToS and making payment, if any.
    pub url: Option<String>,
}

impl InvitationV0 {
    pub fn set_bootstrap(&mut self, content: BootstrapContent) {
        match content {
            BootstrapContent::V0(v0) => self.bootstrap = v0,
        }
    }
    pub fn empty(name: Option<String>) -> Self {
        InvitationV0 {
            bootstrap: BootstrapContentV0::new_empty(),
            code: None,
            name,
            url: None,
        }
    }
    pub fn new(
        bootstrap_content: BootstrapContent,
        code: Option<SymKey>,
        name: Option<String>,
        url: Option<String>,
    ) -> Self {
        match bootstrap_content {
            BootstrapContent::V0(v0) => InvitationV0 {
                bootstrap: v0,
                code,
                name,
                url,
            },
        }
    }
    pub fn append_bootstraps(&mut self, add: &mut Option<BootstrapContentV0>) {
        if add.is_some() {
            let add = add.as_mut().unwrap();
            self.bootstrap.servers.append(&mut add.servers);
        }
    }
}

impl Invitation {
    pub fn new_v0(
        bootstrap: BootstrapContentV0,
        name: Option<String>,
        url: Option<String>,
    ) -> Self {
        Invitation::V0(InvitationV0 {
            bootstrap,
            code: Some(SymKey::random()),
            name,
            url,
        })
    }

    pub fn new_v0_free(
        bootstrap: BootstrapContentV0,
        name: Option<String>,
        url: Option<String>,
    ) -> Self {
        Invitation::V0(InvitationV0 {
            bootstrap,
            code: None,
            name,
            url,
        })
    }

    pub fn intersects(&self, invite2: Invitation) -> Invitation {
        let Invitation::V0(v0) = self;
        let mut new_invite = InvitationV0 {
            bootstrap: BootstrapContentV0::new_empty(),
            code: v0.code.clone(),
            name: v0.name.clone(),
            url: v0.url.clone(),
        };
        for server2 in invite2.get_servers() {
            for server1 in &v0.bootstrap.servers {
                if *server1 == *server2 {
                    new_invite.bootstrap.servers.push(server2.clone());
                    break;
                }
            }
        }
        Invitation::V0(new_invite)
    }

    pub fn get_servers(&self) -> &Vec<BrokerServerV0> {
        match self {
            Invitation::V0(v0) => &v0.bootstrap.servers,
        }
    }

    pub fn set_name(&mut self, name: Option<String>) {
        if name.is_some() {
            match self {
                Invitation::V0(v0) => v0.name = Some(name.unwrap()),
            }
        }
    }

    pub fn set_url(&mut self, url: Option<&String>) {
        if url.is_some() {
            match self {
                Invitation::V0(v0) => v0.url = Some(url.unwrap().clone()),
            }
        }
    }

    /// first URL in the list is the ngone one
    pub fn get_urls(&self) -> Vec<String> {
        match self {
            Invitation::V0(v0) => {
                let mut res = vec![];
                let ser = serde_bare::to_vec(&self).unwrap();
                let url_param = base64_url::encode(&ser);
                res.push(format!("{}/#/i/{}", NG_ONE_URL, url_param));
                for server in &v0.bootstrap.servers {
                    match &server.server_type {
                        BrokerServerTypeV0::Domain(domain) => {
                            res.push(format!("https://{}/#/i/{}", domain, url_param));
                        }
                        BrokerServerTypeV0::BoxPrivate(addrs) => {
                            for bindaddr in addrs {
                                res.push(format!(
                                    "http://{}:{}/#/i/{}",
                                    bindaddr.ip, bindaddr.port, url_param
                                ));
                            }
                        }
                        BrokerServerTypeV0::Localhost(port) => {
                            res.push(format!("{}/#/i/{}", local_http_url(&port), url_param));
                        }
                        _ => {}
                    }
                }
                res
            }
        }
    }
}

impl fmt::Display for Invitation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ser = serde_bare::to_vec(&self).unwrap();
        let string = base64_url::encode(&ser);
        write!(f, "{}", string)
    }
}

impl TryFrom<String> for Invitation {
    type Error = NgError;
    fn try_from(value: String) -> Result<Self, NgError> {
        let ser = base64_url::decode(&value).map_err(|_| NgError::InvalidInvitation)?;
        let invite: Invitation =
            serde_bare::from_slice(&ser).map_err(|_| NgError::InvalidInvitation)?;
        Ok(invite)
    }
}

/// Invitation to create an account at a broker.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Invitation {
    V0(InvitationV0),
}

// impl From<BootstrapContent> for Invitation {
//     fn from(value: BootstrapContent) -> Self {
//         let BootstrapContent::V0(boot) = value;
//         let name = boot.get_domain();
//         Invitation::V0(InvitationV0 {
//             bootstrap: boot,
//             code: None,
//             name,
//             url: None,
//         })
//     }
// }

/// Create an account at a Broker Service Provider (BSP).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CreateAccountBSP {
    V0(CreateAccountBSPV0),
}

impl TryFrom<String> for CreateAccountBSP {
    type Error = NgError;
    fn try_from(value: String) -> Result<Self, NgError> {
        let ser = base64_url::decode(&value).map_err(|_| NgError::InvalidCreateAccount)?;
        let invite: CreateAccountBSP =
            serde_bare::from_slice(&ser).map_err(|_| NgError::InvalidCreateAccount)?;
        Ok(invite)
    }
}

impl CreateAccountBSP {
    pub fn encode(&self) -> Option<String> {
        let payload_ser = serde_bare::to_vec(self).ok();
        if payload_ser.is_none() {
            return None;
        }
        Some(base64_url::encode(&payload_ser.unwrap()))
    }
    // pub fn user(&self) -> PubKey {
    //     match self {
    //         Self::V0(v0) => v0.user,
    //     }
    // }
    pub fn redirect_url(&self) -> &Option<String> {
        match self {
            Self::V0(v0) => &v0.redirect_url,
        }
    }
    // pub fn invitation(&self) -> &Option<InvitationV0> {
    //     match self {
    //         Self::V0(v0) => &v0.invitation,
    //     }
    // }
    // pub fn additional_bootstrap(&mut self) -> &mut Option<BootstrapContentV0> {
    //     match self {
    //         Self::V0(v0) => &mut v0.additional_bootstrap,
    //     }
    // }
}

/// Create an account at a Broker Service Provider (BSP). Version 0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CreateAccountBSPV0 {
    //pub invitation: Option<InvitationV0>,

    //pub additional_bootstrap: Option<BootstrapContentV0>,
    /// the user asking to create an account
    //pub user: PubKey,

    /// signature over serialized invitation code, with user key
    // pub sig: Sig,

    /// for web access, will redirect after successful signup. if left empty, it means user was on native app.
    pub redirect_url: Option<String>,
}

/// ListenerInfo
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ListenerInfo {
    pub config: ListenerV0,

    /// list of BindAddresses
    pub addrs: Vec<BindAddress>,
}

/// AcceptForwardForV0 type
///
/// allow answers to connection requests originating from a client behind a reverse proxy
/// Format of last param in the tuple is a list of comma separated hosts or CIDR subnetworks IPv4 and/or IPv6 addresses accepted as X-Forwarded-For
/// Empty string means all addresses are accepted
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum AcceptForwardForV0 {
    /// X-Forwarded-For not allowed
    No,

    /// X-Forwarded-For accepted only for clients with private LAN addresses. First param is the domain of the proxy server
    PrivateDomain((String, String)),

    /// X-Forwarded-For accepted only for clients with public addresses. First param is the domain of the proxy server
    /// domain can take an option port (trailing `:port`)
    PublicDomain((String, String)),

    /// X-Forwarded-For accepted only for clients with public addresses. First param is the domain of the proxy server
    /// domain can take an optional port (trailing `:port`)
    /// second param is the privKey of the PeerId of the proxy server, useful when the proxy server is load balancing to several daemons
    /// that should all use the same PeerId to answer requests
    PublicDomainPeer((String, PrivKey, String)),

    /// accepts only clients with public addresses that arrive on a LAN address binding. This is used for DMZ and port forwarding configs
    /// first param is the port, second param in tuple is the interval for periodic probe of the external IP
    PublicDyn((u16, u32, String)),

    /// accepts only clients with public addresses that arrive on a LAN address binding. This is used for DMZ and port forwarding configs
    /// First param is the IPv4 bind address of the reverse NAT server (DMZ, port forwarding)
    /// Second param is an optional IPv6 bind address of the reverse NAT server (DMZ, port forwarding)
    PublicStatic((BindAddress, Option<BindAddress>, String)),
}

impl AcceptForwardForV0 {
    pub fn get_public_bind_addresses(&self) -> Vec<BindAddress> {
        match self {
            AcceptForwardForV0::PublicStatic((ipv4, ipv6, _)) => {
                let mut res = vec![ipv4.clone()];
                if ipv6.is_some() {
                    res.push(ipv6.unwrap().clone())
                }
                res
            }
            AcceptForwardForV0::PublicDyn(_) => {
                todo!();
            }
            _ => panic!("cannot call get_public_bind_addresses"),
        }
    }

    pub fn get_public_bind_ipv6_address(&self) -> Option<IP> {
        match self {
            AcceptForwardForV0::PublicStatic((_ipv4, ipv6, _)) => {
                //let _res = vec![ipv4.clone()];
                if ipv6.is_some() {
                    return Some(ipv6.unwrap().ip.clone());
                } else {
                    return None;
                }
            }
            AcceptForwardForV0::PublicDyn(_) => {
                todo!();
            }
            _ => None,
        }
    }

    pub fn is_public_domain(&self) -> bool {
        match self {
            AcceptForwardForV0::PublicDomainPeer(_) => true,
            AcceptForwardForV0::PublicDomain(_) => true,
            _ => false,
        }
    }
    pub fn is_public_static(&self) -> bool {
        match self {
            AcceptForwardForV0::PublicStatic(_) => true,
            _ => false,
        }
    }
    pub fn is_no(&self) -> bool {
        match self {
            AcceptForwardForV0::No => true,
            _ => false,
        }
    }
    pub fn is_public_dyn(&self) -> bool {
        match self {
            AcceptForwardForV0::PublicDyn(_) => true,
            _ => false,
        }
    }
    pub fn is_private_domain(&self) -> bool {
        match self {
            AcceptForwardForV0::PrivateDomain(_) => true,
            _ => false,
        }
    }
    pub fn domain_with_common_peer_id(&self) -> Option<PubKey> {
        match self {
            AcceptForwardForV0::PublicDomainPeer((_, privkey, _)) => Some(privkey.to_pub()),
            _ => None,
        }
    }
    pub fn get_domain(&self) -> &str {
        let domain = get_domain_without_port_443(match self {
            AcceptForwardForV0::PrivateDomain((d, _)) => d,
            AcceptForwardForV0::PublicDomain((d, _)) => d,
            AcceptForwardForV0::PublicDomainPeer((d, _, _)) => d,
            _ => panic!("cannot call get_domain if AcceptForwardForV0 is not a domain"),
        });
        //let mut url = "https://".to_string();
        //url.push_str(domain);
        domain
    }
}

#[cfg(not(target_arch = "wasm32"))]
/// DaemonConfig Listener Version 0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ListenerV0 {
    /// local interface name to bind to
    /// names of interfaces can be retrieved with the --list-interfaces option
    pub interface_name: String,

    pub if_type: InterfaceType,

    /// optional number of seconds for an interval of periodic refresh
    /// of the actual IP(s) of the interface. Used for dynamic IP interfaces (DHCP)
    pub interface_refresh: u32,

    // if to bind to the ipv6 address of the interface
    pub ipv6: bool,

    /// local port to listen on
    pub port: u16,

    /// force a private or localhost interface to be accepted as a core interface
    pub private_core: bool,

    /// should the server serve the app files in HTTP mode (not WS). this setting will be discarded and app will not be served anyway if remote IP is public or listener is public
    pub serve_app: bool,

    /// when the box is behind a DMZ, and ipv6 is enabled, the private interface will get the external public IpV6. with this option we allow binding to it
    pub bind_public_ipv6: bool,

    /// default to false. Set to true by --core (use --core-with-clients to override to false). only useful for a public IP listener, if the clients should use another listener like --domain or --domain-private.
    /// do not set it on a --domain or --domain-private, as this will enable the relay_websocket feature, which should not be used except by app.nextgraph.one
    pub refuse_clients: bool,

    // will answer a probe coming from private LAN and if is_private, with its own peerId, so that guests on the network will be able to connect.
    pub discoverable: bool,

    /// Answers to connection requests originating from a direct client, without X-Forwarded-For headers
    /// Can be used in combination with a accept_forward_for config, when a local daemon is behind a proxy, and also serves as broker for local apps/webbrowsers
    pub accept_direct: bool,

    /// X-Forwarded-For config. only valid if IP/interface is localhost or private
    pub accept_forward_for: AcceptForwardForV0,
    // impl fn is_private()
    // returns false if public IP in interface, or if PublicDyn, PublicStatic

    // an interface with no accept_forward_for and no accept_direct, is de facto, disabled
}

#[cfg(not(target_arch = "wasm32"))]
impl ListenerV0 {
    pub fn should_bind_public_ipv6_to_private_interface(&self, ip: Ipv6Addr) -> bool {
        let public_ip = self.accept_forward_for.get_public_bind_ipv6_address();
        if public_ip.is_none() {
            return false;
        }
        let public_ipv6addr: IpAddr = public_ip.as_ref().unwrap().into();
        return if let IpAddr::V6(v6) = public_ipv6addr {
            self.bind_public_ipv6 && self.if_type == InterfaceType::Private && ip == v6
        } else {
            false
        };
    }

    pub fn new_direct(interface: Interface, ipv6: bool, port: u16) -> Self {
        Self {
            interface_name: interface.name,
            if_type: interface.if_type,
            interface_refresh: 0,
            ipv6,
            port,
            private_core: false,
            discoverable: false,
            accept_direct: true,
            refuse_clients: false,
            serve_app: true,
            bind_public_ipv6: false,
            accept_forward_for: AcceptForwardForV0::No,
        }
    }

    pub fn is_core(&self) -> bool {
        match self.accept_forward_for {
            AcceptForwardForV0::PublicStatic(_) => true,
            AcceptForwardForV0::PublicDyn(_) => true,
            AcceptForwardForV0::PublicDomain(_) | AcceptForwardForV0::PublicDomainPeer(_) => false,
            AcceptForwardForV0::PrivateDomain(_) => false,
            AcceptForwardForV0::No => {
                self.if_type == InterfaceType::Public
                    || (self.private_core && self.if_type != InterfaceType::Invalid)
            }
        }
    }

    pub fn accepts_client(&self) -> bool {
        match self.accept_forward_for {
            AcceptForwardForV0::PublicStatic(_)
            | AcceptForwardForV0::PublicDyn(_)
            | AcceptForwardForV0::PublicDomain(_)
            | AcceptForwardForV0::PublicDomainPeer(_) => self.accept_direct || !self.refuse_clients,
            AcceptForwardForV0::PrivateDomain(_) => true,
            AcceptForwardForV0::No => {
                self.if_type == InterfaceType::Public && !self.refuse_clients
                    || self.if_type != InterfaceType::Public
            }
        }
    }

    pub fn get_bootstraps(&self, addrs: Vec<BindAddress>) -> Vec<BrokerServerTypeV0> {
        let mut res: Vec<BrokerServerTypeV0> = vec![];
        match self.accept_forward_for {
            AcceptForwardForV0::PublicStatic(_) => {
                let pub_addrs = self.accept_forward_for.get_public_bind_addresses();
                //res.push(BrokerServerTypeV0::Core(pub_addrs.clone()));
                if !self.refuse_clients {
                    res.push(BrokerServerTypeV0::Public(pub_addrs));
                }
                if self.accept_direct {
                    res.push(BrokerServerTypeV0::BoxPrivate(addrs));
                }
            }
            AcceptForwardForV0::PublicDyn(_) => {
                let pub_addrs = self.accept_forward_for.get_public_bind_addresses();
                //res.push(BrokerServerTypeV0::Core(pub_addrs.clone()));
                if !self.refuse_clients {
                    res.push(BrokerServerTypeV0::BoxPublicDyn(pub_addrs));
                }
                if self.accept_direct {
                    res.push(BrokerServerTypeV0::BoxPrivate(addrs));
                }
            }
            AcceptForwardForV0::PublicDomain(_) | AcceptForwardForV0::PublicDomainPeer(_) => {
                if !self.refuse_clients {
                    res.push(BrokerServerTypeV0::Domain(
                        self.accept_forward_for.get_domain().to_string(),
                    ));
                }
                //// this is removed since a server serving domain requests often needs a local interface too (for ngaccount), but does not want to expose this local interface to clients.
                // if self.accept_direct {
                //     if self.if_type == InterfaceType::Private {
                //         res.push(BrokerServerTypeV0::BoxPrivate(addrs));
                //     } else if self.if_type == InterfaceType::Loopback {
                //         res.push(BrokerServerTypeV0::Localhost(addrs[0].port));
                //     }
                // }
            }
            AcceptForwardForV0::PrivateDomain(_) => {
                res.push(BrokerServerTypeV0::Domain(
                    self.accept_forward_for.get_domain().to_string(),
                ));
            }
            AcceptForwardForV0::No => {
                if self.if_type == InterfaceType::Loopback {
                    res.push(BrokerServerTypeV0::Localhost(addrs[0].port));
                } else if self.if_type == InterfaceType::Public {
                    //res.push(BrokerServerTypeV0::Core(addrs.clone()));
                    if !self.refuse_clients {
                        res.push(BrokerServerTypeV0::Public(addrs));
                    }
                } else if self.if_type == InterfaceType::Private {
                    res.push(BrokerServerTypeV0::BoxPrivate(addrs));
                }
            }
        }
        res
    }
}
#[cfg(not(target_arch = "wasm32"))]
impl fmt::Display for ListenerV0 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut id = self.interface_name.clone();
        id.push('@');
        id.push_str(&self.port.to_string());
        write!(f, "{}", id)
    }
}

/// Broker Overlay Permission
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum BrokerOverlayPermission {
    Nobody,
    Anybody,
    AllRegisteredUser,
    UsersList(Vec<UserId>),
}

/// Broker Overlay Config
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct BrokerOverlayConfigV0 {
    // list of overlays this config applies to. empty array means applying to all
    pub overlays: Vec<OverlayId>,
    // Who can ask to join an overlay on the core
    pub core: BrokerOverlayPermission,
    // Who can connect as a client to this server
    pub server: BrokerOverlayPermission,
    // if core == Nobody and server == Nobody then the listeners will not be started

    // are ExtRequest allowed on the server? this requires the core to be ON.
    pub allow_read: bool,

    /// an empty list means to forward to the peer known for each overlay.
    /// forward and core are mutually exclusive. forward becomes the default when core is disabled (set to Nobody).
    /// core always takes precedence.
    pub forward: Vec<BrokerServerV0>,
}

impl BrokerOverlayConfigV0 {
    pub fn new() -> Self {
        BrokerOverlayConfigV0 {
            overlays: vec![],
            core: BrokerOverlayPermission::Nobody,
            server: BrokerOverlayPermission::Nobody,
            allow_read: false,
            forward: vec![],
        }
    }
}

/// Registration config
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RegistrationConfig {
    Closed,
    Invitation,
    Open,
}

/// Overlay Access
///
/// Used by the Client when opening or pinning a repo.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OverlayAccess {
    /// The repo will be accessed on the Outer Overlay in Read Only mode
    /// This can be used for Public, Protected or Group overlays
    /// Value should be an OverlayId::Outer
    ReadOnly(OverlayId),
    /// The repo will be accessed on the Inner Overlay in Write mode, and the associated Outer overlay is also given
    /// This is used for Public, Protected and Group overlays
    /// First value in tuple should be the OverlayId::Inner, second the OverlayId::Outer
    ReadWrite((OverlayId, OverlayId)),
    /// The repo will be accessed on the Inner Overlay in Write mode, and it doesn't have an Outer overlay
    /// This is used for Private and Dialog overlays
    /// Value should be an OverlayId::Inner
    WriteOnly(OverlayId),
}

impl OverlayAccess {
    pub fn is_read_only(&self) -> bool {
        match self {
            Self::ReadOnly(_) => true,
            _ => false,
        }
    }
    pub fn new_write_access_from_store(store: &Store) -> OverlayAccess {
        match store.get_store_repo() {
            StoreRepo::V0(StoreRepoV0::PrivateStore(_)) | StoreRepo::V0(StoreRepoV0::Dialog(_)) => {
                OverlayAccess::WriteOnly(store.inner_overlay())
            }
            StoreRepo::V0(StoreRepoV0::ProtectedStore(_))
            | StoreRepo::V0(StoreRepoV0::Group(_))
            | StoreRepo::V0(StoreRepoV0::PublicStore(_)) => {
                OverlayAccess::ReadWrite((store.inner_overlay(), store.outer_overlay()))
            }
        }
    }

    pub fn new_read_access_from_store(store: &Store) -> OverlayAccess {
        match store.get_store_repo() {
            StoreRepo::V0(StoreRepoV0::PrivateStore(_)) | StoreRepo::V0(StoreRepoV0::Dialog(_)) => {
                panic!("cannot get read access to a private or dialog store");
            }
            StoreRepo::V0(StoreRepoV0::ProtectedStore(_))
            | StoreRepo::V0(StoreRepoV0::Group(_))
            | StoreRepo::V0(StoreRepoV0::PublicStore(_)) => {
                OverlayAccess::ReadOnly(store.outer_overlay())
            }
        }
    }

    pub fn new_ro(outer_overlay: OverlayId) -> Result<Self, NgError> {
        if let OverlayId::Outer(_digest) = outer_overlay {
            Ok(OverlayAccess::ReadOnly(outer_overlay))
        } else {
            Err(NgError::InvalidArgument)
        }
    }
    pub fn new_rw(inner_overlay: OverlayId, outer_overlay: OverlayId) -> Result<Self, NgError> {
        if let OverlayId::Inner(_digest) = inner_overlay {
            if let OverlayId::Outer(_digest) = outer_overlay {
                Ok(OverlayAccess::ReadWrite((inner_overlay, outer_overlay)))
            } else {
                Err(NgError::InvalidArgument)
            }
        } else {
            Err(NgError::InvalidArgument)
        }
    }
    pub fn new_wo(inner_overlay: OverlayId) -> Result<Self, NgError> {
        if let OverlayId::Inner(_digest) = inner_overlay {
            Ok(OverlayAccess::WriteOnly(inner_overlay))
        } else {
            Err(NgError::InvalidArgument)
        }
    }
    pub fn overlay_id_for_client_protocol_purpose(&self) -> &OverlayId {
        match self {
            Self::ReadOnly(ro) => ro,
            Self::ReadWrite((inner, _outer)) => inner,
            Self::WriteOnly(wo) => wo,
        }
    }
}

/// Inner Overlay Link
///
/// Details of the inner overlay of an NgLink
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct InnerOverlayLink {
    /// overlay public key ID
    pub id: StoreOverlay,

    /// The store has a special branch called `overlay` that is used to manage access to the InnerOverlay
    /// only the ReadCapSecret is needed to access the InnerOverlay
    /// the full readcap of this branch is needed in order to subscribe to the topic and decrypt the events. The branchId can be found in the branch Definition
    /// it can be useful to subscribe to this topic if the user is a member of the store's repo, so it will be notified of BranchCapRefresh on the overlay
    /// if the user is an external user to the store, it will lose access to the InnerOverlay after a BranchCapRefresh of the overlay branch of the store.
    pub store_overlay_readcap: ReadCap,
}

/// Overlay Link
///
/// Details of the overlay of an NgLink
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OverlayLink {
    Outer(Digest),
    InnerLink(InnerOverlayLink),
    Inner(Digest),
    Inherit,
    Public(PubKey),
}

/// Overlay session ID
///
/// It is a pubkey used for signing all OverlayMessage sent by the peer.
/// Each peer generates it randomly when (re)joining the overlay network.
pub type SessionId = PubKey;

/// Client ID: client of a user
pub type ClientId = PubKey;

/// IPv4 address
pub type IPv4 = [u8; 4];

const LOOPBACK_IPV4: IP = IP::IPv4([127, 0, 0, 1]);

/// IPv6 address
pub type IPv6 = [u8; 16];

/// IP address
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum IP {
    IPv4(IPv4),
    IPv6(IPv6),
}

impl IP {
    pub fn is_public(&self) -> bool {
        is_public_ip(&self.into())
    }
    pub fn is_private(&self) -> bool {
        is_private_ip(&self.into())
    }
    pub fn is_loopback(&self) -> bool {
        let t: &IpAddr = &self.into();
        t.is_loopback()
    }
    pub fn is_v6(&self) -> bool {
        if let Self::IPv6(_) = self {
            true
        } else {
            false
        }
    }
    pub fn is_v4(&self) -> bool {
        if let Self::IPv4(_) = self {
            true
        } else {
            false
        }
    }
}

impl fmt::Display for IP {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let t: IpAddr = self.try_into().unwrap();
        match self {
            IP::IPv4(_) => write!(f, "{}", t),
            IP::IPv6(_) => write!(f, "[{}]", t),
        }
    }
}

impl From<&IpAddr> for IP {
    #[inline]
    fn from(ip: &IpAddr) -> IP {
        match ip {
            IpAddr::V4(v4) => IP::IPv4(v4.octets()),
            IpAddr::V6(v6) => IP::IPv6(v6.octets()),
        }
    }
}

impl From<&IP> for IpAddr {
    #[inline]
    fn from(ip: &IP) -> IpAddr {
        match ip {
            IP::IPv4(v4) => IpAddr::from(*v4),
            IP::IPv6(v6) => IpAddr::from(*v6),
        }
    }
}

/// IP transport protocol
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum TransportProtocol {
    WS,
    QUIC,
    Local,
}

/// IP transport address
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct IPTransportAddr {
    pub ip: IP,
    pub port: u16,
    pub protocol: TransportProtocol,
}

/// Network address
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum NetAddr {
    IPTransport(IPTransportAddr),
}

/**
* info : {
     type : WEB | NATIVE-IOS | NATIVE-ANDROID | NATIVE-MACOS | NATIVE-LINUX | NATIVE-WIN
            NATIVE-SERVICE | NODE-SERVICE | VERIFIER | CLIENT-BROKER | CLI
     vendor : (UA, node version, tauri webview, rust version)
     os : operating system string
     version : version of client
     date_install
     date_updated : last update
   }
*/

/// Client Type
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ClientType {
    Web,
    NativeIos,
    NativeAndroid,
    NativeMacOS,
    NativeLinux,
    NativeWin,
    NativeService,
    NodeService,
    Verifier,
    VerifierLocal,
    Box,   // VerifierBox
    Stick, // VerifierStick
    WalletMaster,
    ClientBroker,
    Cli,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ClientInfoV0 {
    pub client_type: ClientType,
    pub details: String,
    pub version: String,
    pub timestamp_install: u64,
    pub timestamp_updated: u64,
}

/// Client Info
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ClientInfo {
    V0(ClientInfoV0),
}

impl ClientInfo {
    pub fn new(client_type: ClientType, details: String, version: String) -> ClientInfo {
        let timestamp_install = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        ClientInfo::V0(ClientInfoV0 {
            details,
            version,
            client_type,
            timestamp_install,
            timestamp_updated: timestamp_install,
        })
    }
}

//
// OVERLAY MESSAGES
//

/// Overlay leave request
///
/// In outerOverlay: informs the broker that the overlay is not needed anymore
/// In innerOverlay: Sent to all connected overlay participants to terminate a session
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum OverlayLeave {
    V0(),
}

/// Content of PublisherAdvertV0
///
/// the peer is matched with the InnerOverlayMessageV0.Session -> peerId.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct PublisherAdvertContentV0 {
    /// Topic public key
    pub topic: TopicId,

    /// Peer public key
    pub peer: DirectPeerId,
}

/// Topic advertisement by a publisher
///
/// Flooded to all peers in overlay
/// Creates subscription routing table entries
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct PublisherAdvertV0 {
    pub content: PublisherAdvertContentV0,

    /// Signature over content by topic key
    pub sig: Sig,
}

/// Topic advertisement by a publisher
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum PublisherAdvert {
    V0(PublisherAdvertV0),
}

impl PublisherAdvert {
    pub fn new(
        topic_id: TopicId,
        topic_key: BranchWriteCapSecret,
        broker_peer: DirectPeerId,
    ) -> PublisherAdvert {
        let content = PublisherAdvertContentV0 {
            peer: broker_peer,
            topic: topic_id,
        };
        let content_ser = serde_bare::to_vec(&content).unwrap();
        let sig = sign(&topic_key, &topic_id, &content_ser).unwrap();
        PublisherAdvert::V0(PublisherAdvertV0 { content, sig })
    }
    pub fn topic_id(&self) -> &TopicId {
        match self {
            Self::V0(v0) => &v0.content.topic,
        }
    }

    pub fn verify(&self) -> Result<(), NgError> {
        match self {
            Self::V0(v0) => verify(
                &serde_bare::to_vec(&v0.content).unwrap(),
                v0.sig,
                v0.content.topic,
            ),
        }
    }

    pub fn verify_for_broker(&self, peer_id: &DirectPeerId) -> Result<(), ProtocolError> {
        match self {
            Self::V0(v0) => {
                if v0.content.peer != *peer_id {
                    return Err(ProtocolError::InvalidPublisherAdvert);
                }
            }
        }
        Ok(self.verify()?)
    }
}

/// Topic subscription request by a peer
///
/// Forwarded towards all publishers along subscription routing table entries
/// that are created by PublisherAdverts
/// Creates event routing table entries along the path
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct SubReqV0 {
    /// Topic public key
    pub topic: TopicId,

    /// For initial subscription, should be None,
    /// When updating a subscription after a new publisher has joined (with a PublisherAdvert),
    /// then the target publisher should be entered here.
    /// The brokers will only forward the SubscriptionRequest to that publisher (on all available paths)
    pub publisher: Option<DirectPeerId>,
}

/// Topic subscription request by a peer
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum SubReq {
    V0(SubReqV0),
}

/// Topic subscription marker sent by all publishers, back to subscriber
///
/// Forwarded to all subscribers.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SubMarkerV0 {
    /// The publisher broker that marks its starting cut
    /// TODO: that could be omitted, because we can retrieve it with the SessionId
    pub publisher: DirectPeerId,

    /// The subscribed topic
    pub topic: TopicId,

    /// The subscriber
    pub subscriber: DirectPeerId,

    /// Current heads at the broker when receiving the SubReq. Can be used to safely do a CoreTopicSyncReq
    pub known_heads: Vec<ObjectId>,
}

/// Topic subscription acknowledgement by a publisher
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SubMarker {
    V0(SubMarkerV0),
}

/// Topic unsubscription request by a subscriber
///
/// A broker unsubscribes from all publisher brokers in the overlay
/// when it has no more local subscribers left
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct UnsubReqV0 {
    /// Topic public key
    pub topic: TopicId,
}

/// Topic unsubscription request by a subscriber
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum UnsubReq {
    V0(UnsubReqV0),
}

/// Object search in a pub/sub topic
///
/// Sent along the reverse path of a pub/sub topic
/// from a subscriber to one publisher at a time.
/// fanout is always 1
/// if result is none, tries another path if several paths available locally
/// answered with a stream of BlockResult
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlockSearchTopicV0 {
    /// Topic to forward the request in
    pub topic: TopicId,

    /// Also search in subscribers
    pub search_in_subs: bool,

    /// List of Object IDs to request
    pub ids: Vec<ObjectId>,

    /// Whether or not to include all children recursively in the response
    pub include_children: bool,

    /// List of Peer IDs the request traversed so far
    pub path: Vec<PeerId>,
}

/// Object request by ID to publishers
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlockSearchTopic {
    V0(BlockSearchTopicV0),
}

/// Block search along a random walk in the overlay
///
/// fanout is always 1
/// if result is none, tries another path if several paths available locally
/// answered with a stream BlockResult
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlockSearchRandomV0 {
    /// List of Block IDs to request
    pub ids: Vec<BlockId>,

    /// Whether or not to include all children recursively in the response
    pub include_children: bool,

    /// Number of random nodes to forward the request to at each step
    // pub fanout: u8,
    // for now fanout is always 1

    /// List of Broker Peer IDs the request traversed so far
    pub path: Vec<DirectPeerId>,
}

/// Block request by ID using a random walk in the overlay
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlockSearchRandom {
    V0(BlockSearchRandomV0),
}

/// Response to a BlockSearch* request
///
/// can be a stream
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlockResultV0 {
    /// Resulting Blocks(s)
    pub payload: Vec<Block>,
}

/// Response to a BlockSearch* request
///
/// can be a stream
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlockResult {
    V0(BlockResultV0),
}

/// Topic synchronization request
///
/// In response a stream of `TopicSyncRes`s containing the missing Commits or events are sent
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TopicSyncReqV0 {
    /// Topic public key
    pub topic: TopicId,

    /// Fully synchronized until these commits
    pub known_heads: Vec<ObjectId>,

    /// Stop synchronizing when these commits are met.
    /// if empty, the local HEAD at the responder is used instead
    pub target_heads: Vec<ObjectId>,

    /// optional Bloom filter of all the commit IDs present locally (used in case of detected fork)
    pub known_commits: Option<BloomFilter>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Topic synchronization request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TopicSyncReq {
    V0(TopicSyncReqV0),
}

impl TopicSyncReq {
    pub fn overlay(&self) -> &OverlayId {
        match self {
            Self::V0(v0) => v0.overlay.as_ref().unwrap(),
        }
    }
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            Self::V0(v0) => v0.overlay = Some(overlay),
        }
    }
    pub fn topic(&self) -> &TopicId {
        match self {
            TopicSyncReq::V0(o) => &o.topic,
        }
    }
    pub fn known_heads(&self) -> &Vec<ObjectId> {
        match self {
            TopicSyncReq::V0(o) => &o.known_heads,
        }
    }
    pub fn target_heads(&self) -> &Vec<ObjectId> {
        match self {
            TopicSyncReq::V0(o) => &o.target_heads,
        }
    }
    pub fn known_commits(&self) -> &Option<BloomFilter> {
        match self {
            TopicSyncReq::V0(o) => &o.known_commits,
        }
    }
}

/// Status of a Forwarded Peer, sent in the Advert
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PeerStatus {
    Connected,
    Disconnected,
}

/// ForwardedPeerAdvertV0
///
/// peer_advert.forwarded_by is matched with sessionid->peerid
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForwardedPeerAdvertV0 {
    /// PeerAdvert received from Client
    // TODO: this could be obfuscated when user doesnt want to recall events.
    pub peer_advert: PeerAdvertV0,

    /// Hashed user Id, used to prevent concurrent connection from different brokers
    /// BLAKE3 keyed hash over the UserId
    ///   - key: BLAKE3 derive_key ("NextGraph UserId Hash Overlay Id ForwardedPeerAdvertV0 BLAKE3 key", overlayId) // will always be an Inner overlay
    pub user_hash: Digest,

    /// whether the Advert is about connection or disconnection
    pub status: PeerStatus,
}

/// Forwarded Peer advertisement
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ForwardedPeerAdvert {
    V0(ForwardedPeerAdvertV0),
}

/// ForwardedPeerConflictV0
///
/// peer_advert.forwarded_by is matched with sessionid->peerid
/// When the forwarding broker receives the conflict (or notices it), it sends a notification
/// In order to avoid conflicts, the highest version of PeerAdvert should win, when the Forwarding Broker is different.
/// Disconnect wins over connect, for the exact same peer, version and forwarding broker.
/// Conflict can occur when same user_hash, on 2 different Forwarding Broker
/// Or when same peerId appears on 2 different Forwarding Broker.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForwardedPeerConflictV0 {
    /// First conflicting PeerAdvert
    pub advert_1: ForwardedPeerAdvertV0,
    /// Second conflicting PeerAdvert
    pub advert_2: ForwardedPeerAdvertV0,

    pub error_code: u16,
}

/// Forwarded Peer advertisement conflict
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ForwardedPeerConflict {
    V0(ForwardedPeerConflictV0),
}

/// Content of PeerAdvertV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PeerAdvertContentV0 {
    /// Peer ID
    pub peer: PeerId,

    /// Id of the broker that is forwarding the peer
    pub forwarded_by: Option<DirectPeerId>,

    /// Topic subscriptions
    // pub subs: BloomFilter128,

    /// Network addresses, must be empty for forwarded peers
    pub address: Vec<NetAddr>,

    /// Version number
    pub version: u32,

    /// App-specific metadata (profile, cryptographic material, etc)
    #[serde(with = "serde_bytes")]
    pub metadata: Vec<u8>,
}

/// Peer advertisement
///
/// Sent when a peer joins an inner overlay.
/// Used only for forwardedPeer for now.
/// In the future, Core brokers could exchange PeerAdvert on the global overlay, and also do some PeerSearch to search for IPs/newer version of PeerAdvert
/// When the forwarding broker receives a client connection, it checks that the peer isn't
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PeerAdvertV0 {
    /// Peer advertisement content
    pub content: PeerAdvertContentV0,

    /// Signature over content by peer's private key
    pub sig: Sig,
}

/// Peer advertisement
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PeerAdvert {
    V0(PeerAdvertV0),
}

impl PeerAdvert {
    pub fn version(&self) -> u32 {
        match self {
            PeerAdvert::V0(o) => o.content.version,
        }
    }
    pub fn peer(&self) -> &PeerId {
        match self {
            PeerAdvert::V0(o) => &o.content.peer,
        }
    }
}

/// Content of InnerOverlayMessageV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum InnerOverlayMessageContentV0 {
    OverlayLeave(OverlayLeave),
    ForwardedPeerAdvert(ForwardedPeerAdvert),
    ForwardedPeerConflict(ForwardedPeerConflict),
    PublisherJoined(PublisherAdvert),
    PublisherLeft(PublisherAdvert),
    SubReq(SubReq),
    SubMarker(SubMarker),
    UnsubReq(UnsubReq),
    Event(Event),
    //PostInboxRequest(PostInboxRequest),
    //PostInboxResponse(PostInboxResponse),
}

/// Inner Overlay message payload V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InnerOverlayMessagePayloadV0 {
    /// Sequence number incremented by peer when sending every overlay message in a session
    /// Used to prevent replay attacks inside the overlay
    pub seq: u64,

    pub content: InnerOverlayMessageContentV0,
}

/// Inner Overlay message V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InnerOverlayMessageV0 {
    /// Session ID
    pub session: SessionId,

    pub payload: InnerOverlayMessagePayloadV0,

    /// Signature with Session private key, over payload
    pub sig: Sig,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// Inner Overlay message
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum InnerOverlayMessage {
    V0(InnerOverlayMessageV0),
}

/// Overlay Advert Payload V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OverlayAdvertPayloadV0 {
    /// the target Overlay ID (cannot be an Outer overlay)
    pub overlay: OverlayId,

    /// the newly generated session ID the peer will use in this overlay
    /// All the revoked sessionIDs are kept locally by their initiator.
    pub session: SessionId,

    /// Current sequence number. For a new session, must be zero.
    pub seq: u64,

    /// list of publisher currently registered on the peer.
    /// flooded in overlay (with this overlayAdvert) when first joining an overlay, so that subscription routing tables can be updated
    /// or sent in an OverlayAdvertMarker, to a specific new peer that just joined the overlay (in the point of view of the emitter)
    /// it can be left empty when a CoreBrokerConnect is made on a broker that is known to be already part of the overlay.
    pub publishers: Vec<PublisherAdvert>,

    /// the previous session ID the peer was using in this overlay. Used to cleanup seq counters maintained in each other peer
    /// if the previous session is empty (because it is the first time broker joins this overlay)
    /// or if a remote peer doesn't find this session kept locally, it is not an error.
    /// In the later case (if broker missed some intermediary sessions), the remote peer can ask the initiator peer if the last known
    /// session can be locally revoked with a ConfirmRevokedSession message (answered with yes or no)
    pub previous_session: Option<SessionId>,

    /// peer ID of the broker issuing this Advert
    pub peer: DirectPeerId,
}

/// Overlay Advert V0 : used by a broker peer every time it (re)joins an overlay
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OverlayAdvertV0 {
    pub payload: OverlayAdvertPayloadV0,

    /// Signature with peerId private key, over payload
    pub sig: Sig,
}

/// Overlay Advert : used by a broker peer every time it (re)joins an overlay
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OverlayAdvert {
    V0(OverlayAdvertV0),
}

/// CoreBrokerJoinedAdvert V0
///
/// Each broker that is already part of an overlay, when receiving the CoreBrokerJoinedAdvert, should answer with one direct message
/// to the joining peer (found in OverlayAdvertPayloadV0.peer) for each overlay, containing an OverlayAdvertMarker containing their current sequence number.
/// This is sent for each path (in case multiple paths arrive to the same broker). Only the first sequence number received by joining peer is kept locally
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBrokerJoinedAdvertV0 {
    /// list of overlays joined by an initiator broker, and that the forwarding broker has also previously joined
    /// the forwarding broker keeps the ingress edge and all egress edges in the coreRoutingTable
    pub overlays: Vec<OverlayAdvertV0>,
}

/// CoreBrokerLeftAdvert V0
///
/// A broker has disconnected from another broker, and the routes need to be updated
/// this is not used to leave one specific overlay. see OverlayLeave message for that purpose
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBrokerLeftAdvertV0 {
    /// The broker that disconnected from the one that is emitting this advert.
    pub disconnected: DirectPeerId,
}

/// CoreOverlayJoinedAdvert V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreOverlayJoinedAdvertV0 {
    /// One additional overlay joined by an initiator broker, and that the forwarding broker has also previously joined
    /// the forwarding broker keeps the ingress edge and all egress edges in the coreRoutingTable
    pub overlay: OverlayAdvertV0,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBrokerJoinedAdvert {
    V0(CoreBrokerJoinedAdvertV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBrokerLeftAdvert {
    V0(CoreBrokerLeftAdvertV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreOverlayJoinedAdvert {
    V0(CoreOverlayJoinedAdvertV0),
}

/// Content of CoreAdvert V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreAdvertContentV0 {
    BrokerJoined(CoreBrokerJoinedAdvert),
    BrokerLeft(CoreBrokerLeftAdvert),
    OverlayJoined(CoreOverlayJoinedAdvert),
}

/// CoreAdvert V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreAdvertV0 {
    pub content: CoreAdvertContentV0,

    /// list of brokers on the path that was followed to deliver this advert.
    /// new entry pushed each time a forward is happening in the core network
    pub path: Vec<DirectPeerId>,

    /// content signed by the first broker in the path
    pub sig: Sig,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// OverlayAdvertMarker V0
///
/// when receiving a marker, the broker saves the ingress edge and the corresponding remote peer and
/// overlay that can be reached (the OverlayAdvertPayloadV0.peer and .overlay) in the CoreRoutingTable
/// It also saves the sessionId and seq number
/// then a ReturnPathTimingAdvert is sent back
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OverlayAdvertMarkerV0 {
    pub marker: OverlayAdvertV0,

    /// New SessionId that triggered this marker (to avoid replay attacks in the core network)
    pub in_reply_to: SessionId,

    /// path from the new broker who started a session, to the broker that is sending the marker
    pub path: Vec<DirectPeerId>,

    /// randomly generated nonce used for the reply (a ReturnPathTimingMarker) that will be sent back after this marker has been received on the other end
    pub reply_nonce: u64,
}

/// Core Block Get V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBlocksGetV0 {
    /// Block ID to request
    pub ids: Vec<BlockId>,

    /// Whether or not to include all children recursively
    pub include_children: bool,

    /// randomly generated number by requester, used for sending reply.
    /// the requester keeps track of req_nonce and requested peerid.
    /// used for handling the stream
    pub req_nonce: u64,
}

/// Core Block Result V0
///
/// can be a stream
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBlockResultV0 {
    /// Resulting Object(s)
    pub payload: Vec<Block>,

    /// randomly generated number by requester, as received in the request
    pub req_nonce: u64,
}

/// ReturnPathTimingAdvertV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReturnPathTimingAdvertV0 {
    /// Signature over nonce, by sessionId
    pub sig: Sig,

    /// randomly generated number as received in the OverlayAdvertMarker
    pub nonce: u64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OverlayAdvertMarker {
    V0(OverlayAdvertMarkerV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ReturnPathTimingAdvert {
    V0(ReturnPathTimingAdvertV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBlocksGet {
    V0(CoreBlocksGetV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBlockResult {
    V0(CoreBlockResultV0),
}

/// Content of CoreDirectMessage V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreDirectMessageContentV0 {
    OverlayAdvertMarker(OverlayAdvertMarker),
    ReturnPathTimingAdvert(ReturnPathTimingAdvert),
    BlocksGet(CoreBlocksGet),
    BlockResult(CoreBlockResult),
    //PostInbox,
    //PartialSignature,
    //ClientDirectMessage //for messages between forwarded or direct peers
}

/// CoreDirectMessage V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreDirectMessageV0 {
    pub content: CoreDirectMessageContentV0,

    /// list of brokers on the path that must be followed to deliver this message, next hop is at the bottom of the list.
    /// last entry on the list is popped each time a broker is forwarding upstream
    /// when list size is zero, the final destination is reached.
    /// if only one peer in list, and peer not found in local CoreRoutingTable, use the best route to reach it (without popping)
    pub reverse_path: Vec<DirectPeerId>,

    /// The sender
    pub from: DirectPeerId,

    /// content signed by the sender
    pub sig: Sig,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// CoreBrokerConnect V0
///
/// replied with CoreBrokerConnectResponse
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBrokerConnectV0 {
    pub inner_overlays: Vec<OverlayAdvertV0>,
    pub outer_overlays: Vec<Digest>,
}

/// CoreBrokerConnect
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBrokerConnect {
    V0(CoreBrokerConnectV0),
}

/// CoreBrokerConnectResponse
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBrokerConnectResponse {
    V0(CoreBrokerConnectResponseV0),
}

impl CoreBrokerConnect {
    pub fn core_message(&self, id: i64) -> CoreMessage {
        match self {
            CoreBrokerConnect::V0(v0) => {
                CoreMessage::V0(CoreMessageV0::Request(CoreRequest::V0(CoreRequestV0 {
                    padding: vec![],
                    id,
                    content: CoreRequestContentV0::BrokerConnect(CoreBrokerConnect::V0(v0.clone())),
                })))
            }
        }
    }
}

/// sent to a direct peer just before closing the connection
pub type CoreBrokerDisconnectV0 = ();

/// Content of CoreOverlayJoin V0
///
/// replied with an emptyResponse, and an error code if OverlayId not present on remote broker
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreOverlayJoinV0 {
    Inner(OverlayAdvert),
    Outer(Digest),
}

/// Content of OuterOverlayResponse V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayResponseContentV0 {
    EmptyResponse(()),
    Block(Block),
    TopicSyncRes(TopicSyncRes),
    //PostInboxResponse(PostInboxResponse),
}

/// Content of OuterOverlayRequest V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayRequestContentV0 {
    TopicSyncReq(TopicSyncReq),
    OverlayLeave(OverlayLeave),
    TopicSub(PubKey),
    TopicUnsub(PubKey),
    BlocksGet(BlocksGet),
    //PostInboxRequest(PostInboxRequest),
}

/// OuterOverlayRequestV0 V0
///
/// replied with OuterOverlayResponseV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OuterOverlayRequestV0 {
    pub overlay: Digest,
    pub content: OuterOverlayRequestContentV0,
}

/// OuterOverlayResponse V0
///
/// reply to an OuterOverlayRequest V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OuterOverlayResponseV0 {
    pub overlay: Digest,
    pub content: OuterOverlayResponseContentV0,
}

/// Core Topic synchronization request
///
/// behaves like BlockSearchTopic (primarily searches among the publishers, except if search_in_subs is set to true)
/// fanout is 1 for now
///
/// If some target_heads are not found locally, all successors of known_heads are sent anyway,
/// and then this temporary HEAD is used to propagate/fanout the CoreTopicSyncReq to upstream brokers
///
/// Answered with one or many TopicSyncRes a stream of `Block`s or Event of the commits
/// If the responder has an Event for the commit(s) in its HEAD, it will send the event instead of the plain commit's blocks.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreTopicSyncReqV0 {
    /// Topic public key
    pub topic: TopicId,

    /// Also search in subscribers, in addition to publishers
    pub search_in_subs: bool,

    /// Fully synchronized until these commits
    pub known_heads: Vec<ObjectId>,

    /// Stop synchronizing when these commits are met.
    /// if empty, the local HEAD at the responder is used instead
    pub target_heads: Vec<ObjectId>,
}

/// Topic synchronization request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreTopicSyncReq {
    V0(CoreTopicSyncReqV0),
}

/// Topic synchronization response V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TopicSyncResV0 {
    Event(Event),
    Block(Block),
}

/// Topic synchronization response
///
/// it is a stream of blocks and or events.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TopicSyncRes {
    V0(TopicSyncResV0),
}

impl TopicSyncRes {
    pub fn event(&self) -> &Event {
        match self {
            Self::V0(TopicSyncResV0::Event(e)) => e,
            _ => panic!("this TopicSyncResV0 is not an event"),
        }
    }
}

impl fmt::Display for TopicSyncRes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::V0(v0) => match v0 {
                TopicSyncResV0::Event(e) => writeln!(f, "====== Event ====== {e}"),
                TopicSyncResV0::Block(b) => writeln!(f, "====== Block ID ====== {}", b.id()),
            },
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreBrokerDisconnect {
    V0(CoreBrokerDisconnectV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreOverlayJoin {
    V0(CoreOverlayJoinV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayRequest {
    V0(OuterOverlayRequestV0),
}

/// Content of CoreRequest V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreRequestContentV0 {
    BrokerConnect(CoreBrokerConnect),
    BrokerDisconnect(CoreBrokerDisconnect),
    OverlayJoin(CoreOverlayJoin),
    BlockSearchTopic(BlockSearchTopic),
    BlockSearchRandom(BlockSearchRandom),
    TopicSyncReq(CoreTopicSyncReq),
    OuterOverlayRequest(OuterOverlayRequest),
}

/// CoreRequest V0
///
/// replied with CoreResponse V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreRequestV0 {
    /// Request ID
    pub id: i64,
    pub content: CoreRequestContentV0,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// Request sent to a broker in the core network
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreRequest {
    V0(CoreRequestV0),
}

/// CoreBrokerConnectResponse V0
///
/// reply to a CoreBrokerConnect V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreBrokerConnectResponseV0 {
    pub successes: Vec<OverlayId>,
    pub errors: Vec<OverlayId>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayResponse {
    V0(OuterOverlayResponseV0),
}

/// Content CoreResponse V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreResponseContentV0 {
    BrokerConnectResponse(CoreBrokerConnectResponse),
    BlockResult(BlockResult),
    TopicSyncRes(TopicSyncRes),
    OuterOverlayResponse(OuterOverlayResponse),
    EmptyResponse(()),
}

/// CoreResponse V0
///
/// reply to a CoreRequest V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoreResponseV0 {
    /// Request ID
    pub id: i64,

    /// Result
    pub result: u16,
    pub content: CoreResponseContentV0,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// Response to a Request sent to a broker in the core network
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreResponse {
    V0(CoreResponseV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayMessageContentV0 {
    Event(Event),
}

/// OuterOverlayMessage V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OuterOverlayMessageV0 {
    pub overlay: Digest,

    pub content: OuterOverlayMessageContentV0,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreAdvert {
    V0(CoreAdvertV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreDirectMessage {
    V0(CoreDirectMessageV0),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OuterOverlayMessage {
    V0(OuterOverlayMessageV0),
}

/// CoreMessageV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreMessageV0 {
    Request(CoreRequest),
    Response(CoreResponse),
    Advert(CoreAdvert),
    Direct(CoreDirectMessage),
    InnerOverlay(InnerOverlayMessage),
    OuterOverlay(OuterOverlayMessage),
}

/// Core message
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreMessage {
    V0(CoreMessageV0),
}

/// AppMessageContentV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AppMessageContentV0 {
    Request(AppRequest),
    Response(AppResponse),
    SessionStop(AppSessionStop),
    SessionStart(AppSessionStart),
    EmptyResponse,
}

/// AppMessageV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppMessageV0 {
    pub content: AppMessageContentV0,

    pub id: i64,

    pub result: u16,
}

/// App message
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AppMessage {
    V0(AppMessageV0),
}

impl IStreamable for AppMessage {
    fn result(&self) -> u16 {
        match self {
            AppMessage::V0(v0) => v0.result,
        }
    }
    fn set_result(&mut self, result: u16) {
        match self {
            AppMessage::V0(v0) => v0.result = result,
        }
    }
}

impl AppMessage {
    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            AppMessage::V0(AppMessageV0 { content: o, id, .. }) => match o {
                AppMessageContentV0::Request(req) => req.get_actor(*id),
                AppMessageContentV0::SessionStop(req) => req.get_actor(*id),
                AppMessageContentV0::SessionStart(req) => req.get_actor(*id),
                AppMessageContentV0::Response(_) | AppMessageContentV0::EmptyResponse => {
                    panic!("it is not a request");
                }
            },
        }
    }
    pub fn id(&self) -> Option<i64> {
        match self {
            AppMessage::V0(v0) => Some(v0.id),
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            AppMessage::V0(r) => r.id = id,
        }
    }
}

impl From<AppMessage> for ProtocolMessage {
    fn from(msg: AppMessage) -> ProtocolMessage {
        ProtocolMessage::AppMessage(msg)
    }
}

//
// ADMIN PROTOCOL
//

/// Content of `AdminRequestV0`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AdminRequestContentV0 {
    AddUser(AddUser),
    DelUser(DelUser),
    ListUsers(ListUsers),
    ListInvitations(ListInvitations),
    AddInvitation(AddInvitation),
    #[doc(hidden)]
    CreateUser(CreateUser),
}
impl AdminRequestContentV0 {
    pub fn type_id(&self) -> TypeId {
        match self {
            Self::AddUser(a) => a.type_id(),
            Self::DelUser(a) => a.type_id(),
            Self::ListUsers(a) => a.type_id(),
            Self::ListInvitations(a) => a.type_id(),
            Self::AddInvitation(a) => a.type_id(),
            Self::CreateUser(a) => a.type_id(),
        }
    }
    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            Self::AddUser(a) => a.get_actor(),
            Self::DelUser(a) => a.get_actor(),
            Self::ListUsers(a) => a.get_actor(),
            Self::ListInvitations(a) => a.get_actor(),
            Self::AddInvitation(a) => a.get_actor(),
            Self::CreateUser(a) => a.get_actor(),
        }
    }
}

/// Admin request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AdminRequestV0 {
    /// Request ID
    pub id: i64,

    /// Request content
    pub content: AdminRequestContentV0,

    /// Signature over content by admin key
    pub sig: Sig,

    /// THe admin user requesting this operation
    pub admin_user: PubKey,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

impl AdminRequestV0 {
    pub fn get_actor(&self) -> Box<dyn EActor> {
        self.content.get_actor()
    }
}

/// Admin request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AdminRequest {
    V0(AdminRequestV0),
}

impl AdminRequest {
    pub fn id(&self) -> i64 {
        match self {
            Self::V0(o) => o.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            Self::V0(v0) => {
                v0.id = id;
            }
        }
    }
    pub fn type_id(&self) -> TypeId {
        match self {
            Self::V0(o) => o.content.type_id(),
        }
    }
    pub fn sig(&self) -> Sig {
        match self {
            Self::V0(o) => o.sig,
        }
    }
    pub fn admin_user(&self) -> PubKey {
        match self {
            Self::V0(o) => o.admin_user,
        }
    }
    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            Self::V0(a) => a.get_actor(),
        }
    }
}

impl From<AdminRequest> for ProtocolMessage {
    fn from(msg: AdminRequest) -> ProtocolMessage {
        ProtocolMessage::Start(StartProtocol::Admin(msg))
    }
}

/// Content of `AdminResponseV0`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AdminResponseContentV0 {
    EmptyResponse,
    Users(Vec<PubKey>),
    Invitations(Vec<(InvitationCode, u32, Option<String>)>),
    Invitation(Invitation),
    UserId(UserId),
}

/// Response to an `AdminRequest` V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AdminResponseV0 {
    /// Request ID
    pub id: i64,

    /// Result (including but not limited to Result)
    pub result: u16,

    pub content: AdminResponseContentV0,

    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

/// Response to an `AdminRequest`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AdminResponse {
    V0(AdminResponseV0),
}

impl From<Result<(), ProtocolError>> for AdminResponseV0 {
    fn from(res: Result<(), ProtocolError>) -> AdminResponseV0 {
        AdminResponseV0 {
            id: 0,
            result: res.map(|_| 0).unwrap_or_else(|e| e.into()),
            content: AdminResponseContentV0::EmptyResponse,
            padding: vec![],
        }
    }
}

impl From<Result<PubKey, ProtocolError>> for AdminResponseV0 {
    fn from(res: Result<PubKey, ProtocolError>) -> AdminResponseV0 {
        match res {
            Err(e) => AdminResponseV0 {
                id: 0,
                result: e.into(),
                content: AdminResponseContentV0::EmptyResponse,
                padding: vec![],
            },
            Ok(id) => AdminResponseV0 {
                id: 0,
                result: 0,
                content: AdminResponseContentV0::UserId(id),
                padding: vec![],
            },
        }
    }
}

impl From<Result<Vec<PubKey>, ProtocolError>> for AdminResponseV0 {
    fn from(res: Result<Vec<PubKey>, ProtocolError>) -> AdminResponseV0 {
        match res {
            Err(e) => AdminResponseV0 {
                id: 0,
                result: e.into(),
                content: AdminResponseContentV0::EmptyResponse,
                padding: vec![],
            },
            Ok(vec) => AdminResponseV0 {
                id: 0,
                result: 0,
                content: AdminResponseContentV0::Users(vec),
                padding: vec![],
            },
        }
    }
}

impl From<AdminResponseV0> for ProtocolMessage {
    fn from(msg: AdminResponseV0) -> ProtocolMessage {
        ProtocolMessage::AdminResponse(AdminResponse::V0(msg))
    }
}

impl From<AdminResponse> for ProtocolMessage {
    fn from(msg: AdminResponse) -> ProtocolMessage {
        ProtocolMessage::AdminResponse(msg)
    }
}

impl TryFrom<ProtocolMessage> for AdminResponse {
    type Error = ProtocolError;
    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
        if let ProtocolMessage::AdminResponse(res) = msg {
            Ok(res)
        } else {
            Err(ProtocolError::InvalidValue)
        }
    }
}

impl AdminResponse {
    pub fn id(&self) -> i64 {
        match self {
            Self::V0(o) => o.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            Self::V0(v0) => {
                v0.id = id;
            }
        }
    }
    pub fn result(&self) -> u16 {
        match self {
            Self::V0(o) => o.result,
        }
    }
    pub fn content_v0(&self) -> AdminResponseContentV0 {
        match self {
            Self::V0(o) => o.content.clone(),
        }
    }
}

//
// CLIENT PROTOCOL
//

/// Request to open a repo in a non-durable way (without pinning it).
///
/// When client will disconnect, the subscriptions and publisherAdvert of the topics will be removed,
/// except if a PinRepo occurred before or after the OpenRepo
/// replied with a RepoOpened
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OpenRepoV0 {
    /// Repo Hash
    pub hash: RepoHash,

    // for RW overlay, the overlay that should be used in the clientmessage is the innerOverlay
    pub overlay: OverlayAccess,

    /// Broker peers to connect to in order to join the overlay
    /// can be empty for private store (the broker will not connect to any other broker)
    /// but if the private repo is pinned in other brokers, those brokers should be entered here for syncing.
    /// can be empty also when we just created the repo, and there are no other brokers in the overlay
    pub peers: Vec<PeerAdvert>,

    /// a list of core brokers that are allowed to connect to the overlay (only valid for an inner (RW/WO) overlay).
    /// an empty list means any core broker is allowed. this is the default behaviour.
    /// to restrict the overlay to only the current core, its DirectPeerId should be entered here.
    // pub allowed_peers: Vec<DirectPeerId>,

    /// Maximum number of peers to connect to for this overlay (only valid for an inner (RW/WO) overlay)
    /// 0 means automatic/unlimited
    pub max_peer_count: u16,

    /// list of topics that should be subscribed to
    pub ro_topics: Vec<TopicId>,

    /// list of topics for which we will be a publisher
    /// only possible with inner (RW or WO) overlays.
    /// implies also subscribing to it (no need to put it also in ro_topics)
    pub rw_topics: Vec<PublisherAdvert>,
}

/// Request to open a repo
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OpenRepo {
    V0(OpenRepoV0),
}

impl OpenRepo {
    pub fn peers(&self) -> &Vec<PeerAdvert> {
        match self {
            OpenRepo::V0(o) => &o.peers,
        }
    }
}

/// Request to pin a repo on the broker.
///
/// When client will disconnect, the subscriptions and publisherAdvert of the topics will be remain active on the broker.
/// replied with a RepoOpened
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PinRepoV0 {
    /// Repo Hash
    pub hash: RepoHash,

    /// for RW overlay, the overlay that should be used in the clientmessage is the innerOverlay
    pub overlay: OverlayAccess,

    /// Root topic of the overlay, used to listen to overlay refreshes. Only used for inner (RW or WO) overlays
    pub overlay_root_topic: Option<TopicId>,

    /// only possible for RW overlays. not allowed for private or dialog overlay
    pub expose_outer: bool,

    /// Broker peers to connect to in order to join the overlay
    /// If the repo has previously been opened (during the same session) or if it is a private overlay, then peers info can be omitted.
    /// If there are no known peers in the overlay yet, vector is left empty (creation of a store, or repo in a store that is owned by user).
    pub peers: Vec<PeerAdvert>,

    /// Maximum number of peers to connect to for this overlay (only valid for an inner (RW/WO) overlay)
    pub max_peer_count: u16,

    // /// a list of core brokers that are allowed to connect to the overlay (only valid for an inner (RW/WO) overlay).
    // /// an empty list means any core broker is allowed. this is the default behaviour.
    // /// to restrict the overlay to only the current core, its DirectPeerId should be entered here.
    // /// not compatible with expose_outer
    // this is probably going to be a config in the server itself.
    // pub allowed_peers: Vec<DirectPeerId>,
    /// list of topics that should be subscribed to
    /// If the repo has previously been opened (during the same session) then ro_topics info can be omitted
    pub ro_topics: Vec<TopicId>,

    /// list of topics for which we will be a publisher
    /// only possible with inner (RW or WO) overlays.
    /// If the repo has previously been opened (during the same session) then rw_topics info can be omitted
    pub rw_topics: Vec<PublisherAdvert>,
    // TODO pub inbox_proof
    // TODO pub signer_proof
}

/// Request to pin a repo
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PinRepo {
    V0(PinRepoV0),
}

impl PinRepo {
    pub fn peers(&self) -> &Vec<PeerAdvert> {
        match self {
            PinRepo::V0(o) => &o.peers,
        }
    }
    pub fn hash(&self) -> &RepoHash {
        match self {
            PinRepo::V0(o) => &o.hash,
        }
    }
    pub fn ro_topics(&self) -> &Vec<TopicId> {
        match self {
            PinRepo::V0(o) => &o.ro_topics,
        }
    }
    pub fn rw_topics(&self) -> &Vec<PublisherAdvert> {
        match self {
            PinRepo::V0(o) => &o.rw_topics,
        }
    }
    pub fn overlay(&self) -> &OverlayId {
        match self {
            PinRepo::V0(o) => &o.overlay.overlay_id_for_client_protocol_purpose(),
        }
    }
    pub fn overlay_access(&self) -> &OverlayAccess {
        match self {
            PinRepo::V0(o) => &o.overlay,
        }
    }

    pub fn overlay_root_topic(&self) -> &Option<TopicId> {
        match self {
            PinRepo::V0(o) => &o.overlay_root_topic,
        }
    }

    pub fn expose_outer(&self) -> bool {
        match self {
            PinRepo::V0(o) => o.expose_outer,
        }
    }
}

/// Request to refresh the Pinning of a previously pinned repo.
///
/// it can consist of updating the expose_outer, the list of ro_topics and/or rw_topics,
/// and in case of a ban_member, the broker will effectively flush the topics locally after all local members except the banned one, have refreshed
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefreshPinRepoV0 {
    /// The new PinRepo info
    pub pin: PinRepo,

    /// optional hashed member ID that should be banned
    pub ban_member: Option<Digest>,

    /// when banning, list of topics that are to be flushed (once all the local members have left, except the one to be banned)
    /// All the honest local members have to send this list in order for the banned one to be effectively banned
    /// for each Topic, a signature over the hashed UserId to ban, by the Topic private key.
    /// The banning process on the broker is meant to flush topics that would remain dangling if the malicious member would not unpin them after being removed from members of repo.
    /// The userId of banned user is revealed to the local broker where it was attached, which is a breach of privacy deemed acceptable
    /// as only a broker that already knew the userid will enforce it, and
    /// that broker might be interested to know that the offending user was banned from a repo, as only malicious users are banned.
    /// The broker might also discard this information, and just proceed with the flush without much ado.
    /// Of course, if the broker is controlled by the malicious user, it might not proceed with the ban/flush. But who cares. That broker will keep old data forever, but it is a malicious broker anyway.
    pub flush_topics: Vec<(TopicId, Sig)>,
}

/// Request to pin a repo
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RefreshPinRepo {
    V0(RefreshPinRepoV0),
}

/// Request to unpin a repo on the broker.
///
/// When client will disconnect, the subscriptions and publisherAdvert of the topics will be removed on the broker
/// (for that user only. other users might continue to have the repo pinned)

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UnpinRepoV0 {
    /// Repo Hash
    pub hash: RepoHash,
}

/// Request to unpin a repo
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum UnpinRepo {
    V0(UnpinRepoV0),
}

impl UnpinRepo {
    pub fn hash(&self) -> &RepoHash {
        match self {
            UnpinRepo::V0(o) => &o.hash,
        }
    }
}

/// Request the status of pinning for a repo on the broker. V0
///
/// returns an error code if not pinned, otherwise returns a RepoPinStatusV0
/// the overlay entered in ClientMessage is important. if it is the outer, only outer pinning will be checked.
/// if it is the inner overlay, only the inner pinning will be checked.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepoPinStatusReqV0 {
    /// Repo Hash
    pub hash: RepoHash,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request the status of pinning for a repo on the broker.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RepoPinStatusReq {
    V0(RepoPinStatusReqV0),
}

impl RepoPinStatusReq {
    pub fn hash(&self) -> &RepoHash {
        match self {
            RepoPinStatusReq::V0(o) => &o.hash,
        }
    }
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            Self::V0(v0) => v0.overlay = Some(overlay),
        }
    }

    pub fn overlay(&self) -> &OverlayId {
        match self {
            Self::V0(v0) => v0.overlay.as_ref().unwrap(),
        }
    }
}

/// Response with the status of pinning for a repo on the broker. V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepoPinStatusV0 {
    /// Repo Hash
    pub hash: RepoHash,

    /// only possible for RW overlays
    pub expose_outer: bool,

    /// list of topics that are subscribed to
    pub topics: Vec<TopicSubRes>,
    // TODO pub inbox_proof

    // TODO pub signer_proof
}

/// Response with the status of pinning for a repo on the broker.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RepoPinStatus {
    V0(RepoPinStatusV0),
}

impl RepoPinStatus {
    pub fn hash(&self) -> &RepoHash {
        match self {
            RepoPinStatus::V0(o) => &o.hash,
        }
    }
    pub fn is_topic_subscribed_as_publisher(&self, topic: &TopicId) -> bool {
        match self {
            Self::V0(v0) => {
                for sub in &v0.topics {
                    if sub.topic_id() == topic {
                        return sub.is_publisher();
                    }
                }
                false
            }
        }
    }
    pub fn topics(&self) -> &Vec<TopicSubRes> {
        match self {
            Self::V0(v0) => &v0.topics,
        }
    }
}

/// Request subscription to a `Topic` of an already opened or pinned Repo
///
/// replied with a TopicSubRes containing the current heads that should be used to do a TopicSync
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct TopicSubV0 {
    /// Topic to subscribe
    pub topic: TopicId,

    /// Hash of the repo that was previously opened or pinned
    pub repo_hash: RepoHash,

    /// Publisher need to provide a signed `PublisherAdvert` for the PeerId of the broker
    pub publisher: Option<PublisherAdvert>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request subscription to a `Topic` of an already opened or pinned Repo
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum TopicSub {
    V0(TopicSubV0),
}

impl TopicSub {
    pub fn hash(&self) -> &RepoHash {
        match self {
            Self::V0(o) => &o.repo_hash,
        }
    }
    pub fn topic(&self) -> &TopicId {
        match self {
            Self::V0(o) => &o.topic,
        }
    }
    pub fn publisher(&self) -> Option<&PublisherAdvert> {
        match self {
            Self::V0(o) => o.publisher.as_ref(),
        }
    }
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            Self::V0(v0) => v0.overlay = Some(overlay),
        }
    }
    pub fn overlay(&self) -> &OverlayId {
        match self {
            Self::V0(v0) => v0.overlay.as_ref().unwrap(),
        }
    }
}

/// Request unsubscription from a `Topic` of an already opened or pinned Repo
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct TopicUnsubV0 {
    /// Topic to unsubscribe
    pub topic: PubKey,

    /// Hash of the repo that was previously opened or pinned
    pub repo_hash: RepoHash,
}

/// Request unsubscription from a `Topic` of an already opened or pinned Repo
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum TopicUnsub {
    V0(TopicUnsubV0),
}

/// Request a Block by ID
///
/// commit_header_key is always set to None in the reply when request is made on OuterOverlay of protected or Group overlays
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlocksGetV0 {
    /// Block IDs to request
    pub ids: Vec<BlockId>,

    /// Whether or not to include all children recursively
    pub include_children: bool,

    /// Topic the object is referenced from, if it is known by the requester.
    /// can be used to do a BlockSearchTopic in the core overlay.
    pub topic: Option<TopicId>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request an object by ID
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlocksGet {
    V0(BlocksGetV0),
}

impl BlocksGet {
    pub fn ids(&self) -> &Vec<BlockId> {
        match self {
            BlocksGet::V0(o) => &o.ids,
        }
    }
    pub fn include_children(&self) -> bool {
        match self {
            BlocksGet::V0(o) => o.include_children,
        }
    }
    pub fn topic(&self) -> Option<PubKey> {
        match self {
            BlocksGet::V0(o) => o.topic,
        }
    }
}

/// Request a Commit by ID
///
/// commit_header_key is always set to None in the reply when request is made on OuterOverlay of protected or Group overlays
/// The difference with BlocksGet is that the Broker will try to return all the commit blocks as they were sent in the Pub/Sub Event, if it has it.
/// This will help in having all the blocks (including the header and body blocks), while a BlocksGet would inevitably return only the blocks of the ObjectContent,
/// and not the header nor the body. And the load() would fail with CommitLoadError::MissingBlocks. That's what happens when the Commit is not present in the pubsub,
/// and we need to default to using BlocksGet instead.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommitGetV0 {
    /// Block IDs to request
    pub id: ObjectId,

    /// Topic the commit is referenced from, if it is known by the requester.
    /// can be used to do a BlockSearchTopic in the core overlay.
    pub topic: Option<TopicId>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request a Commit by ID (see [CommitGetV0] for more details)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CommitGet {
    V0(CommitGetV0),
}
impl CommitGet {
    pub fn id(&self) -> &ObjectId {
        match self {
            CommitGet::V0(o) => &o.id,
        }
    }
}

/// Request to store one or more blocks
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlocksPutV0 {
    /// Blocks to store
    pub blocks: Vec<Block>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request to store one or more blocks
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlocksPut {
    V0(BlocksPutV0),
}

impl BlocksPut {
    pub fn blocks(&self) -> &Vec<Block> {
        match self {
            BlocksPut::V0(o) => &o.blocks,
        }
    }
    pub fn overlay(&self) -> &OverlayId {
        match self {
            Self::V0(v0) => v0.overlay.as_ref().unwrap(),
        }
    }
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            Self::V0(v0) => v0.overlay = Some(overlay),
        }
    }
}

/// Request to know if some blocks are present locally
///
/// used by client before publishing an event with files, to know what to push
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlocksExistV0 {
    /// Ids of Blocks to check
    pub blocks: Vec<BlockId>,

    #[serde(skip)]
    pub overlay: Option<OverlayId>,
}

/// Request to store one or more blocks
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlocksExist {
    V0(BlocksExistV0),
}

impl BlocksExist {
    pub fn blocks(&self) -> &Vec<BlockId> {
        match self {
            BlocksExist::V0(o) => &o.blocks,
        }
    }
    pub fn overlay(&self) -> &OverlayId {
        match self {
            Self::V0(v0) => v0.overlay.as_ref().unwrap(),
        }
    }
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            Self::V0(v0) => v0.overlay = Some(overlay),
        }
    }
}

/// Request to pin an object
///
/// Brokers maintain an LRU cache of objects,
/// where old, unused objects might get deleted to free up space for new ones.
/// Pinned objects are retained, regardless of last access.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ObjectPinV0 {
    pub id: ObjectId,
}

/// Request to pin an object
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum ObjectPin {
    V0(ObjectPinV0),
}

impl ObjectPin {
    pub fn id(&self) -> ObjectId {
        match self {
            ObjectPin::V0(o) => o.id,
        }
    }
}

/// Request to unpin an object
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ObjectUnpinV0 {
    pub id: ObjectId,
}

/// Request to unpin an object
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum ObjectUnpin {
    V0(ObjectUnpinV0),
}

impl ObjectUnpin {
    pub fn id(&self) -> ObjectId {
        match self {
            ObjectUnpin::V0(o) => o.id,
        }
    }
}

/// Request to delete an object
///
/// only effective if the refcount for this object is zero (basically it removes it from LRU)
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ObjectDelV0 {
    pub id: ObjectId,
}

/// Request to delete an object
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum ObjectDel {
    V0(ObjectDelV0),
}

impl ObjectDel {
    pub fn id(&self) -> ObjectId {
        match self {
            ObjectDel::V0(o) => o.id,
        }
    }
}

/// Request to publish an event in pubsub
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PublishEvent(pub Event, #[serde(skip)] pub Option<OverlayId>);

/// Content of `ClientRequestV0`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientRequestContentV0 {
    OpenRepo(OpenRepo),
    PinRepo(PinRepo),
    UnpinRepo(UnpinRepo),
    RepoPinStatusReq(RepoPinStatusReq),

    // once repo is opened or pinned:
    TopicSub(TopicSub),
    TopicUnsub(TopicUnsub),

    BlocksExist(BlocksExist),
    BlocksGet(BlocksGet),
    CommitGet(CommitGet),
    TopicSyncReq(TopicSyncReq),

    // For Pinned Repos only :
    ObjectPin(ObjectPin),
    ObjectUnpin(ObjectUnpin),
    ObjectDel(ObjectDel),

    // For InnerOverlay's only :
    BlocksPut(BlocksPut),
    PublishEvent(PublishEvent),
}

impl ClientRequestContentV0 {
    pub fn set_overlay(&mut self, overlay: OverlayId) {
        match self {
            ClientRequestContentV0::RepoPinStatusReq(a) => a.set_overlay(overlay),
            ClientRequestContentV0::TopicSub(a) => a.set_overlay(overlay),
            ClientRequestContentV0::PinRepo(_a) => {}
            ClientRequestContentV0::PublishEvent(a) => a.set_overlay(overlay),
            ClientRequestContentV0::CommitGet(a) => a.set_overlay(overlay),
            ClientRequestContentV0::TopicSyncReq(a) => a.set_overlay(overlay),
            ClientRequestContentV0::BlocksPut(a) => a.set_overlay(overlay),
            ClientRequestContentV0::BlocksExist(a) => a.set_overlay(overlay),
            ClientRequestContentV0::BlocksGet(a) => a.set_overlay(overlay),
            _ => unimplemented!(),
        }
    }
}

/// Broker overlay request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientRequestV0 {
    /// Request ID
    pub id: i64,

    /// Request content
    pub content: ClientRequestContentV0,
}

/// Broker overlay request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientRequest {
    V0(ClientRequestV0),
}

impl ClientRequest {
    pub fn id(&self) -> i64 {
        match self {
            ClientRequest::V0(o) => o.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ClientRequest::V0(v0) => {
                v0.id = id;
            }
        }
    }
    pub fn content_v0(&self) -> &ClientRequestContentV0 {
        match self {
            ClientRequest::V0(o) => &o.content,
        }
    }
    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            Self::V0(ClientRequestV0 { content, .. }) => match content {
                ClientRequestContentV0::RepoPinStatusReq(r) => r.get_actor(self.id()),
                ClientRequestContentV0::PinRepo(r) => r.get_actor(self.id()),
                ClientRequestContentV0::TopicSub(r) => r.get_actor(self.id()),
                ClientRequestContentV0::PublishEvent(r) => r.get_actor(self.id()),
                ClientRequestContentV0::CommitGet(r) => r.get_actor(self.id()),
                ClientRequestContentV0::TopicSyncReq(r) => r.get_actor(self.id()),
                ClientRequestContentV0::BlocksPut(r) => r.get_actor(self.id()),
                ClientRequestContentV0::BlocksExist(r) => r.get_actor(self.id()),
                ClientRequestContentV0::BlocksGet(r) => r.get_actor(self.id()),
                _ => unimplemented!(),
            },
        }
    }
}

impl TryFrom<ProtocolMessage> for ClientRequestContentV0 {
    type Error = ProtocolError;
    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
        if let ProtocolMessage::ClientMessage(ClientMessage::V0(ClientMessageV0 {
            overlay,
            content:
                ClientMessageContentV0::ClientRequest(ClientRequest::V0(ClientRequestV0 {
                    mut content,
                    ..
                })),
            ..
        })) = msg
        {
            content.set_overlay(overlay);
            Ok(content)
        } else {
            log_debug!("INVALID {:?}", msg);
            Err(ProtocolError::InvalidValue)
        }
    }
}

/// Response which blocks have been found locally. V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlocksFoundV0 {
    /// Ids of Blocks that were found locally
    pub found: Vec<BlockId>,

    /// Ids of Blocks that were missing locally
    pub missing: Vec<BlockId>,
}

/// Response which blocks have been found locally.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BlocksFound {
    V0(BlocksFoundV0),
}

impl BlocksFound {
    pub fn found(&self) -> &Vec<BlockId> {
        match self {
            BlocksFound::V0(o) => &o.found,
        }
    }
    pub fn missing(&self) -> &Vec<BlockId> {
        match self {
            BlocksFound::V0(o) => &o.missing,
        }
    }
}

/// Topic subscription response V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TopicSubResV0 {
    /// Topic subscribed
    pub topic: TopicId,
    pub known_heads: Vec<ObjectId>,
    pub publisher: bool,
    pub commits_nbr: u64,
}

/// Topic subscription response
///
/// it is a stream of blocks and or events.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TopicSubRes {
    V0(TopicSubResV0),
}

impl TopicSubRes {
    pub fn topic_id(&self) -> &TopicId {
        match self {
            Self::V0(v0) => &v0.topic,
        }
    }
    pub fn is_publisher(&self) -> bool {
        match self {
            Self::V0(v0) => v0.publisher,
        }
    }
    pub fn new_from_heads(
        topics: HashSet<ObjectId>,
        publisher: bool,
        topic: TopicId,
        commits_nbr: u64,
    ) -> Self {
        TopicSubRes::V0(TopicSubResV0 {
            topic,
            known_heads: topics.into_iter().collect(),
            publisher,
            commits_nbr,
        })
    }
    pub fn known_heads(&self) -> &Vec<ObjectId> {
        match self {
            Self::V0(v0) => &v0.known_heads,
        }
    }
    pub fn commits_nbr(&self) -> u64 {
        match self {
            Self::V0(v0) => v0.commits_nbr,
        }
    }
}

impl From<TopicId> for TopicSubRes {
    fn from(topic: TopicId) -> Self {
        TopicSubRes::V0(TopicSubResV0 {
            topic,
            known_heads: vec![],
            publisher: false,
            commits_nbr: 0,
        })
    }
}

impl From<PublisherAdvert> for TopicSubRes {
    fn from(topic: PublisherAdvert) -> Self {
        TopicSubRes::V0(TopicSubResV0 {
            topic: topic.topic_id().clone(),
            known_heads: vec![],
            publisher: true,
            commits_nbr: 0,
        })
    }
}

pub type RepoOpened = Vec<TopicSubRes>;

/// Content of `ClientResponseV0`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientResponseContentV0 {
    EmptyResponse,
    Block(Block),
    RepoOpened(RepoOpened),
    TopicSubRes(TopicSubRes),
    TopicSyncRes(TopicSyncRes),
    BlocksFound(BlocksFound),
    RepoPinStatus(RepoPinStatus),
}

/// Response to a `ClientRequest`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientResponseV0 {
    /// Request ID
    pub id: i64,

    /// Result (including but not limited to Result)
    pub result: u16,

    /// Response content
    pub content: ClientResponseContentV0,
}

impl ClientResponse {
    pub fn set_result(&mut self, res: u16) {
        match self {
            Self::V0(v0) => v0.result = res,
        }
    }
}

/// Response to a `ClientRequest`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientResponse {
    V0(ClientResponseV0),
}

impl From<ServerError> for ClientResponse {
    fn from(err: ServerError) -> ClientResponse {
        ClientResponse::V0(ClientResponseV0 {
            id: 0,
            result: err.into(),
            content: ClientResponseContentV0::EmptyResponse,
        })
    }
}

#[derive(Debug)]
pub struct EmptyAppResponse(pub ());

impl From<ServerError> for AppMessage {
    fn from(err: ServerError) -> AppMessage {
        AppMessage::V0(AppMessageV0 {
            id: 0,
            result: err.into(),
            content: AppMessageContentV0::EmptyResponse,
        })
    }
}

impl<A> From<Result<A, ServerError>> for ProtocolMessage
where
    A: Into<ProtocolMessage> + std::fmt::Debug,
{
    fn from(res: Result<A, ServerError>) -> ProtocolMessage {
        match res {
            Ok(a) => a.into(),
            Err(e) => ProtocolMessage::from_client_response_err(e),
        }
    }
}

impl From<()> for ProtocolMessage {
    fn from(_msg: ()) -> ProtocolMessage {
        let cm: ClientResponse = ServerError::Ok.into();
        cm.into()
    }
}

impl ClientResponse {
    pub fn id(&self) -> i64 {
        match self {
            ClientResponse::V0(o) => o.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ClientResponse::V0(v0) => {
                v0.id = id;
            }
        }
    }
    pub fn result(&self) -> u16 {
        match self {
            ClientResponse::V0(o) => o.result,
        }
    }
    pub fn block(&self) -> Option<&Block> {
        match self {
            ClientResponse::V0(o) => match &o.content {
                ClientResponseContentV0::Block(b) => Some(b),
                _ => panic!("this not a block response"),
            },
        }
    }
}

impl TryFrom<ProtocolMessage> for ClientResponseContentV0 {
    type Error = ProtocolError;
    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
        if let ProtocolMessage::ClientMessage(ClientMessage::V0(ClientMessageV0 {
            content:
                ClientMessageContentV0::ClientResponse(ClientResponse::V0(ClientResponseV0 {
                    content,
                    result: res,
                    ..
                })),
            ..
        })) = msg
        {
            let err = ServerError::try_from(res).unwrap();
            if !err.is_err() {
                Ok(content)
            } else {
                Err(ProtocolError::ServerError)
            }
        } else {
            log_debug!("INVALID {:?}", msg);
            Err(ProtocolError::InvalidValue)
        }
    }
}

/// Content of `ClientMessageV0`
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientMessageContentV0 {
    ClientRequest(ClientRequest),
    ClientResponse(ClientResponse),
    ForwardedEvent(Event),
    ForwardedBlock(Block),
}
impl ClientMessageContentV0 {
    pub fn is_block(&self) -> bool {
        match self {
            Self::ClientRequest(ClientRequest::V0(ClientRequestV0 {
                content: ClientRequestContentV0::BlocksPut(_),
                ..
            })) => true,
            Self::ClientResponse(ClientResponse::V0(ClientResponseV0 {
                content: ClientResponseContentV0::Block(_),
                ..
            })) => true,
            _ => false,
        }
    }
}

/// Broker message for an overlay
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientMessageV0 {
    pub overlay: OverlayId,
    pub content: ClientMessageContentV0,
    /// Optional padding
    #[serde(with = "serde_bytes")]
    pub padding: Vec<u8>,
}

pub trait IStreamable {
    fn result(&self) -> u16;
    fn set_result(&mut self, result: u16);
}

/// Broker message for an overlay
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientMessage {
    V0(ClientMessageV0),
}

impl IStreamable for ClientMessage {
    fn result(&self) -> u16 {
        match self {
            ClientMessage::V0(o) => match &o.content {
                ClientMessageContentV0::ClientResponse(r) => r.result(),
                ClientMessageContentV0::ClientRequest(_)
                | ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => {
                    panic!("it is not a response");
                }
            },
        }
    }
    fn set_result(&mut self, result: u16) {
        match self {
            ClientMessage::V0(o) => match &mut o.content {
                ClientMessageContentV0::ClientResponse(r) => r.set_result(result),
                ClientMessageContentV0::ClientRequest(_)
                | ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => {
                    panic!("it is not a response");
                }
            },
        }
    }
}

impl ClientMessage {
    pub fn content_v0(&self) -> &ClientMessageContentV0 {
        match self {
            ClientMessage::V0(o) => &o.content,
        }
    }
    pub fn overlay_request(&self) -> &ClientRequest {
        match self {
            ClientMessage::V0(o) => match &o.content {
                ClientMessageContentV0::ClientRequest(r) => &r,
                _ => panic!("not an overlay request"),
            },
        }
    }

    pub fn forwarded_event(self) -> Option<(Event, OverlayId)> {
        let overlay = self.overlay_id();
        match self {
            ClientMessage::V0(o) => match o.content {
                ClientMessageContentV0::ForwardedEvent(e) => Some((e, overlay)),
                _ => None,
            },
        }
    }
    pub fn overlay_id(&self) -> OverlayId {
        match self {
            ClientMessage::V0(o) => o.overlay,
        }
    }
    pub fn is_request(&self) -> bool {
        match self {
            ClientMessage::V0(o) => {
                matches!(o.content, ClientMessageContentV0::ClientRequest { .. })
            }
        }
    }
    pub fn is_response(&self) -> bool {
        match self {
            ClientMessage::V0(o) => {
                matches!(o.content, ClientMessageContentV0::ClientResponse { .. })
            }
        }
    }
    pub fn id(&self) -> Option<i64> {
        match self {
            ClientMessage::V0(o) => match &o.content {
                ClientMessageContentV0::ClientResponse(r) => Some(r.id()),
                ClientMessageContentV0::ClientRequest(r) => Some(r.id()),
                ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => None,
            },
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ClientMessage::V0(o) => match &mut o.content {
                ClientMessageContentV0::ClientResponse(ref mut r) => r.set_id(id),
                ClientMessageContentV0::ClientRequest(ref mut r) => r.set_id(id),
                ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => {
                    panic!("it is an event")
                }
            },
        }
    }

    pub fn block<'a>(&self) -> Option<&Block> {
        match self {
            ClientMessage::V0(o) => match &o.content {
                ClientMessageContentV0::ClientResponse(r) => r.block(),
                ClientMessageContentV0::ClientRequest(_)
                | ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => {
                    panic!("it is not a response");
                }
            },
        }
    }

    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            ClientMessage::V0(o) => match &o.content {
                ClientMessageContentV0::ClientRequest(req) => req.get_actor(),
                ClientMessageContentV0::ClientResponse(_)
                | ClientMessageContentV0::ForwardedEvent(_)
                | ClientMessageContentV0::ForwardedBlock(_) => {
                    panic!("it is not a request");
                }
            },
        }
    }
}

//
// EXTERNAL REQUESTS
//

/// Request object(s) by ID from a repository by non-members
///
/// The request is sent by a non-member to an overlay member node,
/// which has a replica of the repository.
///
/// The response includes the requested objects and all their children recursively,
/// and optionally all object dependencies recursively.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExtObjectGetV0 {
    /// Repository to request the objects from
    pub repo: PubKey,

    /// List of Object IDs to request, including their children
    pub ids: Vec<ObjectId>,

    /// Whether or not to include all children recursively
    pub include_children: bool,

    /// Expiry time after which the link becomes invalid
    pub expiry: Option<Timestamp>,
}

/// Request object(s) by ID from a repository by non-members
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ExtObjectGet {
    V0(ExtObjectGetV0),
}

/// Topic synchronization request
pub type ExtTopicSyncReq = TopicSyncReq;

/// Content of ExtRequestV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ExtRequestContentV0 {
    ExtObjectGet(ExtObjectGet),
    ExtTopicSyncReq(ExtTopicSyncReq),
    // TODO inbox requests
    // TODO subreq ?
}

/// External request with its request ID
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExtRequestV0 {
    /// outer overlayId
    pub overlay: Digest,

    /// Request ID
    pub id: i64,

    /// Request content
    pub content: ExtRequestContentV0,
}

/// External request are made by clients directly to a core broker of their choice.
///
/// They differ from OuterOverlayRequests in the sense that the broker where the client is attached, is not involved in the request.
/// It is a direct connection that is established between the client and the core broker that will give the response.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ExtRequest {
    V0(ExtRequestV0),
}

impl ExtRequest {
    pub fn id(&self) -> i64 {
        match self {
            ExtRequest::V0(v0) => v0.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ExtRequest::V0(v0) => {
                v0.id = id;
            }
        }
    }
}

/// Content of ExtResponseV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ExtResponseContentV0 {
    Block(Block),
    // TODO  inbox related replies
    // TODO event ?
}

/// Response to an ExtRequest
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExtResponseV0 {
    /// Request ID
    pub id: i64,

    /// Result code
    pub result: u16,

    /// Response content
    pub content: Option<ExtResponseContentV0>,
}

/// Response to an ExtRequest
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ExtResponse {
    V0(ExtResponseV0),
}

impl ExtResponse {
    pub fn id(&self) -> i64 {
        match self {
            ExtResponse::V0(v0) => v0.id,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ExtResponse::V0(v0) => {
                v0.id = id;
            }
        }
    }
}

impl TryFrom<ProtocolMessage> for ExtResponse {
    type Error = ProtocolError;
    fn try_from(msg: ProtocolMessage) -> Result<Self, Self::Error> {
        if let ProtocolMessage::ExtResponse(ext_res) = msg {
            Ok(ext_res)
        } else {
            Err(ProtocolError::InvalidValue)
        }
    }
}

//
// PROTOCOL MESSAGES
//
#[doc(hidden)]
pub static MAGIC_NG_REQUEST: [u8; 2] = [78u8, 71u8];
#[doc(hidden)]
pub static MAGIC_NG_RESPONSE: [u8; 4] = [89u8, 88u8, 78u8, 75u8];

#[derive(Clone, Debug)]
pub enum Authorization {
    Discover,
    ExtMessage,
    Core,
    Client((PubKey, Option<Option<[u8; 32]>>)),
    OverlayJoin(PubKey),
    Admin(PubKey),
}

/// ProbeResponse
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProbeResponse {
    /// Response Magic number
    #[serde(with = "serde_bytes")]
    pub magic: Vec<u8>,

    /// Used for discovery of broker on private LAN
    /// see ListenerV0.discoverable
    pub peer_id: Option<PubKey>,
}

/// RelayRequest
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RelayRequest {
    /// The BindAddress of the broker to relay to should be of the same IP family than the TunnelRequest.remote_addr
    pub address: BindAddress,
}

/// RelayResponse
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RelayResponse {
    /// Response Magic number
    #[serde(with = "serde_bytes")]
    pub magic: Vec<u8>,

    /// result to the relay request (accept, refuse)
    pub result: u16,
}

/// Tunnel Request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TunnelRequest {
    /// Request Magic number
    #[serde(with = "serde_bytes")]
    pub magic: Vec<u8>,

    // Bind address of client as connected to the relaying broker.
    pub remote_addr: BindAddress,
}

/// Tunnel Response
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TunnelResponse {
    /// Response Magic number
    #[serde(with = "serde_bytes")]
    pub magic: Vec<u8>,

    /// result to the tunnel request (accept, refuse)
    pub result: u16,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ProtocolMessage {
    Probe([u8; 2]),
    ProbeResponse(ProbeResponse),
    Relay(RelayRequest),
    RelayResponse(RelayResponse),
    Tunnel(TunnelRequest),
    TunnelResponse(TunnelResponse),
    Noise(Noise),
    Start(StartProtocol),
    ServerHello(ServerHello),
    ClientAuth(ClientAuth),
    AuthResult(AuthResult),
    ExtRequest(ExtRequest),
    ExtResponse(ExtResponse),
    //AdminRequest(AdminRequest),
    AdminResponse(AdminResponse),
    ClientMessage(ClientMessage),
    AppMessage(AppMessage),
    CoreMessage(CoreMessage),
}

impl TryFrom<&ProtocolMessage> for ServerError {
    type Error = NgError;
    fn try_from(msg: &ProtocolMessage) -> Result<Self, NgError> {
        if let ProtocolMessage::ClientMessage(ref bm) = msg {
            let res = bm.result();
            if res != 0 {
                return Ok(ServerError::try_from(res).unwrap());
            }
        }
        if let ProtocolMessage::AppMessage(ref bm) = msg {
            let res = bm.result();
            if res != 0 {
                return Ok(ServerError::try_from(res).unwrap());
            }
        }
        Err(NgError::NotAServerError)
    }
}

impl ProtocolMessage {
    pub fn id(&self) -> Option<i64> {
        match self {
            ProtocolMessage::ExtRequest(ext_req) => Some(ext_req.id()),
            ProtocolMessage::ExtResponse(ext_res) => Some(ext_res.id()),
            ProtocolMessage::ClientMessage(client_msg) => client_msg.id(),
            ProtocolMessage::AppMessage(app_msg) => app_msg.id(),
            _ => None,
        }
    }
    pub fn set_id(&mut self, id: i64) {
        match self {
            ProtocolMessage::ExtRequest(ext_req) => ext_req.set_id(id),
            ProtocolMessage::ExtResponse(ext_res) => ext_res.set_id(id),
            ProtocolMessage::ClientMessage(client_msg) => client_msg.set_id(id),
            ProtocolMessage::AppMessage(app_msg) => app_msg.set_id(id),
            _ => panic!("cannot set ID"),
        }
    }
    pub fn type_id(&self) -> TypeId {
        match self {
            ProtocolMessage::Noise(a) => a.type_id(),
            ProtocolMessage::Start(a) => a.type_id(),
            ProtocolMessage::ServerHello(a) => a.type_id(),
            ProtocolMessage::ClientAuth(a) => a.type_id(),
            ProtocolMessage::AuthResult(a) => a.type_id(),
            ProtocolMessage::ExtRequest(a) => a.type_id(),
            ProtocolMessage::ExtResponse(a) => a.type_id(),
            ProtocolMessage::ClientMessage(a) => a.type_id(),
            ProtocolMessage::CoreMessage(a) => a.type_id(),
            ProtocolMessage::AppMessage(a) => a.type_id(),
            //ProtocolMessage::AdminRequest(a) => a.type_id(),
            ProtocolMessage::AdminResponse(a) => a.type_id(),
            ProtocolMessage::Probe(a) => a.type_id(),
            ProtocolMessage::ProbeResponse(a) => a.type_id(),
            ProtocolMessage::Relay(a) => a.type_id(),
            ProtocolMessage::RelayResponse(a) => a.type_id(),
            ProtocolMessage::Tunnel(a) => a.type_id(),
            ProtocolMessage::TunnelResponse(a) => a.type_id(),
        }
    }

    pub(crate) fn is_streamable(&self) -> Option<&dyn IStreamable> {
        match self {
            ProtocolMessage::ClientMessage(s) => Some(s as &dyn IStreamable),
            ProtocolMessage::AppMessage(s) => Some(s as &dyn IStreamable),
            // ProtocolMessage::ServerHello(a) => a.get_actor(),
            // ProtocolMessage::ClientAuth(a) => a.get_actor(),
            // ProtocolMessage::AuthResult(a) => a.get_actor(),
            // ProtocolMessage::ExtRequest(a) => a.get_actor(),
            // ProtocolMessage::ExtResponse(a) => a.get_actor(),
            // ProtocolMessage::BrokerMessage(a) => a.get_actor(),
            _ => None,
        }
    }

    pub fn get_actor(&self) -> Box<dyn EActor> {
        match self {
            //ProtocolMessage::Noise(a) => a.get_actor(),
            ProtocolMessage::Start(a) => a.get_actor(),
            ProtocolMessage::ClientMessage(a) => a.get_actor(),
            ProtocolMessage::AppMessage(a) => a.get_actor(),
            // ProtocolMessage::ServerHello(a) => a.get_actor(),
            // ProtocolMessage::ClientAuth(a) => a.get_actor(),
            // ProtocolMessage::AuthResult(a) => a.get_actor(),
            // ProtocolMessage::ExtRequest(a) => a.get_actor(),
            // ProtocolMessage::ExtResponse(a) => a.get_actor(),
            // ProtocolMessage::BrokerMessage(a) => a.get_actor(),
            _ => unimplemented!(),
        }
    }

    pub fn from_client_response_err(err: ServerError) -> ProtocolMessage {
        let res: ClientResponse = err.into();
        res.into()
    }

    pub fn from_client_request_v0(
        req: ClientRequestContentV0,
        overlay: OverlayId,
    ) -> ProtocolMessage {
        ProtocolMessage::ClientMessage(ClientMessage::V0(ClientMessageV0 {
            overlay,
            content: ClientMessageContentV0::ClientRequest(ClientRequest::V0(ClientRequestV0 {
                id: 0,
                content: req,
            })),
            padding: vec![],
        }))
    }

    pub fn is_block(&self) -> bool {
        match self {
            ProtocolMessage::ClientMessage(ClientMessage::V0(ClientMessageV0 {
                content: c,
                ..
            })) => c.is_block(),
            _ => false,
        }
    }
}

impl From<ClientResponseContentV0> for ClientResponse {
    fn from(msg: ClientResponseContentV0) -> ClientResponse {
        ClientResponse::V0(ClientResponseV0 {
            id: 0,
            result: 0,
            content: msg,
        })
    }
}

impl From<ClientResponseContentV0> for ProtocolMessage {
    fn from(msg: ClientResponseContentV0) -> ProtocolMessage {
        let client_res = ClientResponse::V0(ClientResponseV0 {
            id: 0,
            result: 0,
            content: msg,
        });
        client_res.into()
    }
}

impl From<ClientResponse> for ProtocolMessage {
    fn from(msg: ClientResponse) -> ProtocolMessage {
        ProtocolMessage::ClientMessage(ClientMessage::V0(ClientMessageV0 {
            overlay: OverlayId::nil(),
            content: ClientMessageContentV0::ClientResponse(msg),
            padding: vec![],
        }))
    }
}

//
// AUTHENTICATION MESSAGES
//

/// Content of ClientAuthV0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientAuthContentV0 {
    /// User pub key
    pub user: PubKey,

    /// Client pub key
    pub client: PubKey,

    pub info: ClientInfoV0,

    pub registration: Option<Option<[u8; 32]>>,

    /// Nonce from ServerHello
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
}

/// Client authentication
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientAuthV0 {
    /// Authentication data
    pub content: ClientAuthContentV0,

    /// Signature by user key
    pub sig: Sig,

    /// Signature by client key
    pub client_sig: Sig,
}

/// Client authentication
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientAuth {
    V0(ClientAuthV0),
}

impl ClientAuth {
    pub fn content_v0(&self) -> ClientAuthContentV0 {
        match self {
            ClientAuth::V0(o) => o.content.clone(),
        }
    }
    pub fn sig(&self) -> Sig {
        match self {
            ClientAuth::V0(o) => o.sig,
        }
    }
    pub fn user(&self) -> PubKey {
        match self {
            ClientAuth::V0(o) => o.content.user,
        }
    }
    pub fn client(&self) -> PubKey {
        match self {
            ClientAuth::V0(o) => o.content.client,
        }
    }
    pub fn nonce(&self) -> &Vec<u8> {
        match self {
            ClientAuth::V0(o) => &o.content.nonce,
        }
    }
    pub fn registration(&self) -> Option<Option<[u8; 32]>> {
        match self {
            ClientAuth::V0(o) => o.content.registration,
        }
    }
}

impl From<ClientAuth> for ProtocolMessage {
    fn from(msg: ClientAuth) -> ProtocolMessage {
        ProtocolMessage::ClientAuth(msg)
    }
}

/// Authentication result
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthResultV0 {
    pub result: u16,
    #[serde(with = "serde_bytes")]
    pub metadata: Vec<u8>,
}

/// Authentication result
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AuthResult {
    V0(AuthResultV0),
}

impl AuthResult {
    pub fn result(&self) -> u16 {
        match self {
            AuthResult::V0(o) => o.result,
        }
    }
    pub fn metadata(&self) -> &Vec<u8> {
        match self {
            AuthResult::V0(o) => &o.metadata,
        }
    }
}

impl From<AuthResult> for ProtocolMessage {
    fn from(msg: AuthResult) -> ProtocolMessage {
        ProtocolMessage::AuthResult(msg)
    }
}

//
// LINKS
//

/// Link to a repository
///
/// Consists of an identifier (repoid), a ReadCap or WriteCap, and a locator (peers and overlayLink)
/// Those capabilities are not durable: They can be refreshed by the members and previously shared Caps will become obsolete/revoked.
/// As long as the user is a member of the repo and subscribes to the root topic (of the repo, and of the store if needed/applicable), they will receive the updated capabilities.
/// But if they don't subscribe, they will lose access after the refresh.
/// For durable capabilities, see PermaCap.
/// In most cases, the link is shared and then the recipient opens it and subscribes soon afterward, so there is no need for a PermaCap
/// Perma capabilities are needed only when the link is stored on disk and kept there unopened for a long period.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepoLinkV0 {
    /// Repository ID
    pub id: RepoId,

    /// read capability for the whole repo
    /// current (at the time of sharing the link) root branch definition commit
    pub read_cap: ReadCap,

    /// Write capability secret. Only set for editors. in this case, overlay MUST be set to an InnerOverlay
    // pub write_cap_secret: Option<RepoWriteCapSecret>,

    /// Current overlay link, used to join the overlay
    pub overlay: OverlayLink,

    /// Peer brokers to connect to
    pub peers: Vec<PeerAdvert>,
}

/// Link to a repository
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RepoLink {
    V0(RepoLinkV0),
}

impl RepoLink {
    pub fn id(&self) -> &RepoId {
        match self {
            RepoLink::V0(o) => &o.id,
        }
    }
    pub fn peers(&self) -> &Vec<PeerAdvert> {
        match self {
            RepoLink::V0(o) => &o.peers,
        }
    }
}

/// Link for a Public Repo
///
/// The latest ReadCap of the branch (or main branch) will be downloaded from the outerOverlay, if the peer brokers listed below allow it.
/// The snapshot can be downloaded instead
/// This link is durable, because the public site are served differently by brokers.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PublicRepoLinkV0 {
    /// Repository ID
    pub repo: RepoId,

    /// optional branchId to access. a specific public branch,
    /// if not set, the main branch of the repo will be used.
    pub branch: Option<BranchId>,

    /// optional commits of head to access.
    /// if not set, the main branch of the repo will be used.
    pub heads: Vec<ObjectRef>,

    /// optional snapshot to download, in order to display the content quicker to end-user.
    pub snapshot: Option<ObjectRef>,

    /// The public site store
    pub public_store: PubKey,

    /// Peer brokers to connect to
    pub peers: Vec<PeerAdvert>,
}

/// Link to a public repository
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PublicRepoLink {
    V0(PublicRepoLinkV0),
}

/// Read access to a branch of a Public, Protected or Group store.
///
/// The overlay to join can be the outer or the inner, depending on what was offered in the link.
/// The difference between the two is that in the outer overlay, only one broker is contacted.
/// In the inner overlay, all the publisher's brokers are contacted, so subscription to the pub/sub is more reliable, less prone to outage.
/// This is not a durable link. If the topic has been refreshed, the pubsub won't be able to be subscribed to,
/// but TopicSyncReq will still work (answering the commits up until the moment the topic was refreshed)
/// and the optional heads will always be retrievable
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReadBranchLinkV0 {
    /// Repository ID
    pub repo: RepoId,

    pub branch: BranchId, // must match the one in read_cap

    pub topic: TopicId,

    /// an optional list of heads that can be fetched in this branch
    /// useful if a specific head is to be shared
    pub heads: Vec<ObjectRef>,

    /// read capability for the branch
    /// current (at the time of sharing the link) branch definition commit
    pub read_cap: ReadCap,

    /// Current overlay link, used to join the overlay, most of the time, an outerOverlay is preferred
    pub overlay: OverlayLink,

    /// Peer brokers to connect to
    pub peers: Vec<PeerAdvert>,
}

/// Link to a repository
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ReadBranchLink {
    V0(ReadBranchLinkV0),
}

/// Obtains one or more objects of a repo (Commit, File) by their ID.
///
/// On an outerOverlay, the header is always emptied (no way to reconstruct the DAG of commits) except on public overlays or if a topicId is provided
/// If the intent is to share a whole DAG of commits at a definite CommitID/HEAD, then ReadBranchLink should be used instead (or PublicRepoLink if public site)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ObjectLinkV0 {
    /// Repository ID: not used to make the request. but useful for commits, to know which repo they are from without needing to fetch and open the full DAG of commits.
    /// (but the one here might be wrong. only when opening the DAG can the real repo be known. also note that on outerOverlay of non public stores, the DAG is not accessible)
    /// note that it could be omitted, specially if the objects are files. As files are content-addressable and belong to an overlay but not to a specific repo or topic.
    pub repo: Option<RepoId>,

    /// An optional topic that will be used to retrieve the Certificate of a commit, if needed
    /// (topic has to be checked with the one inside the commit. the one here might be wrong. it is provided here as an optimization)
    /// or can be used to help with BlockSearchTopic.
    /// If the topic is provided, a TopicSyncReq can be performed, and the causal past of the commit will appear (by repeated tries while narrowing down on the ancestors),
    /// hence defeating the "emptied header" protection
    pub topic: Option<TopicId>,

    pub objects: Vec<ObjectRef>,

    /// Overlay to join
    pub overlay: OverlayLink,

    /// Peer brokers to connect to
    pub peers: Vec<PeerAdvert>,
}

/// Link to a specific commit, without its causal past
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ObjectLink {
    V0(ObjectLinkV0),
}

/// NextGraph Link V0
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum NgLinkV0 {
    Repo(RepoLink),
    PublicRepo(PublicRepoLink),
    Branch(ReadBranchLink),
    Object(ObjectLink),
}

/// NextGraph Link
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum NgLink {
    V0(NgLinkV0),
}

// TODO: PermaLinks and PostInbox (and ExtRequests)

#[cfg(test)]
mod test {

    use crate::types::{BootstrapContentV0, BrokerServerTypeV0, BrokerServerV0, Invitation};
    use ng_repo::types::PubKey;

    #[test]
    pub fn invitation() {
        let inv = Invitation::new_v0(
            BootstrapContentV0 {
                servers: vec![BrokerServerV0 {
                    server_type: BrokerServerTypeV0::Localhost(14400),
                    can_verify: false,
                    can_forward: false,
                    peer_id: PubKey::Ed25519PubKey([
                        95, 73, 225, 250, 3, 147, 24, 164, 177, 211, 34, 244, 45, 130, 111, 136,
                        229, 145, 53, 167, 50, 168, 140, 227, 65, 111, 203, 41, 210, 186, 162, 149,
                    ]),
                }],
            },
            Some("test invitation".to_string()),
            None,
        );

        println!("{:?}", inv.get_urls());
    }
}