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
|
//! `continuum-party`: a party's client of a federation (`docs/federation.md`). It signs its
//! party's events with one of its keys (`--key`: an OpenSSH private key file, or a public
//! key the ssh-agent at `SSH_AUTH_SOCK` holds, given itself or in a file), puts them
//! through a node's API (`--node`, its user and password in the URL, or `--token`; with
//! neither, as its party, logging in there by that key: `Node::log_in`), and keeps its
//! party's record (`--record`, `client::Record`), by which it votes, written before a vote
//! is sent; without one, `--party` names the party it reads as. Its options may be set in
//! configuration files as the node's are (`--config`, `config::PARTY_OPTIONS`): the same
//! format, imports and all.
//!
//! * `init PARTY`: begins a record of `PARTY`, on the version current now; with `--root
//! FILE`, from the file the store's swarm starts from, for a party that never voted in
//! it: the record casts on every version, the first too;
//! * `write PATH VALUE`: writes `VALUE` (JSON) at `PATH`;
//! * `keys`, `nodes`: the party's key set (`authorized_keys` lines, each one argument, or
//! files of them, their comments left out) or node list (node IDs) as it counts at the
//! node, one a line (`--list`); or written: with `--add` and `--remove`, the set or list
//! as it counts, changed; with `--set`, set whole. One left empty is written with
//! `--force` only;
//! * `next`: the version after the current one, to change and propose: the current one
//! numbered on, naming its hash, without its checkpoint (JSON), to standard output;
//! * `propose FILE`: proposes the version `FILE` holds (JSON), where a party may back it
//! (`client::backable`), saying first what it does and asking on a terminal, and says
//! the proposal's hash; with `--yes`, votes `true` on it too, as `vote` does; with
//! `--print`, writes the version to standard output instead. `propose admit`, `remove`,
//! `give`, `take`, `keys`, `nodes`, `checkpoint` and `revision` propose the next
//! version changed as they say (`Intent`), likewise;
//! * `vote PROPOSAL yes|no`: votes on the proposal of hash `PROPOSAL` on the current
//! version, by the record; with `--through`, through the node that votes for the
//! party by itself and keeps its record, as such a party votes by hand;
//! * `again`: signs again what a move refused;
//! * `restore`: takes the party's votes on the current version, as the node holds them,
//! into its record, or a new one (`Record::restore`), best effort;
//! * `twice RECORD...`: names, from the records of parties' clients, a party that voted
//! twice;
//! * `proposals`: the proposals on the current version at the node, each with whether it
//! passed or is dead, who voted what, and what its version changes (`client::changes`);
//! * `status`: the store, its version and parties, the party's keys and nodes, the node,
//! the proposals, the versions the node refused of its own, what to sign again;
//! * `values [PATH]`: the values that count, all or under `PATH`, with who writes there;
//! * `get [PATH]`: what counts at `PATH` as one JSON value (`tree`): a place's, or what lies
//! under it, places and the values within theirs; with `-r`, a string as it is;
//! * `found PARTY=KEY|FILE...`: the first version of a federation, from its parties' keys,
//! node lists (`--nodes`) and rules (`--rule`), to standard output;
//! * `root FILE`: the root of the federation whose first version `FILE` holds (JSON),
//! the file its founders start its swarm from (`--store-root`), to standard output;
//! * `fork FILE [HEAD...]`: the root of the fork at the heads named (those the node shows,
//! where none are) by the version `FILE` holds, as the node builds it, with the events
//! it keeps: the file the fork's founders start its swarm from, to standard output.
//! `fork proposal PROPOSAL` forks by the version a proposal proposes, and `fork admit`,
//! `remove`, `give`, `take`, `keys`, `nodes` and `revision` by the next version changed
//! as they say, as `propose` does; at the heads `--at` names, `--founder PARTY=NODE,…`
//! naming a party's node list anew in the fork;
//! * `check FILE`: what the node finds of the fork whose root `FILE` holds: whether it
//! builds it, what it holds that its heads lack, and the parties whose keys it gives
//! otherwise.
//!
//! Votes, proposals, key sets and node lists are signed with a key the current version
//! names for the party, which the client checks first (`Signer::named_by`): where its key
//! isn't one, only a version naming the party's keys or list anew changes them.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow, bail};
use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command};
use ed25519_dalek::SigningKey;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use super::client::{self, Record};
use super::event::{self, Does, Event, Signed};
use super::fold::Federation;
use super::jcs::Json;
use super::judge;
use super::keys::{self, Key};
use super::revision::{FEATURES, Revision};
use super::store::Id;
use super::store::memory::Store;
use super::version::Version;
use crate::access::sshsig::PublicKey;
use crate::config;
/// The client's options (`config::PARTY_OPTIONS`), as the command line and configuration
/// files set them.
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct Options {
#[serde(default = "default_node")]
node: String,
token: Option<String>,
key: Option<String>,
record: Option<String>,
party: Option<String>,
}
fn default_node() -> String {
"http://localhost:3000".to_owned()
}
fn command() -> Command {
let id = |name: &'static str| Arg::new(name).required(true);
let command = Command::new("continuum-party")
.version(env!("CARGO_PKG_VERSION"))
.long_version(crate::release::described())
.about("A party's client of a federation: signs its events, and votes by its record");
config::with_options(command, config::PARTY_OPTIONS)
.arg(
Arg::new("federation")
.long("federation")
.value_name("NAME")
.help(
"The federation to work with, by the name of its directory in \
~/.config/continuum/federations: its party.toml, record and key. Where \
there is one, and no --config, that one",
),
)
.subcommand_required(true)
.subcommand(
Command::new("init")
.about("Begins a record")
.arg(id("party"))
.arg(
Arg::new("root")
.long("root")
.value_name("FILE")
.help("From the file the store's swarm starts from, for a party that never voted in it"),
),
)
.subcommand(
Command::new("write")
.about("Writes a value (JSON) at a path")
.arg(id("path"))
.arg(id("value")),
)
.subcommand(
Command::new("keys")
.about(
"The party's key set as it counts at the node, or written with keys added, \
taken off, or set whole",
)
.args(changing("KEY|FILE", "keys", "key set"))
.group(changes()),
)
.subcommand(
Command::new("nodes")
.about(
"The party's node list as it counts at the node, or written with nodes \
added, taken off, or set whole",
)
.args(changing("NODE", "nodes", "node list"))
.group(changes()),
)
.subcommand(
Command::new("next")
.about(
"The version after the current one, to change and propose: numbered on, \
naming the current one's hash, without its checkpoint",
)
.arg(
Arg::new("revision")
.long("revision")
.value_name("FEATURE")
.help(
"Following the revision that adds FEATURE (federation.md, Changing \
the federation): pass it once every party's nodes run a continuum \
that knows it",
),
),
)
.subcommand(
Command::new("propose")
.about(
"Proposes a version, saying what it does and asking first on a terminal: the \
version a file holds (JSON), or the next one changed as a subcommand says",
)
.arg(id("file").help("A file holding the version (JSON)"))
.args(proposing())
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true)
.subcommands(intents().into_iter().map(|intent| intent.args(proposing()))),
)
.subcommand(
Command::new("vote")
.about("Votes on a proposal on the current version, by its hash")
.arg(id("proposal"))
.arg(Arg::new("yes").required(true).value_parser(["yes", "no"]))
.arg(
Arg::new("through")
.long("through")
.action(ArgAction::SetTrue)
.help("Through the node, which votes for the party and keeps its record"),
)
.arg(waiting()),
)
.subcommand(Command::new("again").about("Signs again what a move refused"))
.subcommand(Command::new("restore").about(
"Takes into the party's record, or a new one, its votes on the current version as \
the node holds them: best effort, as one on its way from elsewhere isn't among them",
))
.subcommand(
Command::new("found")
.about(
"The first version of a federation (JSON), to standard output, from its \
parties' keys, node lists and rules: what root makes the root of",
)
.arg(
Arg::new("parties")
.value_name("PARTY=KEY|FILE")
.num_args(1..)
.required(true)
.action(ArgAction::Append)
.help(
"A party and its keys: an authorized_keys line, one argument, or a \
file of them; again for more keys of it",
),
)
.arg(
Arg::new("nodes")
.long("nodes")
.value_name("PARTY=NODE,…")
.action(ArgAction::Append)
.help("A party's node list, by node IDs (continuum node-id): none where not given"),
)
.arg(
Arg::new("rule")
.long("rule")
.value_name("PATH=WRITER")
.action(ArgAction::Append)
.help(
"A rule, in order: the places PATH matches to WRITER, a party, \
{party} or nobody. Without any, each party writes under \
home/{party}/",
),
)
.arg(
Arg::new("revision")
.long("revision")
.value_name("FEATURE")
.help("Following the revision that adds FEATURE, as next --revision"),
),
)
.subcommand(
Command::new("root")
.about("The root of the federation whose first version a file holds (JSON)")
.arg(id("file")),
)
.subcommand(
Command::new("fork")
.about(
"The root of a fork, as the node builds it, to standard output: at the \
heads the node shows, or those named; by the version a file holds (JSON), \
a proposal's, or the next one changed as a subcommand says",
)
.arg(id("file").help("A file holding the fork's version (JSON)"))
.arg(
Arg::new("heads")
.num_args(1..)
.help("The heads it forks at, by ID or prefix: those the node shows where none are"),
)
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true)
.subcommand(
Command::new("proposal")
.about("By the version a proposal on the current version proposes")
.arg(id("proposal")),
)
.subcommands(
intents()
.into_iter()
.filter(|intent| intent.get_name() != "checkpoint"),
)
.mut_subcommands(|intent| intent.args(forking())),
)
.subcommand(
Command::new("check")
.about("What the node finds of the fork whose root a file holds")
.arg(id("file")),
)
.subcommand(Command::new("judge").about(
"What a store makes of the histories its input spells, in a format every release \
keeps (federation-tests.md, Against released revisions)",
))
.subcommand(Command::new("proposals").about(
"The proposals on the current version, each as show says it",
))
.subcommand(Command::new("status").about(
"The store, its version and parties, the party's keys and nodes, the node, the \
proposals on the current version, and what the party has to sign again",
))
.subcommand(
Command::new("get")
.about(
"What counts at a path, as JSON: a place's value, or what lies under it, \
places and the values within theirs, as one object; all without a path",
)
.arg(Arg::new("path").help("Segments by slashes (home/tv/motd); a list's items by their index"))
.arg(
Arg::new("raw")
.short('r')
.long("raw")
.action(ArgAction::SetTrue)
.help("A string as it is, not as JSON, as jq -r prints one"),
),
)
.subcommand(
Command::new("values")
.about("The values that count, each with who writes there: all, or under a path")
.arg(Arg::new("path").help("The place, and those under it"))
.arg(
Arg::new("json")
.long("json")
.action(ArgAction::SetTrue)
.help("As one JSON object, by place"),
),
)
.subcommand(
Command::new("show")
.about(
"What a proposal on the current version does, in words, before a vote: \
who voted what, the parties, keys, nodes and rules it changes, who writes \
where after it",
)
.arg(id("proposal")),
)
.subcommand(
Command::new("twice")
.about("Names, from records, a party that voted twice")
.arg(
Arg::new("records")
.num_args(1..)
.required(true)
.action(ArgAction::Append),
),
)
}
/// How long a vote waits before it is cast, and asks the node again whether another of
/// its party's came meanwhile (`vote`).
fn waiting() -> Arg {
Arg::new("wait")
.long("wait")
.value_name("SECONDS")
.default_value("5")
.value_parser(clap::value_parser!(u64))
.help(
"Before casting, waits so long and asks the node again for its party's votes, so \
that one cast elsewhere just before arrives first",
)
}
/// `propose`'s own options, and each of its subcommands'.
fn proposing() -> [Arg; 3] {
[
waiting(),
Arg::new("yes")
.long("yes")
.action(ArgAction::SetTrue)
.help("Votes true on it too, by the record, as vote does"),
Arg::new("print")
.long("print")
.action(ArgAction::SetTrue)
.help("Writes the version to standard output (JSON) instead, to change and propose"),
]
}
/// The options of `fork`'s subcommands: the heads, and the founders' node lists.
fn forking() -> [Arg; 2] {
[
Arg::new("at")
.long("at")
.value_name("HEAD")
.num_args(1..)
.action(ArgAction::Append)
.help("The heads it forks at, by ID or prefix: those the node shows where none are"),
Arg::new("founder")
.long("founder")
.value_name("PARTY=NODE,…")
.action(ArgAction::Append)
.help(
"Names the party's node list anew in the fork, so that these nodes are members \
there: a founder's, its nodes there",
),
]
}
/// The changes `propose` makes by what they are for (`Intent`), a subcommand each; `fork`
/// takes them too, but `checkpoint`.
fn intents() -> Vec<Command> {
let required = |name: &'static str| Arg::new(name).required(true);
let keys = || {
Arg::new("keys")
.value_name("KEY|FILE")
.num_args(1..)
.action(ArgAction::Append)
.help("Keys, each an authorized_keys line, one argument, or a file of such lines")
};
let nodes = || {
Arg::new("nodes")
.value_name("NODE")
.num_args(0..)
.action(ArgAction::Append)
.help("Node IDs (continuum:…), as `continuum node-id` says them")
};
vec![
Command::new("admit")
.about("Lets a party in, naming its keys and its node list")
.arg(required("party"))
.arg(keys().long("keys").required(true))
.arg(nodes().long("nodes")),
Command::new("remove")
.about("Takes a party out, with the rules giving it places")
.arg(required("party")),
Command::new("give")
.about(
"Gives the places a path matches to a party, or each to the party it names \
({party}), by a rule before every other",
)
.arg(required("path"))
.arg(required("writer").value_name("PARTY|{party}")),
Command::new("take")
.about(
"Gives the places a path matches to nobody: its rule goes, and another \
still giving one of them is overruled",
)
.arg(required("path")),
Command::new("keys")
.about("Names a party's keys anew: every key set it wrote before counts no more")
.arg(required("party"))
.arg(keys().required(true)),
Command::new("nodes")
.about("Names a party's node list anew: every node list it wrote before counts no more")
.arg(required("party"))
.arg(nodes()),
Command::new("checkpoint")
.about("Moves the store to a checkpoint at the heads the node shows"),
Command::new("revision")
.about(
"Follows the revision that adds a feature (federation.md, Changing the \
federation): once every party's nodes run a continuum that knows it",
)
.arg(required("feature")),
]
}
/// What lists or changes the party's key set or node list (`whole`), of `items` named
/// `value`: `--list`, as it counts, what the command does given none of the others;
/// `--add` and `--remove`, changing it as it counts; `--set`, setting it whole; `--force`,
/// writing it empty.
fn changing(value: &'static str, items: &str, whole: &str) -> [Arg; 5] {
[
Arg::new("list")
.long("list")
.action(ArgAction::SetTrue)
.conflicts_with("changes")
.help(format!(
"Shows the party's {whole} as it counts at the node, one a line: what the \
command does given nothing"
)),
Arg::new("add")
.long("add")
.value_name(value)
.num_args(1..)
.action(ArgAction::Append)
.help(format!(
"Adds these {items} to the party's {whole}, as it counts at the node"
)),
Arg::new("remove")
.long("remove")
.value_name(value)
.num_args(1..)
.action(ArgAction::Append)
.help(format!(
"Takes these {items} off the party's {whole}, as it counts at the node"
)),
Arg::new("set")
.long("set")
.value_name(value)
.num_args(0..)
.action(ArgAction::Append)
.conflicts_with_all(["add", "remove"])
.help(format!("Sets the party's {whole} to these {items}, whole")),
Arg::new("force")
.long("force")
.action(ArgAction::SetTrue)
.requires("changes")
.help(format!(
"Writes the party's {whole} where the change leaves it empty"
)),
]
}
/// What changes a key set or node list: `--add`, `--remove`, `--set`.
fn changes() -> ArgGroup {
ArgGroup::new("changes")
.args(["add", "remove", "set"])
.multiple(true)
}
/// Where the client keeps a directory for each federation, by its name: `continuum/
/// federations` in `$XDG_CONFIG_HOME`, else in `~/.config`.
fn federations() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME")
.filter(|dir| !dir.is_empty())
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
Some(base.join("continuum").join("federations"))
}
/// The directory of the federation the client works with: the one `--federation` names;
/// else, without `--config`, the only one in `all` (`federations`). None where there is
/// none, and an error where there are several.
fn federation(matches: &ArgMatches, all: Option<&Path>) -> Result<Option<PathBuf>> {
if let Some(name) = matches.get_one::<String>("federation") {
if name.is_empty() || name.contains('/') || name == "." || name == ".." {
bail!("--federation {name:?}: a federation is named by one segment of a path");
}
let all = all.context("no directory for federations: set HOME or XDG_CONFIG_HOME")?;
return Ok(Some(all.join(name)));
}
let Some(all) = all else {
return Ok(None);
};
if matches.get_many::<String>("config").is_some() || !all.is_dir() {
return Ok(None);
}
let mut names: Vec<String> = std::fs::read_dir(all)
.with_context(|| format!("Reading {}", all.display()))?
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().is_dir())
.filter_map(|entry| entry.file_name().into_string().ok())
.collect();
names.sort();
match names.as_slice() {
[] => Ok(None),
[one] => Ok(Some(all.join(one))),
several => bail!(
"{} federations in {} ({}): choose one with --federation",
several.len(),
all.display(),
several.join(", ")
),
}
}
/// A federation's directory begun by `init`: made, only its owner reading it, with a
/// `party.toml` holding the options given on the command line, `node`, `token` and `key`,
/// the key's path made absolute.
fn begin_federation(dir: &Path, matches: &ArgMatches) -> Result<()> {
use clap::parser::ValueSource;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)
.with_context(|| format!("Making {}", dir.display()))?;
let mut given = toml::Table::new();
for name in ["node", "token", "key"] {
if matches.value_source(name) != Some(ValueSource::CommandLine) {
continue;
}
let Some(value) = matches.get_one::<String>(name) else {
continue;
};
let value = if name == "key" && Path::new(value).exists() {
std::path::absolute(value)?.display().to_string()
} else {
value.clone()
};
given.insert(name.to_owned(), toml::Value::String(value));
}
let file = dir.join("party.toml");
if given.is_empty() || file.exists() {
return Ok(());
}
let mut out = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&file)
.with_context(|| format!("Writing {}", file.display()))?;
std::io::Write::write_all(&mut out, toml::to_string(&given)?.as_bytes())?;
println!("wrote {}", file.display());
Ok(())
}
/// Runs the client, as its arguments say.
pub(crate) async fn main() -> Result<()> {
let matches = command().get_matches();
let (name, sub) = matches.subcommand().expect("a subcommand is required");
// Those that use no options read no federation's.
let dir = if matches!(name, "twice" | "root" | "judge" | "found") {
None
} else {
federation(&matches, federations().as_deref())?
};
if let Some(dir) = &dir {
if name == "init" {
begin_federation(dir, &matches)?;
} else if !dir.is_dir() {
bail!(
"no federation {}: {} isn't there; `init` begins one",
dir.file_name().unwrap_or_default().to_string_lossy(),
dir.display()
);
}
}
let first: Vec<PathBuf> = dir
.iter()
.map(|dir| dir.join("party.toml"))
.filter(|file| file.exists())
.collect();
let (merged, _) = config::merged_with(&matches, config::PARTY_OPTIONS, &first)?;
let mut options: Options = config::read(&merged)?;
// In a federation's directory, its record and key, where none other is named.
if let Some(dir) = &dir {
if options.record.is_none() {
options.record = Some(dir.join("record").display().to_string());
}
if options.key.is_none() && dir.join("key").exists() {
options.key = Some(dir.join("key").display().to_string());
}
}
if name == "twice" {
let records = sub
.get_many::<String>("records")
.into_iter()
.flatten()
.map(|path| Record::load(Path::new(path)).map_err(|why| anyhow!(why)))
.collect::<Result<Vec<_>>>()?;
for (version, party, why) in client::voted_twice(&records) {
println!("{party} voted twice on version {version}: {why}");
}
return Ok(());
}
if name == "found" {
println!("{}", serde_json::to_string_pretty(&founded(sub)?)?);
return Ok(());
}
if name == "root" {
let version = version_in(sub.get_one::<String>("file").expect("required"))?;
let version = Version::read(&version).map_err(|why| anyhow!("no version: {why}"))?;
let root = event::Checkpoint {
at: Vec::new(),
keeps: Vec::new(),
version,
}
.bytes();
if let Err(refused) = Store::<Federation>::new(root.clone(), Vec::new()) {
bail!("no federation's root: {}", refused.0);
}
return out(&super::fork::root_file(&root, &[]));
}
if name == "judge" {
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input)?;
let histories = judge::read(&input).map_err(|why| anyhow!(why))?;
print!("{}", judge::judge(&histories));
return Ok(());
}
let mut node = Node::new(&options)?;
let party = working_as(name, sub, &options)?;
// Without a user of the node or a token: as the party, by its key.
if node.password.is_none()
&& node.token.is_none()
&& options.key.is_some()
&& let Some(party) = &party
{
node.log_in(party, &signing_key(&options)?).await?;
}
if name == "propose" && proposing_flags(sub).get_flag("print") {
let current = node.current().await?;
let version = to_propose(&node, ¤t, sub).await?;
let version: JsonValue = serde_json::from_slice(&version.bytes())?;
println!("{}", serde_json::to_string_pretty(&version)?);
return Ok(());
}
if name == "proposals" {
return proposals(&node).await;
}
if name == "status" {
return status(&node, &options, party.as_deref()).await;
}
if name == "values" {
return values(&node, sub).await;
}
if name == "get" {
let counts = node.counts().await?;
let path = sub
.get_one::<String>("path")
.map(|path| path.trim_matches('/'))
.unwrap_or_default();
let empty = serde_json::Map::new();
let tree = tree(counts["values"].as_object().unwrap_or(&empty), path);
let found = at(&tree, path).with_context(|| format!("nothing counts at {path}"))?;
match found {
JsonValue::String(text) if sub.get_flag("raw") => println!("{text}"),
JsonValue::Object(_) | JsonValue::Array(_) => {
println!("{}", serde_json::to_string_pretty(found)?)
}
scalar => println!("{scalar}"),
}
return Ok(());
}
if name == "show" {
let counts = node.counts().await?;
let proposal = proposal_named(&counts, sub)?.to_string();
for line in preview(&node, &counts, &proposal, &proposal_hashes(&counts)).await? {
println!("{line}");
}
return Ok(());
}
if name == "next" {
let current = node.current().await?;
let feature = sub.get_one::<String>("revision");
let next = next(¤t, feature.map(String::as_str))?;
if feature.is_none() {
// A later revision this client and the node know, said.
let known = node.revisions().await?;
if let Some(later) = Revision::known()
.filter(|revision| *revision > current.revision && known.contains(&revision.id()))
.last()
{
let name = later
.features()
.last()
.expect("a later revision adds one")
.name();
eprintln!(
"The node knows {later}, the current version follows {}: --revision {name} \
moves to it, once every party's nodes run a continuum that knows it",
current.revision
);
warn_unready(&node.counts().await?, later);
}
} else if let Some(revision) = next["revision"]
.as_str()
.and_then(Id::from_hex)
.and_then(|id| Revision::of(&id))
&& revision != current.revision
{
warn_unready(&node.counts().await?, revision);
}
println!("{}", serde_json::to_string_pretty(&next)?);
return Ok(());
}
if name == "fork" {
let (version, heads) = match sub.subcommand() {
None => (
version_in(sub.get_one::<String>("file").expect("required"))?,
strings(sub, "heads"),
),
Some(("proposal", given)) => {
let counts = node.counts().await?;
let proposal = proposal_named(&counts, given)?;
let version = proposal_version(&node, &counts, proposal).await?;
let mut version: JsonValue = serde_json::from_slice(&version.bytes())?;
founders(&mut version, given)?;
let version = client::json(&version).map_err(|why| anyhow!(why))?;
(version, strings(given, "at"))
}
Some((intent, given)) => {
let current = node.current().await?;
let mut version = intended(¤t, &intent_of(&node, intent, given).await?)?;
founders(&mut version, given)?;
let version = client::json(&version).map_err(|why| anyhow!(why))?;
(version, strings(given, "at"))
}
};
// Each head by its ID, or a prefix of one of the heads the node shows; those it
// shows, where none is named.
let (_, shown) = node.summary().await?;
let shown: Vec<String> = shown.iter().map(Id::to_string).collect();
let heads = if heads.is_empty() {
shown
} else {
let shown: Vec<&str> = shown.iter().map(String::as_str).collect();
heads
.iter()
.map(|head| {
client::named(head, &shown, "head")
.map(|id| id.to_string())
.map_err(|why| anyhow!(why))
})
.collect::<Result<Vec<String>>>()?
};
let body = serde_json::json!({
"heads": heads,
"version": serde_json::from_slice::<JsonValue>(&version.bytes())?,
});
return out(&node.post_for_bytes("/admin/events/fork", &body).await?);
}
if name == "check" {
let file = sub.get_one::<String>("file").expect("required");
let bytes = std::fs::read(file).with_context(|| format!("Reading {file}"))?;
let check = node.post_bytes("/events/fork", bytes).await?;
let fork = check["fork"].as_str().unwrap_or_default();
match (check["builds"].as_bool(), check["why"].as_str()) {
(Some(true), _) => println!("{fork}: built here, byte for byte"),
(_, Some(why)) => println!("{fork}: not built here: {why}"),
_ => println!("{fork}: not built here: another root at its heads"),
}
for id in check["lacking"].as_array().into_iter().flatten() {
println!("its heads lack {}", id.as_str().unwrap_or_default());
}
let changes: Vec<&str> = check["changes"]
.as_array()
.into_iter()
.flatten()
.filter_map(JsonValue::as_str)
.collect();
if !changes.is_empty() {
println!("its version changes:");
}
for line in changes {
println!(" {line}");
}
for line in check["writers"].as_array().into_iter().flatten() {
println!(" who writes {}", line.as_str().unwrap_or_default());
}
for (party, keys) in check["keys"].as_object().into_iter().flatten() {
println!(
"{party}'s keys: {} here, {} in the fork",
keys["there"], keys["fork"]
);
}
return Ok(());
}
// A party that has a node vote by itself votes by hand only through it.
if name == "vote" && sub.get_flag("through") {
let counts = node.counts().await?;
let proposal = proposal_named(&counts, sub)?;
let yes = sub.get_one::<String>("yes").map(String::as_str) == Some("yes");
let hashes = proposal_hashes(&counts);
for line in preview(&node, &counts, &proposal.to_string(), &hashes).await? {
println!("{line}");
}
let word = if yes { "`true`" } else { "`false`" };
let question = format!(
"Vote {word} on {}, through the node?",
marked(&proposal.to_string(), &hashes)
);
if !confirmed(&question)? {
println!("nothing cast");
return Ok(());
}
let answer = node
.post(
"/admin/events/vote",
&serde_json::json!({"proposal": proposal.to_string(), "yes": yes}),
)
.await?;
println!("{} cast", answer["id"].as_str().unwrap_or_default());
return Ok(());
}
let path = PathBuf::from(
options
.record
.as_ref()
.context("--record names the party's record")?,
);
if name == "init" {
if path.exists() {
bail!("{} holds a record already", path.display());
}
let party = sub.get_one::<String>("party").expect("required");
let record = match sub.get_one::<String>("root") {
Some(file) => {
let bytes = std::fs::read(file).with_context(|| format!("Reading {file}"))?;
let (root, kept) = super::fork::read_root_file(&bytes);
if let Err(refused) = Store::<Federation>::new(root.clone(), kept) {
bail!("no store's root: {}", refused.0);
}
Record::before(Id::of(&root), party)
}
None => {
let (store, _) = node.summary().await?;
Record::begin(store, party, &node.current().await?)
}
};
record.save(&path).map_err(|why| anyhow!(why))?;
println!("began a record of {party}, of the store {}", record.store);
return Ok(());
}
if name == "restore" {
return restore(&node, &path, party.as_deref()).await;
}
let mut record = Record::load(&path).map_err(|why| anyhow!(why))?;
// The party's key set or node list as it counts, given no change: no key needed.
if matches!(name, "keys" | "nodes") && !sub.contains_id("changes") {
for item in listed(&node.counts().await?, &record.party, name) {
println!("{item}");
}
return Ok(());
}
let key = signing_key(&options)?;
let signer = Signer {
key,
party: record.party.clone(),
};
match (name, sub) {
("write", sub) => {
let path_to = sub.get_one::<String>("path").expect("required");
let value: JsonValue =
serde_json::from_str(sub.get_one::<String>("value").expect("required"))
.context("the value isn't JSON")?;
let value = client::json(&value).map_err(|why| anyhow!(why))?;
sign(
&node,
&signer,
&mut record,
&path,
event::write(path_to, value),
)
.await
}
("keys", sub) => {
// As the federation spells a key: without the line's comment.
let spelled = |name: &str| keys_given(&strings(sub, name));
let counts = node.counts().await?;
signer.named_by(¤t(&counts)?)?;
let party = &signer.party;
let keys = changed(
listed(&counts, party, "keys"),
sub.contains_id("set").then(|| spelled("set")).transpose()?,
spelled("add")?,
spelled("remove")?,
sub.get_flag("force"),
&format!("{party}'s key set"),
&format!("none of {party}'s writes would count"),
)?;
sign(&node, &signer, &mut record, &path, event::keys(&keys)).await
}
("nodes", sub) => {
let given = |name: &str| node_ids(strings(sub, name));
let counts = node.counts().await?;
signer.named_by(¤t(&counts)?)?;
let party = &signer.party;
let nodes = changed(
listed(&counts, party, "nodes"),
sub.contains_id("set").then(|| given("set")).transpose()?,
given("add")?,
given("remove")?,
sub.get_flag("force"),
&format!("{party}'s node list"),
&format!("none of {party}'s nodes would be members"),
)?;
sign(&node, &signer, &mut record, &path, event::nodes(&nodes)).await
}
("propose", sub) => {
let counts = node.counts().await?;
let current = current(&counts)?;
signer.named_by(¤t)?;
let version = to_propose(&node, ¤t, sub).await?;
let proposed = client::backable(¤t, &version)
.map_err(|why| anyhow!("not a version a party may back: {why}"))?;
if client::described(¤t, &proposed).is_empty() {
bail!(
"it changes nothing of version {} but its number",
current.number
);
}
// What it proposes, said before anything is signed.
println!("version {} on {}:", proposed.number, current.number);
for line in version_lines(&counts, ¤t, &proposed) {
println!(" {line}");
}
let yes = proposing_flags(sub).get_flag("yes");
let question = if yes {
"Propose it, and vote `true` on it?"
} else {
"Propose it?"
};
if !confirmed(question)? {
println!("nothing proposed");
return Ok(());
}
sign(
&node,
&signer,
&mut record,
&path,
event::proposal(&version),
)
.await?;
let counts = node.counts().await?;
println!(
"proposal {}",
marked(&proposed.hash.to_string(), &proposal_hashes(&counts))
);
if yes {
let wait = waited(proposing_flags(sub));
vote(
&node,
&signer,
&mut record,
&path,
proposed.hash,
true,
false,
wait,
)
.await?;
}
Ok(())
}
("vote", sub) => {
let proposal = proposal_named(&node.counts().await?, sub)?;
let yes = sub.get_one::<String>("yes").map(String::as_str) == Some("yes");
vote(
&node,
&signer,
&mut record,
&path,
proposal,
yes,
true,
waited(sub),
)
.await
}
("again", _) => again(&node, &signer, &mut record, &path).await,
_ => unreachable!("every subcommand handled"),
}
}
/// The hashes of the proposals on the current version, as `counts` names them.
fn proposal_hashes(counts: &JsonValue) -> Vec<String> {
counts["proposals"]
.as_object()
.into_iter()
.flatten()
.map(|(hash, _)| hash.clone())
.collect()
}
/// The proposal the argument `proposal` names: by its hash, or a prefix of the hash of one
/// on the current version (`client::named`).
fn proposal_named(counts: &JsonValue, sub: &ArgMatches) -> Result<Id> {
let given = sub.get_one::<String>("proposal").expect("required");
let hashes = proposal_hashes(counts);
let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect();
client::named(given, &hashes, "proposal").map_err(|why| anyhow!(why))
}
/// `--wait` of `matches`.
fn waited(matches: &ArgMatches) -> std::time::Duration {
std::time::Duration::from_secs(matches.get_one::<u64>("wait").copied().unwrap_or(5))
}
/// The matches of `propose` holding `--yes` and `--print`: its subcommand's, where it has
/// one.
fn proposing_flags(sub: &ArgMatches) -> &ArgMatches {
sub.subcommand().map_or(sub, |(_, intent)| intent)
}
/// What `propose` proposes: the version its file holds, or the version after `current`
/// changed as its subcommand says (`Intent`, `intended`).
async fn to_propose(node: &Node, current: &Version, sub: &ArgMatches) -> Result<Json> {
let Some((name, given)) = sub.subcommand() else {
return version_in(sub.get_one::<String>("file").expect("required"));
};
let intent = intent_of(node, name, given).await?;
client::json(&intended(current, &intent)?).map_err(|why| anyhow!(why))
}
/// The change an intent's subcommand `name` asks for, with its arguments `given`
/// (`intents`); of a checkpoint, at the heads `node` shows.
async fn intent_of(node: &Node, name: &str, given: &ArgMatches) -> Result<Intent> {
let one = |arg: &str| given.get_one::<String>(arg).expect("required").clone();
Ok(match name {
"admit" => Intent::Admit {
party: one("party"),
keys: key_lines(&strings(given, "keys"))?,
nodes: node_ids(strings(given, "nodes"))?,
},
"remove" => Intent::Remove(one("party")),
"give" => Intent::Give {
path: one("path"),
writer: one("writer"),
},
"take" => Intent::Take(one("path")),
"keys" => Intent::Keys {
party: one("party"),
keys: key_lines(&strings(given, "keys"))?,
},
"nodes" => Intent::Nodes {
party: one("party"),
nodes: node_ids(strings(given, "nodes"))?,
},
"checkpoint" => Intent::Checkpoint(node.summary().await?.1),
"revision" => Intent::Revision(one("feature")),
_ => unreachable!("every intent handled"),
})
}
/// `--founder PARTY=NODE,…` of `given`: each party's node list named anew in the fork's
/// version `version`, `since` its number, so that those nodes are members there.
fn founders(version: &mut JsonValue, given: &ArgMatches) -> Result<()> {
let number = version["number"].clone();
for item in strings(given, "founder") {
let (party, nodes) = item
.split_once('=')
.with_context(|| format!("--founder {item:?}: PARTY=NODE,… it is"))?;
if version["keys"].get(party).is_none() {
bail!("--founder {party}: no party of the fork's version");
}
let nodes = node_ids(
nodes
.split(',')
.filter(|node| !node.is_empty())
.map(str::to_owned)
.collect(),
)?;
version["nodes"][party] = serde_json::json!({"since": number, "nodes": nodes});
}
Ok(())
}
/// The version the proposal `proposal` on the current version proposes, as `counts` names
/// the event proposing it, and the node holds it.
async fn proposal_version(node: &Node, counts: &JsonValue, proposal: Id) -> Result<Json> {
let ballot = &counts["proposals"][proposal.to_string()];
let Some(id) = ballot["proposals"][0].as_str().and_then(Id::from_hex) else {
bail!(
"{proposal}: {}",
ballot["none"]
.as_str()
.unwrap_or("the node names no event proposing it")
);
};
match Event::read(&node.event(&id).await?) {
Some(Event::Signed(Signed {
does: Does::Proposal { hash, version },
..
})) if hash == proposal => Ok(version),
_ => bail!("the node's {id} isn't the proposal it names"),
}
}
/// The keys `given` names, as the federation spells them (without comments): each an
/// `authorized_keys` line itself, or a file of such lines, blank ones and `#` comments
/// left out; none twice, one at least.
fn key_lines(given: &[String]) -> Result<Vec<String>> {
let lines = keys_given(given)?;
if lines.is_empty() {
bail!("no key given: a party signs with the keys a version names");
}
Ok(lines)
}
/// As `key_lines`, none too.
fn keys_given(given: &[String]) -> Result<Vec<String>> {
let mut lines: Vec<String> = Vec::new();
for item in given {
let found = match Key::parse(item) {
Ok(key) => vec![key.line()],
Err(itself) => std::fs::read_to_string(item)
.map_err(|error| anyhow!("{item}: no key ({itself}), nor a file ({error})"))?
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(|line| {
Key::parse(line)
.map(|key| key.line())
.map_err(|why| anyhow!("{item}: {line:?}: {why}"))
})
.collect::<Result<Vec<String>>>()?,
};
for line in found {
if lines.contains(&line) {
bail!("{} given twice", client::fingerprint(&line));
}
lines.push(line);
}
}
Ok(lines)
}
/// `given`, where each is a node ID.
fn node_ids(given: Vec<String>) -> Result<Vec<String>> {
match given.iter().find(|id| !keys::node_id(id)) {
Some(none) => bail!("{none:?} isn't a node ID"),
None => Ok(given),
}
}
/// `hash`, its shortest prefix that no other of `among` starts with marked, as bold, where
/// it goes to a terminal and `NO_COLOR` is unset: the part that names it to the client.
fn marked(hash: &str, among: &[String]) -> String {
use std::io::IsTerminal;
if !std::io::stdout().is_terminal() || std::env::var_os("NO_COLOR").is_some() {
return hash.to_owned();
}
let mut ids: Vec<&str> = among.iter().map(String::as_str).collect();
if !ids.contains(&hash) {
ids.push(hash);
}
let at = ids.iter().position(|id| *id == hash).expect("among them");
let length = client::prefixes(&ids)[at];
format!("\x1b[1m{}\x1b[0m{}", &hash[..length], &hash[length..])
}
/// The party's keys or nodes (`what`) as they count, as `counts` names them.
fn listed(counts: &JsonValue, party: &str, what: &str) -> Vec<String> {
counts["parties"][party][what]
.as_array()
.into_iter()
.flatten()
.filter_map(|value| value.as_str().map(str::to_owned))
.collect()
}
/// The key set or node list to write: `set`, where given, else `now`, as it counts, with
/// `add` added and `remove` taken off, each of which must change it. Left empty, only with
/// `force`, as then `empty` (`what` names the set or list in the errors). Said before it
/// is signed.
fn changed(
now: Vec<String>,
set: Option<Vec<String>>,
add: Vec<String>,
remove: Vec<String>,
force: bool,
what: &str,
empty: &str,
) -> Result<Vec<String>> {
let mut list = Vec::new();
for item in set.unwrap_or(now) {
if list.contains(&item) {
bail!("{what} would hold {item} twice");
}
list.push(item);
}
for item in add {
if list.contains(&item) {
bail!("{what} holds {item} already");
}
list.push(item);
}
for item in remove {
let Some(at) = list.iter().position(|held| *held == item) else {
bail!("{what} doesn't hold {item}");
};
list.remove(at);
}
if list.is_empty() && !force {
bail!("{what} would be empty: {empty}. --force writes it so");
}
let shown = if list.is_empty() {
"none".to_owned()
} else {
list.join(" ")
};
println!("{what}: {shown}");
Ok(list)
}
/// The version the file `file` holds, as JSON the federation takes.
fn version_in(file: &str) -> Result<Json> {
let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?;
let version: JsonValue =
serde_json::from_str(&text).with_context(|| format!("{file} isn't JSON"))?;
client::json(&version).map_err(|why| anyhow!(why))
}
/// `bytes`, to standard output.
fn out(bytes: &[u8]) -> Result<()> {
use std::io::Write;
let mut stdout = std::io::stdout().lock();
stdout.write_all(bytes)?;
stdout.flush()?;
Ok(())
}
fn strings(matches: &ArgMatches, name: &str) -> Vec<String> {
matches
.get_many::<String>(name)
.into_iter()
.flatten()
.cloned()
.collect()
}
/// What `--key` gives: a private key, from an OpenSSH private key file; or a public key,
/// given itself (an `authorized_keys` line), or the first of a file of such lines, with
/// how many more the file holds.
enum Given {
Private(SigningKey),
Public(Key, usize),
}
/// What `given`, `--key`'s value, gives (`Given`).
fn given_key(given: &str) -> Result<Given> {
let itself = match Key::parse(given) {
Ok(key) => return Ok(Given::Public(key, 0)),
Err(why) => why,
};
let text = match std::fs::read_to_string(given) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
bail!("{given}: no file, nor a key ({itself})")
}
Err(error) => return Err(error).with_context(|| format!("Reading {given}")),
};
if text.trim_start().starts_with("-----BEGIN") {
let key = client::signing_key(&text).map_err(|why| anyhow!("{given}: {why}"))?;
return Ok(Given::Private(key));
}
let mut lines = text
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'));
let first = lines
.next()
.with_context(|| format!("{given} holds no key"))?;
let key = Key::parse(first).map_err(|why| anyhow!("{given}: {why}"))?;
Ok(Given::Public(key, lines.count()))
}
/// The key `--key` gives (`given_key`): a private key, signing here; or a public key,
/// signing through the ssh-agent at `SSH_AUTH_SOCK`, which must hold it. Of a file of
/// several public keys, the first, with a warning: another is given as `--key` itself.
fn signing_key(options: &Options) -> Result<Signing> {
let given = options
.key
.as_ref()
.context("--key names the party's key")?;
let key = match given_key(given)? {
Given::Private(key) => return Ok(Signing::File(key)),
Given::Public(key, 0) => key,
Given::Public(key, more) => {
eprintln!(
"Warning: {given} holds {} keys: signing with the first, {}; to sign with \
another, give that key itself as --key",
more + 1,
key.line()
);
key
}
};
let socket = std::env::var_os("SSH_AUTH_SOCK").with_context(|| {
format!(
"{} signs through an ssh-agent: SSH_AUTH_SOCK names none",
key.line()
)
})?;
Ok(Signing::Agent(key, PathBuf::from(socket)))
}
/// What signs: a key at hand, or a key the ssh-agent at a socket holds.
enum Signing {
File(SigningKey),
Agent(Key, PathBuf),
}
/// Who signs: the party, with one of its keys.
struct Signer {
key: Signing,
party: String,
}
impl Signer {
/// The key it signs with, as the federation spells it.
fn line(&self) -> String {
match &self.key {
Signing::File(key) => PublicKey(key.verifying_key().to_bytes()).line(),
Signing::Agent(key, _) => key.line(),
}
}
/// Refuses where `current` doesn't name the key it signs with for its party: only those
/// sign the party's votes, proposals, key set and node list, and otherwise only a
/// version naming the party's keys or list anew, by the parties' votes, changes them.
fn named_by(&self, current: &Version) -> Result<()> {
let (party, number) = (&self.party, current.number);
let Some(given) = current.parties.get(party) else {
bail!(
"{party} is no party of version {number}: only a version letting it in names its \
keys and node list, which a party of it proposes and the parties pass"
);
};
if !given.keys.contains(&self.line()) {
bail!(
"version {number} doesn't name the key --key gives for {party}: only the keys it \
names sign {party}'s votes, proposals, key set and node list. A version naming \
its keys or its list anew changes them: another party proposes it \
(continuum-party next, then propose), and the parties pass it"
);
}
Ok(())
}
fn sign(&self, deps: &[Id], does: (&str, Json)) -> Result<Vec<u8>> {
match &self.key {
Signing::File(key) => Ok(event::signed(key, &self.party, &self.line(), deps, does)),
Signing::Agent(key, socket) => {
// The agent's answer is waited for blocking the thread, in async code: the
// client signs one event at a time and does nothing else meanwhile, and an
// agent may wait for its user (a touch, a confirmation) as long as that
// takes, which nothing here should cut short.
event::signed_by(&self.party, &key.line(), deps, does, |bytes| {
keys::sign_through(socket, key, bytes)
})
.map_err(|why| anyhow!(why))
}
}
}
}
/// An event signed on the node's heads, recorded, and put.
async fn sign(
node: &Node,
signer: &Signer,
record: &mut Record,
path: &Path,
does: (&str, Json),
) -> Result<()> {
let (_, heads) = node.summary().await?;
let event = signer.sign(&heads, does)?;
record.signed(&event);
record.save(path).map_err(|why| anyhow!(why))?;
node.put(&event).await
}
/// A vote, by the record: written to it before it is sent. Refused where the node shows a
/// vote of its party on the current version that the record lacks (`consistent`); what
/// may keep another from the node said (`cut_off`). With `ask`, what it votes on is said
/// first, and asked about on a terminal (`confirmed`); without, that was done. It waits
/// `wait` before it casts, and asks the node again.
#[allow(clippy::too_many_arguments)]
async fn vote(
node: &Node,
signer: &Signer,
record: &mut Record,
path: &Path,
proposal: Id,
yes: bool,
ask: bool,
wait: std::time::Duration,
) -> Result<()> {
let counts = node.counts().await?;
let current = current(&counts)?;
signer.named_by(¤t)?;
consistent(&counts, ¤t, record)?;
for line in cut_off(&counts, &record.party) {
eprintln!("Warning: {line}");
}
let ballots = &counts["proposals"];
let ids = |hash: &Id, what: &str| -> Vec<Id> {
ballots[hash.to_string()][what]
.as_array()
.into_iter()
.flatten()
.filter_map(|id| id.as_str().and_then(Id::from_hex))
.collect()
};
let proposals = ids(&proposal, "proposals");
let Some(proposing) = proposals.first().copied() else {
if let Some(why) = ballots[proposal.to_string()]["none"].as_str() {
bail!("{proposal}: {why}");
}
bail!("no proposal of hash {proposal} on the current version, as the node reads it");
};
let proposed = match Event::read(&node.event(&proposing).await?) {
Some(Event::Signed(Signed {
does: Does::Proposal { hash, version },
..
})) if hash == proposal => version,
_ => bail!("the node's {proposing} isn't the proposal it names"),
};
// What it votes on, said before anything is cast.
let hashes = proposal_hashes(&counts);
if ask {
for line in preview(node, &counts, &proposal.to_string(), &hashes).await? {
println!("{line}");
}
}
// A later revision: the node knows it, or it stops at the version once it passes; and
// so does every other node not known to know it.
if yes
&& let Ok(version) = Version::read(&proposed)
&& version.revision != current.revision
{
if !node.revisions().await?.contains(&version.revision.id()) {
bail!(
"{proposal} moves to {}, which the node doesn't know: once it passed, a node \
that doesn't stops at it, and votes nothing till upgraded; upgrade this node \
and every other of the party to a continuum that knows it, then back it",
version.revision
);
}
warn_unready(&counts, version.revision);
}
// The votes on its party's earlier proposals it backed, for the nays among them.
let mut nays = Vec::new();
let backed: BTreeSet<Id> = record
.votes
.iter()
.filter_map(|text| match Event::read_taken(text.as_bytes()) {
Some(Event::Signed(Signed {
does:
Does::Vote {
on,
proposal,
yes: true,
},
..
})) if on == current.hash => Some(proposal),
_ => None,
})
.collect();
for earlier in &backed {
for id in ids(earlier, "votes") {
nays.push(node.event(&id).await?);
}
}
let kept = record
.may_vote(¤t, proposal, &proposed, yes, &nays)
.map_err(|why| anyhow!(why))?;
if yes {
let parties = |what: &str| -> BTreeSet<String> {
ballots[proposal.to_string()][what]
.as_array()
.into_iter()
.flatten()
.filter_map(|party| party.as_str().map(str::to_owned))
.collect()
};
if let Some(why) = client::binding(¤t, &signer.party, &parties("yes"), &parties("no"))
{
eprintln!("Warning: {why}");
}
}
// On an event proposing it the node shows, of a checkpoint one above the heads it
// names, and on the nays that freed the party (`client::building`).
let checkpoint = Version::read(&proposed)
.ok()
.and_then(|version| version.checkpoint)
.is_some();
if checkpoint && yes && !kept.is_empty() {
eprintln!(
"Warning: this `true` builds on {proposing} alone, not on the nays that freed \
{party}: where they came after the heads it names, and {party}'s `true` they \
ended is in the history of {proposing}, nodes refuse it; a checkpoint proposed \
after them takes {party}'s `true`",
party = signer.party
);
}
let on = client::building(proposing, checkpoint, &kept).map_err(|why| anyhow!(why))?;
let word = if yes { "`true`" } else { "`false`" };
if ask
&& !confirmed(&format!(
"Vote {word} on {}?",
marked(&proposal.to_string(), &hashes)
))?
{
println!("nothing cast");
return Ok(());
}
if !wait.is_zero() {
tokio::time::sleep(wait).await;
let again = node.counts().await?;
if self::current(&again)?.hash != current.hash {
bail!(
"a version passed meanwhile: the proposal lapsed with version {}",
current.number
);
}
consistent(&again, ¤t, record)?;
}
let cast = signer.sign(&on, event::vote(current.hash, proposal, yes))?;
record.cast(¤t, &cast, kept);
record.save(path).map_err(|why| anyhow!(why))?;
node.put(&cast).await
}
/// How long ago a node heard from another for it to count as heard from lately (`cut_off`).
const LATELY: u64 = 5 * 60;
/// Refuses where the node shows a vote of `record`'s party on `current`, by `counts`, that
/// the record lacks (`unrecorded`): another record votes for the party, or this one was
/// begun anew. Of the record's votes the node lacks, says that they may be on their way.
fn consistent(counts: &JsonValue, current: &Version, record: &Record) -> Result<()> {
let party = &record.party;
let (theirs, ours) = unrecorded(counts, current, record);
if !theirs.is_empty() {
bail!(
"the node shows votes of {party} on version {} that this record lacks: {}. Another \
record votes for {party}, or this one was begun anew: casting beside them may be \
voting twice. `continuum-party restore` takes them into this record; then vote",
current.number,
theirs.join(", ")
);
}
if !ours.is_empty() {
eprintln!(
"Note: the node doesn't show this record's {} yet: on their way, or held back where \
they were put",
ours.join(", ")
);
}
Ok(())
}
/// How the party's votes on `current` that `counts` shows differ from `record`'s: those the
/// node shows that the record lacks, and those the record holds that the node doesn't show;
/// each as `` `true` on <proposal's hash> ``.
fn unrecorded(
counts: &JsonValue,
current: &Version,
record: &Record,
) -> (Vec<String>, Vec<String>) {
let party = record.party.as_str();
let mut shown = Vec::new();
for (hash, ballot) in counts["proposals"].as_object().into_iter().flatten() {
for (what, yes) in [("yes", true), ("no", false)] {
let voted = ballot[what]
.as_array()
.is_some_and(|parties| parties.iter().any(|of| of.as_str() == Some(party)));
if voted {
shown.push((hash.clone(), yes));
}
}
}
let held: Vec<(String, bool)> = record
.votes_cast(¤t.hash)
.into_iter()
.map(|(proposal, yes)| (proposal.to_string(), yes))
.collect();
let spelled = |(hash, yes): &(String, bool)| format!("`{yes}` on {hash}");
(
shown
.iter()
.filter(|vote| !held.contains(vote))
.map(spelled)
.collect(),
held.iter()
.filter(|vote| !shown.contains(vote))
.map(spelled)
.collect(),
)
}
/// What may keep a vote of `party`'s from the node, by `counts`: the party's nodes the node
/// didn't hear from within `LATELY`, through which another of its votes may have gone; and,
/// where those are a third of the parties with nodes or more, the parties none of whose
/// nodes it heard from within it, which a part of the swarm cut off would be. A line each.
fn cut_off(counts: &JsonValue, party: &str) -> Vec<String> {
let parties = counts["parties"].as_object();
let quiet = |of: &JsonValue| -> Vec<String> {
let names = &of["names"];
of["nodes"]
.as_array()
.into_iter()
.flatten()
.filter_map(JsonValue::as_str)
.filter(|node| of["heard"][*node].as_u64().is_none_or(|ago| ago > LATELY))
.map(|node| match names[node].as_str() {
Some(name) => format!("{node} ({name})"),
None => node.to_owned(),
})
.collect()
};
let mut lines = Vec::new();
if let Some(own) = parties.and_then(|parties| parties.get(party)) {
let quiet = quiet(own);
if !quiet.is_empty() {
lines.push(format!(
"the node hasn't heard from these nodes of {party} lately: {}: a vote of \
{party} put through one of them may not have reached it",
quiet.join(", ")
));
}
}
let with_nodes: Vec<(&String, &JsonValue)> = parties
.into_iter()
.flatten()
.filter(|(_, of)| {
of["nodes"]
.as_array()
.is_some_and(|nodes| !nodes.is_empty())
})
.collect();
let unheard: Vec<&str> = with_nodes
.iter()
.filter(|(_, of)| quiet(of).len() == of["nodes"].as_array().map_or(0, Vec::len))
.map(|(name, _)| name.as_str())
.collect();
if !unheard.is_empty() && 3 * unheard.len() >= with_nodes.len() {
lines.push(format!(
"the node hasn't heard from any node of {} lately: a part of the swarm may be cut \
off, and its votes not here",
unheard.join(", ")
));
}
lines
}
/// Takes into the record at `path`, or a new one of `party`, the party's votes on the current
/// version as the node holds them (`Record::restore`): best effort, as one on its way from
/// elsewhere isn't among them. What it signs anew after a move (`again`) it doesn't learn.
async fn restore(node: &Node, path: &Path, party: Option<&str>) -> Result<()> {
let (store, _) = node.summary().await?;
let counts = node.counts().await?;
let current = current(&counts)?;
let mut record = if path.exists() {
Record::load(path).map_err(|why| anyhow!(why))?
} else {
let party = party.context("no record, and no --party saying whose votes to take")?;
Record::before(store, party)
};
if record.store != store.to_string() {
bail!("{} is a record of another store", path.display());
}
let began_here = record.began == current.hash.to_string();
let mut votes = Vec::new();
for hash in proposal_hashes(&counts) {
for id in counts["proposals"][&hash]["votes"]
.as_array()
.into_iter()
.flatten()
.filter_map(|id| id.as_str().and_then(Id::from_hex))
{
votes.push(node.event(&id).await?);
}
}
let taken = record.restore(¤t, &votes);
record.save(path).map_err(|why| anyhow!(why))?;
println!(
"took {taken} vote{} of {} on version {} into {}, as the node holds them; one on its \
way from elsewhere isn't among them",
if taken == 1 { "" } else { "s" },
record.party,
current.number,
path.display()
);
if began_here {
println!("it casts on version {} now, by them", current.number);
}
for line in cut_off(&counts, &record.party) {
eprintln!("Warning: {line}");
}
Ok(())
}
/// Warns of the nodes not known to know `revision`, by `counts` (`client::unready`).
fn warn_unready(counts: &JsonValue, revision: Revision) {
let behind = client::unready(counts, revision);
if behind.is_empty() {
return;
}
eprintln!(
"Warning: these nodes aren't known to know {revision}, as far as the node heard from \
them; once a version of it passes, each stops at it till upgraded:"
);
for line in behind {
eprintln!(" {line}");
}
}
/// Signs again what a move refused: of the latest event it signed at each place, its key
/// set and its node list, those the node refuses as not above its checkpoint's heads, or
/// as built on one it refuses.
async fn again(node: &Node, signer: &Signer, record: &mut Record, path: &Path) -> Result<()> {
let refused = node.get("/events/refused").await?;
let moved: BTreeSet<Id> = refused["refused"]
.as_array()
.into_iter()
.flatten()
.filter(|entry| matches!(entry["kind"].as_str(), Some("notAbove" | "builtOn")))
.filter_map(|entry| entry["id"].as_str().and_then(Id::from_hex))
.collect();
let again = record.again(|id| moved.contains(id));
if again.is_empty() {
println!("nothing to sign again");
}
for (refused, does) in again {
let does = match does {
Does::Write { path, value } => event::write(&path.join("/"), value),
Does::Keys(keys) => event::keys(&keys),
Does::Nodes(nodes) => event::nodes(&nodes),
Does::Proposal { .. } | Does::Vote { .. } | Does::Merge => continue,
};
println!("signing again {refused}");
sign(node, signer, record, path, does).await?;
}
Ok(())
}
/// The party the client works as: for `init`, the one it begins a record of; else the
/// one its record names, where there is one, else `--party`; none where neither. `--party`
/// naming another than these is an error.
fn working_as(name: &str, sub: &ArgMatches, options: &Options) -> Result<Option<String>> {
let named = if name == "init" {
sub.get_one::<String>("party").cloned()
} else {
options
.record
.as_ref()
.map(Path::new)
.filter(|path| path.exists())
.map(|path| Record::load(path).map(|record| record.party))
.transpose()
.map_err(|why| anyhow!(why))?
};
match (named, &options.party) {
(Some(named), Some(given)) if named != *given => {
let whose = if name == "init" {
"init begins a record of"
} else {
"the record is"
};
bail!("--party {given}, but {whose} {named}'s")
}
(Some(named), _) => Ok(Some(named)),
(None, given) => Ok(given.clone()),
}
}
/// What the node and the party's record say at a glance: the store, its checkpoint and
/// heads; the current version, its federation and revision, and its parties; the party's
/// keys and node list as they count, and whether the version names `--key`; the node's
/// party, whether it votes for it by itself, and where it stopped; the proposals on the
/// current version, each as `show` begins; the versions the node refused of its own; and
/// what a move refused that the party signs again (`again`).
async fn status(node: &Node, options: &Options, party: Option<&str>) -> Result<()> {
let summary = node.get("/events").await?;
let counts = node.counts().await?;
let current = current(&counts)?;
let text = |value: &JsonValue| value.as_str().unwrap_or_default().to_owned();
let plural =
|n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many });
let heads = summary["heads"].as_array().map_or(0, Vec::len);
println!("store {}", text(&summary["store"]));
println!(" checkpoint {}", text(&summary["checkpoint"]));
println!(
" {}, {} taken after the checkpoint",
plural(heads, "head", "heads"),
plural(
summary["taken"].as_u64().unwrap_or_default() as usize,
"event",
"events"
)
);
let needed = (2 * current.parties.len()).div_ceil(3);
println!("version {} ({})", current.number, current.hash);
println!(
" federation {}, {}",
counts["version"]["version"]["federation"], current.revision
);
println!(
" {}, {needed} passing a change:",
plural(current.parties.len(), "party", "parties")
);
for party in current.parties.keys() {
println!(" {party}");
}
let record = options
.record
.as_ref()
.map(PathBuf::from)
.filter(|path| path.exists())
.map(|path| Record::load(&path).map_err(|why| anyhow!(why)))
.transpose()?;
let party = party
.map(str::to_owned)
.or_else(|| summary["party"].as_str().map(str::to_owned));
if let Some(party) = &party {
println!("{party}");
match current.parties.get(party) {
None => println!(" no party of version {}", current.number),
Some(given) => {
for line in party_lines(&counts, party, &given.keys, options.key.as_deref()) {
println!(" {line}");
}
}
}
}
let by_itself = if summary["votesByItself"].as_bool() == Some(true) {
", voting for it by itself"
} else {
""
};
match summary["party"].as_str() {
Some(of) => println!("the node: {of}'s{by_itself}"),
None => println!("the node: of no party"),
}
if let Some(stopped) = summary["stopped"].as_object() {
println!(
" stopped at {}: {}",
stopped
.get("id")
.and_then(JsonValue::as_str)
.unwrap_or_default(),
stopped
.get("why")
.and_then(JsonValue::as_str)
.unwrap_or_default()
);
}
let hashes = proposal_hashes(&counts);
match hashes.len() {
0 => println!("no proposal on version {}", current.number),
1 => println!("1 proposal on version {} (show says more):", current.number),
n => println!(
"{n} proposals on version {} (show says more):",
current.number
),
}
for hash in &hashes {
println!(" {}", ballot_line(&counts, ¤t, hash, &hashes));
}
let refused = node.get("/events/refused").await?;
let own = refused["own"].as_array().map_or(0, Vec::len);
if own > 0 {
println!(
"the node refused {own} version event{} by what it took before: keys may have \
voted twice, and nodes be apart (GET /events/refused)",
if own == 1 { "" } else { "s" }
);
}
if let Some(record) = &record {
let moved: BTreeSet<Id> = refused["refused"]
.as_array()
.into_iter()
.flatten()
.filter(|entry| matches!(entry["kind"].as_str(), Some("notAbove" | "builtOn")))
.filter_map(|entry| entry["id"].as_str().and_then(Id::from_hex))
.collect();
let again = record.again(|id| moved.contains(id)).len();
if again > 0 {
println!(
"{} of {}'s latest events a move refused: `again` signs {} again",
again,
record.party,
if again == 1 { "it" } else { "them" }
);
}
}
Ok(())
}
/// A party's keys and nodes, as `status` says them under its name, a line each, indented
/// beneath their heading: the keys the version names (`named`), which sign its votes,
/// proposals, key set and node list; those of its key set as it counts (`counts`), which
/// sign its writes; each by its fingerprint, `--key`'s (`given`) marked, and said where
/// it is neither; and its nodes as they count, by ID, each with the name it gave itself
/// where it did.
fn party_lines(
counts: &JsonValue,
party: &str,
named: &[String],
given: Option<&str>,
) -> Vec<String> {
let given = given.and_then(|given| match given_key(given).ok()? {
Given::Private(key) => Some(PublicKey(key.verifying_key().to_bytes()).line()),
Given::Public(key, _) => Some(key.line()),
});
let key_line = |key: &String| {
let mark = if given.as_ref() == Some(key) {
" (--key)"
} else {
""
};
format!(" {}{mark}", client::fingerprint(key))
};
let set = listed(counts, party, "keys");
let mut lines =
vec!["keys the version names (votes, proposals, key set, node list):".to_owned()];
lines.extend(named.iter().map(key_line));
if set == named {
lines.push("keys of its key set (writes): the same".to_owned());
} else {
lines.push("keys of its key set (writes):".to_owned());
lines.extend(set.iter().map(key_line));
}
if let Some(given) = &given
&& !named.contains(given)
&& !set.contains(given)
{
lines.push(format!(
"--key, {}, is none of these: it signs nothing for {party}",
client::fingerprint(given)
));
}
let nodes = listed(counts, party, "nodes");
if nodes.is_empty() {
lines.push("nodes: none".to_owned());
} else {
lines.push("nodes:".to_owned());
}
let names = &counts["parties"][party]["names"];
lines.extend(nodes.iter().map(|node| match names[node].as_str() {
Some(name) => format!(" {node} ({name})"),
None => format!(" {node}"),
}));
lines
}
/// The values that count, all or under the place `path` names (and it), each with who
/// writes there, a line each: `PATH VALUE (WRITER)`, the value as JSON; or with `--json`,
/// one JSON object of them, by place.
async fn values(node: &Node, sub: &ArgMatches) -> Result<()> {
let counts = node.counts().await?;
let current = current(&counts)?;
let under = sub
.get_one::<String>("path")
.map(|path| path.trim_end_matches('/').to_owned());
let selected: serde_json::Map<String, JsonValue> = counts["values"]
.as_object()
.into_iter()
.flatten()
.filter(|(place, _)| is_under(place, under.as_deref()))
.map(|(place, value)| (place.clone(), value.clone()))
.collect();
if sub.get_flag("json") {
println!("{}", serde_json::to_string_pretty(&selected)?);
return Ok(());
}
for (place, value) in &selected {
let writer = super::version::path(place)
.and_then(|segments| current.writer(&segments).map(str::to_owned))
.unwrap_or_else(|| "nobody".to_owned());
println!("{place} {} ({writer})", serde_json::to_string(value)?);
}
Ok(())
}
/// What counts as one JSON value, from `values`, what counts at each place: each place's
/// value at its path, the maps on its way made; of those on the way to `path` or under
/// it alone (all, for an empty `path`). A place under another one's value goes into it,
/// winning over what that value held there: the deeper place is the later word.
fn tree(values: &serde_json::Map<String, JsonValue>, path: &str) -> JsonValue {
let under = (!path.is_empty()).then_some(path);
let mut places: Vec<(Vec<&str>, &JsonValue)> = values
.iter()
.filter(|(place, _)| {
is_under(place, under) || under.is_some_and(|under| is_under(under, Some(place)))
})
.map(|(place, value)| (place.split('/').collect(), value))
.collect();
places.sort_by(|(a, _), (b, _)| a.len().cmp(&b.len()).then(a.cmp(b)));
let mut tree = JsonValue::Object(serde_json::Map::new());
for (segments, value) in places {
let mut at = &mut tree;
for segment in segments {
if !at.is_object() {
*at = JsonValue::Object(serde_json::Map::new());
}
at = at
.as_object_mut()
.expect("made an object")
.entry(segment.to_owned())
.or_insert(JsonValue::Null);
}
merge(at, value.clone());
}
tree
}
/// `value` put where `at` is: objects merged, `value`'s members winning, deeply; else
/// `value` in its place.
fn merge(at: &mut JsonValue, value: JsonValue) {
match (at, value) {
(JsonValue::Object(held), JsonValue::Object(given)) => {
for (key, value) in given {
merge(held.entry(key).or_insert(JsonValue::Null), value);
}
}
(at, value) => *at = value,
}
}
/// What `tree` holds at `path`, segments by slashes, a list's items by their index; all of
/// it for an empty `path`.
fn at<'a>(tree: &'a JsonValue, path: &str) -> Option<&'a JsonValue> {
if path.is_empty() {
return Some(tree);
}
path.split('/').try_fold(tree, |at, segment| match at {
JsonValue::Object(members) => members.get(segment),
JsonValue::Array(items) => items.get(segment.parse::<usize>().ok()?),
_ => None,
})
}
/// Whether `place` is the place `under` names, or under it; any, where `under` is none.
fn is_under(place: &str, under: Option<&str>) -> bool {
under.is_none_or(|under| {
place == under
|| place
.strip_prefix(under)
.is_some_and(|rest| rest.starts_with('/'))
})
}
/// The proposals on the current version, each as `preview` says it.
async fn proposals(node: &Node) -> Result<()> {
let counts = node.counts().await?;
let hashes = proposal_hashes(&counts);
for hash in &hashes {
for line in preview(node, &counts, hash, &hashes).await? {
println!("{line}");
}
}
Ok(())
}
/// What a party votes on, in words: the proposal of `hash` on the current version, as
/// `counts` reads it, named among `hashes` (`marked`): whether it passed or is dead, who
/// voted what, and how many more `true` pass it; who proposed it; what its version does
/// (`client::described`); what moving to its checkpoint refuses of what this node took;
/// the places holding a value whose writer it moves; the nodes not known to know its
/// revision; and why no client backs it, where none does.
async fn preview(
node: &Node,
counts: &JsonValue,
hash: &str,
hashes: &[String],
) -> Result<Vec<String>> {
let current = current(counts)?;
let ballot = &counts["proposals"][hash];
let mut lines = vec![ballot_line(counts, ¤t, hash, hashes)];
let Some(id) = ballot["proposals"][0].as_str() else {
if let Some(why) = ballot["none"].as_str() {
lines.push(format!(" backed by no client: {why}"));
}
return Ok(lines);
};
let id = Id::from_hex(id).ok_or_else(|| anyhow!("the node names no event ID: {id}"))?;
let (party, version) = match Event::read(&node.event(&id).await?) {
Some(Event::Signed(Signed {
party,
does: Does::Proposal { hash: of, version },
..
})) if of.to_string() == hash => (party, version),
_ => {
lines.push(format!(" the event {id} proposes no version of that hash"));
return Ok(lines);
}
};
let proposed = match client::backable(¤t, &version) {
Ok(proposed) => proposed,
Err(why) => {
lines.push(format!(" proposed by {party}; backed by no client: {why}"));
return Ok(lines);
}
};
lines.push(format!(
" proposed by {party}: version {} on {}",
proposed.number, current.number
));
lines.extend(
version_lines(counts, ¤t, &proposed)
.into_iter()
.map(|line| format!(" {line}")),
);
if proposed.checkpoint.is_some() {
let beside = ballot["beside"].as_array().map_or(0, Vec::len);
lines.push(match beside {
0 => " moving there refuses nothing this node took".to_owned(),
n => format!(
" moving there refuses {n} of the writes, key sets and node lists this node \
took, which their parties sign again (`beside` in GET /events/counts)"
),
});
}
Ok(lines)
}
/// The proposal of `hash` on `current`, as `counts` reads it, named among `hashes`
/// (`marked`): whether it passed or is dead, how many more `true` pass it, and who voted
/// what.
fn ballot_line(counts: &JsonValue, current: &Version, hash: &str, hashes: &[String]) -> String {
let ballot = &counts["proposals"][hash];
let names = |what: &str| -> (usize, String) {
let names: Vec<&str> = ballot[what]
.as_array()
.into_iter()
.flatten()
.filter_map(JsonValue::as_str)
.collect();
let spelled = if names.is_empty() {
"nobody".to_owned()
} else {
names.join(", ")
};
(names.len(), spelled)
};
let ((yes, backers), (_, nays)) = (names("yes"), names("no"));
let parties = current.parties.len();
let needed = (2 * parties).div_ceil(3);
let standing = if ballot["passed"].as_bool() == Some(true) {
"passed".to_owned()
} else if ballot["dead"].as_bool() == Some(true) {
"dead".to_owned()
} else {
let more = needed.saturating_sub(yes);
format!("can still pass, {more} more `true` passing it ({needed} of {parties})")
};
format!(
"{}: {standing}; true: {backers}; false: {nays}",
marked(hash, hashes)
)
}
/// What `proposed` does to `current`, in words, a line each: what its version does
/// (`client::described`), the places holding a value in `counts` whose writer it moves,
/// and the nodes not known to know its revision.
fn version_lines(counts: &JsonValue, current: &Version, proposed: &Version) -> Vec<String> {
let mut lines = client::described(current, proposed);
let places: Vec<&str> = counts["values"]
.as_object()
.into_iter()
.flatten()
.map(|(place, _)| place.as_str())
.collect();
lines.extend(
client::writers(current, proposed, places)
.into_iter()
.map(|line| format!("who writes {line}")),
);
if proposed.revision != current.revision {
lines.extend(
client::unready(counts, proposed.revision)
.into_iter()
.map(|line| format!("not known to know {}: {line}", proposed.revision)),
);
}
lines
}
/// Whether the user, asked `question` where both its input and the client's errors are a
/// terminal, answers yes. Asked nothing, as in a script, it does.
fn confirmed(question: &str) -> Result<bool> {
use std::io::{BufRead, IsTerminal, Write};
if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
return Ok(true);
}
eprint!("{question} [y/N] ");
std::io::stderr().flush()?;
let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?;
Ok(matches!(
answer.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
/// The version after `current`, to change and propose: `current` numbered on, naming its
/// hash as the version it changes, and without the checkpoint it names, whose heads are
/// behind: a version naming them again is never written. With `feature`, following the
/// revision that adds it, where that isn't earlier than the current one's.
fn next(current: &Version, feature: Option<&str>) -> Result<JsonValue> {
let mut next: JsonValue = serde_json::from_slice(¤t.json.bytes())?;
let fields = next
.as_object_mut()
.context("a version that is no object")?;
fields.insert("number".to_owned(), (current.number + 1).into());
fields.insert("changes".to_owned(), current.hash.to_string().into());
fields.remove("checkpoint");
if let Some(name) = feature {
let revision = adding(name)?;
if revision < current.revision {
bail!(
"the current version follows {}, later than {revision}: a version never \
follows an earlier revision than the one it changes",
current.revision
);
}
fields.insert("revision".to_owned(), revision.id().to_string().into());
}
Ok(next)
}
/// A change to a version by what it is for, as `propose` and `fork` take it: the version
/// after the current one, changed so (`intended`).
#[derive(Debug)]
enum Intent {
/// Lets a party in, naming its keys and node list.
Admit {
party: String,
keys: Vec<String>,
nodes: Vec<String>,
},
/// Takes a party out, with the rules giving it places.
Remove(String),
/// Gives the places a path matches to `writer`, a party or `{party}`, by a rule before
/// every other; a rule of that path before goes.
Give { path: String, writer: String },
/// Gives the places a path matches to nobody: the rules of that path go, and where
/// another may still give one of them, a rule giving them to nobody goes first.
Take(String),
/// Names a party's keys anew.
Keys { party: String, keys: Vec<String> },
/// Names a party's node list anew.
Nodes { party: String, nodes: Vec<String> },
/// Moves the store to a checkpoint at these heads.
Checkpoint(Vec<Id>),
/// Follows the revision that adds this feature (`next`).
Revision(String),
}
/// The version after `current` (`next`), changed as `intent` says: checked here where the
/// change needs `current` (the party it names is one, or isn't yet), and otherwise when it
/// is proposed (`client::backable`).
fn intended(current: &Version, intent: &Intent) -> Result<JsonValue> {
if let Intent::Revision(feature) = intent {
return next(current, Some(feature));
}
let mut next = next(current, None)?;
let number = next["number"].clone();
let of = |party: &str| -> Result<()> {
if !current.parties.contains_key(party) {
bail!("{party} is no party of version {}", current.number);
}
Ok(())
};
match intent {
Intent::Admit { party, keys, nodes } => {
if current.parties.contains_key(party) {
bail!("{party} is a party of version {} already", current.number);
}
if !super::version::is_party(party) {
bail!("{party:?} is no party's name: 1 to 64 of A-Z a-z 0-9 . _ @ -");
}
next["keys"][party.as_str()] = serde_json::json!({"since": number, "keys": keys});
next["nodes"][party.as_str()] = serde_json::json!({"since": number, "nodes": nodes});
}
Intent::Remove(party) => {
of(party)?;
for field in ["keys", "nodes"] {
if let Some(given) = next[field].as_object_mut() {
given.remove(party);
}
}
rules_of(&mut next)?.retain(|rule| rule["writer"].as_str() != Some(party.as_str()));
}
Intent::Give { path, writer } => {
if writer != "{party}" {
of(writer)?;
}
let rules = rules_of(&mut next)?;
rules.retain(|rule| rule["path"].as_str() != Some(path.as_str()));
rules.insert(0, serde_json::json!({"path": path, "writer": writer}));
}
Intent::Take(path) => {
let segments =
super::version::path(path).with_context(|| format!("{path:?} is no path"))?;
let rules = rules_of(&mut next)?;
let before = rules.len();
rules.retain(|rule| rule["path"].as_str() != Some(path.as_str()));
let dropped = rules.len() < before;
let still = rules.iter().any(|rule| {
rule["writer"] != JsonValue::Bool(false)
&& rule["path"]
.as_str()
.and_then(super::version::path)
.is_some_and(|other| overlaps(&segments, &other))
});
if still {
rules.insert(0, serde_json::json!({"path": path, "writer": false}));
} else if !dropped {
bail!("nobody writes at {path}: no rule gives a place there");
}
}
Intent::Keys { party, keys } => {
of(party)?;
next["keys"][party.as_str()] = serde_json::json!({"since": number, "keys": keys});
}
Intent::Nodes { party, nodes } => {
of(party)?;
next["nodes"][party.as_str()] = serde_json::json!({"since": number, "nodes": nodes});
}
Intent::Checkpoint(heads) => {
let mut heads = heads.clone();
heads.sort();
heads.dedup();
next["checkpoint"] = heads.iter().map(Id::to_string).collect::<Vec<_>>().into();
}
Intent::Revision(_) => unreachable!("returned above"),
}
Ok(next)
}
/// The rules of the version `json`.
fn rules_of(json: &mut JsonValue) -> Result<&mut Vec<JsonValue>> {
json["rules"]
.as_array_mut()
.context("a version whose rules are no list")
}
/// Whether some path matches both the rule paths `a` and `b`, as rules spell them (`*` any
/// one segment, `**` last, one or more, `{party}` a party's name): where unsure, as of
/// `{party}` and a name, yes.
fn overlaps(a: &[String], b: &[String]) -> bool {
match (a.split_first(), b.split_first()) {
(None, None) => true,
(Some((first, _)), _) if first.as_str() == "**" => !b.is_empty(),
(_, Some((first, _))) if first.as_str() == "**" => !a.is_empty(),
(Some((x, a)), Some((y, b))) => {
let any = |segment: &str| matches!(segment, "*" | "{party}");
(any(x) || any(y) || x == y) && overlaps(a, b)
}
_ => false,
}
}
/// The revision that adds the feature `name`.
fn adding(name: &str) -> Result<Revision> {
let Some(feature) = FEATURES.iter().find(|feature| feature.name() == name) else {
let names: Vec<&str> = FEATURES.iter().map(|feature| feature.name()).collect();
bail!(
"no feature {name:?} this continuum knows: it knows {}",
if names.is_empty() {
"none".to_owned()
} else {
names.join(", ")
}
);
};
Ok(feature.revision())
}
/// The first version of a federation, as `found`'s arguments `sub` say: its parties, each
/// with its keys (`PARTY=KEY|FILE`, again for more), `since` 0; their node lists
/// (`--nodes PARTY=NODE,…`), empty where not given; its rules in order (`--rule
/// PATH=WRITER`, `nobody` writing `false`), each party writing under `home/{party}/` where
/// none is given; and its revision (`--revision`). Checked as a first version.
fn founded(sub: &ArgMatches) -> Result<JsonValue> {
let mut keys: std::collections::BTreeMap<String, Vec<String>> = Default::default();
for item in strings(sub, "parties") {
let (party, given) = item
.split_once('=')
.with_context(|| format!("{item:?}: PARTY=KEY or PARTY=FILE it is"))?;
let held = keys.entry(party.to_owned()).or_default();
for line in key_lines(&[given.to_owned()])? {
if held.contains(&line) {
bail!("{party}: {} given twice", client::fingerprint(&line));
}
held.push(line);
}
}
let mut nodes: std::collections::BTreeMap<String, Vec<String>> = keys
.keys()
.map(|party| (party.clone(), Vec::new()))
.collect();
for item in strings(sub, "nodes") {
let (party, given) = item
.split_once('=')
.with_context(|| format!("--nodes {item:?}: PARTY=NODE,… it is"))?;
let Some(list) = nodes.get_mut(party) else {
bail!("--nodes {party}: no party given keys");
};
list.extend(node_ids(
given
.split(',')
.filter(|node| !node.is_empty())
.map(str::to_owned)
.collect(),
)?);
}
let given = strings(sub, "rule");
let rules: Vec<JsonValue> = if given.is_empty() {
vec![serde_json::json!({"path": "home/{party}/**", "writer": "{party}"})]
} else {
given
.iter()
.map(|rule| {
let (path, writer) = rule
.rsplit_once('=')
.with_context(|| format!("--rule {rule:?}: PATH=WRITER it is"))?;
let writer = match writer {
"nobody" => JsonValue::Bool(false),
writer => writer.into(),
};
Ok(serde_json::json!({"path": path, "writer": writer}))
})
.collect::<Result<_>>()?
};
let given = |lists: &std::collections::BTreeMap<String, Vec<String>>, what: &str| {
lists
.iter()
.map(|(party, items)| (party.clone(), serde_json::json!({"since": 0, what: items})))
.collect::<serde_json::Map<String, JsonValue>>()
};
let mut version = serde_json::json!({
"federation": super::version::FEDERATION,
"number": 0,
"changes": null,
"keys": given(&keys, "keys"),
"nodes": given(&nodes, "nodes"),
"rules": rules,
});
if let Some(name) = sub.get_one::<String>("revision") {
let revision = adding(name)?;
if revision != Revision::default() {
version["revision"] = revision.id().to_string().into();
}
}
let read = Version::read(&client::json(&version).map_err(|why| anyhow!(why))?)
.map_err(|why| anyhow!("no first version: {why}"))?;
read.changes_validly(None)
.map_err(|why| anyhow!("no first version: {why}"))?;
Ok(version)
}
/// The current version, as `counts` names it, checked: its hash its own.
fn current(counts: &JsonValue) -> Result<Version> {
let json = client::json(&counts["version"]["version"]).map_err(|why| anyhow!(why))?;
let version =
Version::read(&json).map_err(|why| anyhow!("the node's current version: {why}"))?;
if Some(version.hash.to_string().as_str()) != counts["version"]["hash"].as_str() {
bail!("the node's current version isn't of the hash it names");
}
Ok(version)
}
/// A node's API.
struct Node {
url: reqwest::Url,
http: reqwest::Client,
password: Option<(String, Option<String>)>,
token: Option<String>,
}
impl Node {
fn new(options: &Options) -> Result<Self> {
let _ = rustls::crypto::ring::default_provider().install_default();
let mut url: reqwest::Url = options.node.parse().context("--node isn't a URL")?;
let password = (!url.username().is_empty())
.then(|| (url.username().to_owned(), url.password().map(str::to_owned)));
let _ = url.set_username("");
let _ = url.set_password(None);
Ok(Node {
url,
http: reqwest::Client::new(),
password,
token: options.token.clone(),
})
}
fn request(&self, method: reqwest::Method, path: &str) -> Result<reqwest::RequestBuilder> {
let url = self.url.join(path).context("a path of the node's API")?;
let request = self.http.request(method, url);
Ok(match (&self.token, &self.password) {
(Some(token), _) => request.bearer_auth(token),
(None, Some((user, password))) => request.basic_auth(user, password.as_ref()),
(None, None) => request,
})
}
async fn answer(&self, response: reqwest::Response) -> Result<reqwest::Response> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
let body = response.text().await.unwrap_or_default();
if status == reqwest::StatusCode::UNAUTHORIZED
&& self.password.is_none()
&& self.token.is_none()
{
bail!(
"the node answers {status}: {body}. Name a user of it in --node, give --token, \
or --key and --record to log in as the party"
);
}
bail!("the node answers {status}: {body}")
}
/// Logs in as `party` by its key `key` (`POST /auth/login/party`): a party's session,
/// which does federation work alone, its token going with every request then.
async fn log_in(&mut self, party: &str, key: &Signing) -> Result<()> {
let namespace = crate::access::challenge::NAMESPACE;
let asked = async {
let response = self
.request(reqwest::Method::POST, "/auth/challenge")?
.send()
.await?;
let challenge: JsonValue = self.answer(response).await?.json().await?;
let challenge = challenge["challenge"]
.as_str()
.context("the node gives no challenge")?
.to_owned();
let signature = match key {
Signing::File(key) => keys::sign_in(namespace, key, challenge.as_bytes()),
Signing::Agent(key, socket) => {
keys::sign_through_in(namespace, socket, key, challenge.as_bytes())
.map_err(|why| anyhow!(why))?
}
};
let body = serde_json::json!({
"party": party,
"challenge": challenge,
"signature": signature,
});
self.post("/auth/login/party", &body).await
};
let answer = asked.await.with_context(|| {
format!("Logging in as {party} by its key, with no user of the node")
})?;
let token = answer["token"]
.as_str()
.context("the node gives no token")?;
self.token = Some(token.to_owned());
Ok(())
}
async fn get(&self, path: &str) -> Result<JsonValue> {
let response = self.request(reqwest::Method::GET, path)?.send().await?;
Ok(self.answer(response).await?.json().await?)
}
/// The store's ID, and its heads.
async fn summary(&self) -> Result<(Id, Vec<Id>)> {
let summary = self.get("/events").await?;
let store = summary["store"]
.as_str()
.and_then(Id::from_hex)
.context("the node names no store")?;
let heads = summary["heads"]
.as_array()
.into_iter()
.flatten()
.filter_map(|id| id.as_str().and_then(Id::from_hex))
.collect();
Ok((store, heads))
}
async fn counts(&self) -> Result<JsonValue> {
self.get("/events/counts").await
}
async fn current(&self) -> Result<Version> {
current(&self.counts().await?)
}
/// The IDs of the revisions the node knows: none where it says none, as one too old to
/// know the base revision by name.
async fn revisions(&self) -> Result<Vec<Id>> {
let summary = self.get("/events").await?;
Ok(summary["revisions"]
.as_array()
.into_iter()
.flatten()
.filter_map(|revision| revision["id"].as_str().and_then(Id::from_hex))
.collect())
}
/// The bytes of an event the node's store holds.
async fn event(&self, id: &Id) -> Result<Vec<u8>> {
let response = self
.request(reqwest::Method::GET, &format!("/events/{id}"))?
.send()
.await?;
let bytes = self.answer(response).await?.bytes().await?.to_vec();
if Id::of(&bytes) != *id {
bail!("the node's event {id} isn't of that ID");
}
Ok(bytes)
}
async fn post(&self, path: &str, body: &JsonValue) -> Result<JsonValue> {
let response = self
.request(reqwest::Method::POST, path)?
.json(body)
.send()
.await?;
Ok(self.answer(response).await?.json().await?)
}
/// What the node answers to `body`, as bytes.
async fn post_for_bytes(&self, path: &str, body: &JsonValue) -> Result<Vec<u8>> {
let response = self
.request(reqwest::Method::POST, path)?
.json(body)
.send()
.await?;
Ok(self.answer(response).await?.bytes().await?.to_vec())
}
/// What the node answers to the bytes `body`.
async fn post_bytes(&self, path: &str, body: Vec<u8>) -> Result<JsonValue> {
let response = self
.request(reqwest::Method::POST, path)?
.header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
.body(body)
.send()
.await?;
Ok(self.answer(response).await?.json().await?)
}
async fn put(&self, event: &[u8]) -> Result<()> {
let response = self
.request(reqwest::Method::POST, "/events")?
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(event.to_vec())
.send()
.await?;
let answer: JsonValue = self.answer(response).await?.json().await?;
println!(
"{} {}",
answer["id"].as_str().unwrap_or_default(),
answer["event"].as_str().unwrap_or_default()
);
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
fn its_arguments_are_well_formed() {
super::command().debug_assert();
}
/// `propose` and `fork` take a file, or a subcommand saying what the version is for,
/// with their options after it.
#[test]
fn a_version_by_its_file_or_by_what_it_is_for() {
let parsed = |args: &[&str]| {
super::command().try_get_matches_from(["continuum-party"].iter().chain(args))
};
let matches = parsed(&["propose", "next.json", "--yes"]).unwrap();
let (_, propose) = matches.subcommand().unwrap();
assert!(propose.subcommand().is_none());
assert!(super::proposing_flags(propose).get_flag("yes"));
let matches = parsed(&[
"propose", "admit", "makefu", "--keys", "a.pub", "b.pub", "--nodes", "n1", "--yes",
])
.unwrap();
let (_, propose) = matches.subcommand().unwrap();
let (intent, admit) = propose.subcommand().unwrap();
assert_eq!(intent, "admit");
assert_eq!(super::strings(admit, "keys"), ["a.pub", "b.pub"]);
assert_eq!(super::strings(admit, "nodes"), ["n1"]);
assert!(super::proposing_flags(propose).get_flag("yes"));
assert!(!super::proposing_flags(propose).get_flag("print"));
assert!(parsed(&["propose", "checkpoint", "--print"]).is_ok());
assert!(parsed(&["propose"]).is_err());
assert!(parsed(&["propose", "next.json", "admit", "makefu"]).is_err());
let matches = parsed(&["fork", "fork.json"]).unwrap();
let (_, fork) = matches.subcommand().unwrap();
assert!(super::strings(fork, "heads").is_empty());
let matches = parsed(&[
"fork",
"remove",
"lass",
"--at",
"4a1d",
"9e30",
"--founder",
"tv=n1,n2",
])
.unwrap();
let (_, fork) = matches.subcommand().unwrap();
let (intent, remove) = fork.subcommand().unwrap();
assert_eq!(intent, "remove");
assert_eq!(super::strings(remove, "at"), ["4a1d", "9e30"]);
assert_eq!(super::strings(remove, "founder"), ["tv=n1,n2"]);
let matches = parsed(&["fork", "proposal", "8d02"]).unwrap();
let (_, fork) = matches.subcommand().unwrap();
assert_eq!(fork.subcommand_name(), Some("proposal"));
// A fork is at heads of its own: `checkpoint` is a file's name there.
let matches = parsed(&["fork", "checkpoint"]).unwrap();
let (_, fork) = matches.subcommand().unwrap();
assert!(fork.subcommand().is_none());
}
/// `--founder PARTY=NODE,…` names a party's node list anew in a fork's version, `since`
/// its number; one that isn't a party of it, or a node that isn't one, refused.
#[test]
fn founders_name_their_nodes_anew() {
use crate::federation::harness::node_id;
let founder = |given: &str| {
let matches = super::command()
.try_get_matches_from([
"continuum-party",
"fork",
"remove",
"lass",
"--founder",
given,
])
.unwrap();
let (_, fork) = matches.subcommand().unwrap();
let (_, remove) = fork.subcommand().unwrap();
let mut version = serde_json::json!({
"number": 5,
"keys": {"tv": {"since": 0, "keys": []}},
"nodes": {"tv": {"since": 0, "nodes": []}},
});
super::founders(&mut version, remove).map(|()| version)
};
let version = founder(&format!("tv={},{}", node_id(1), node_id(2))).unwrap();
assert_eq!(
version["nodes"]["tv"],
serde_json::json!({"since": 5, "nodes": [node_id(1), node_id(2)]})
);
assert!(founder(&format!("lass={}", node_id(1))).is_err());
assert!(founder("tv=elsewhere").is_err());
assert!(founder("tv").is_err());
}
/// `--key` gives a public key itself, or the first of a file's with how many more it
/// holds, or a private key file's key; a file of neither, or none, gives nothing.
#[test]
fn the_key_given() {
use super::{Given, given_key};
use crate::federation::vectors::ECDSA_KEY;
let ed25519 = crate::federation::harness::key_line(1);
let dir = crate::files::scratch_dir("party-key");
let file = |name: &str, text: &str| {
let path = dir.join(name);
std::fs::write(&path, text).unwrap();
path.to_str().unwrap().to_owned()
};
let public = |given: &str| match given_key(given).unwrap() {
Given::Public(key, more) => (key.line(), more),
Given::Private(_) => panic!("{given}: a private key"),
};
assert_eq!(public(ECDSA_KEY), (ECDSA_KEY.to_owned(), 0));
assert_eq!(
public(&format!("{ed25519} tv@laptop")),
(ed25519.clone(), 0)
);
let one = file("phone.pub", &format!("{ECDSA_KEY} tv@phone\n"));
assert_eq!(public(&one), (ECDSA_KEY.to_owned(), 0));
let two = file(
"agent.pub",
&format!("{ed25519} tv@laptop\n\n{ECDSA_KEY} tv@phone\n"),
);
assert_eq!(public(&two), (ed25519, 1));
assert!(given_key(&file("rsa.pub", "ssh-rsa AAAAB3NzaC1yc2E tv\n")).is_err());
assert!(given_key(&file("empty.pub", "\n")).is_err());
assert!(given_key(dir.join("missing").to_str().unwrap()).is_err());
let private = file(
"tv.key",
"-----BEGIN OPENSSH PRIVATE KEY-----\n-----END OPENSSH PRIVATE KEY-----\n",
);
let why = given_key(&private).err().expect("no key").to_string();
assert!(why.contains("OpenSSH private key"), "{why}");
}
/// A key set or node list changed as it counts: each item added absent, each taken off
/// held; set whole, it is as set, none twice; left empty only by force.
#[test]
fn a_list_changed_as_it_counts() {
use super::changed;
let list = |items: &[&str]| -> Vec<String> {
items.iter().map(|item| (*item).to_owned()).collect()
};
let now = list(&["a", "b"]);
let changed_by = |set: Option<&[&str]>, add: &[&str], remove: &[&str], force: bool| {
let set = set.map(list);
let (add, remove) = (list(add), list(remove));
changed(
now.clone(),
set,
add,
remove,
force,
"tv's list",
"nothing left",
)
};
assert_eq!(
changed_by(Some(&["c"]), &[], &[], false).unwrap(),
list(&["c"])
);
assert_eq!(
changed_by(None, &["c"], &["a"], false).unwrap(),
list(&["b", "c"])
);
assert!(changed_by(None, &["a"], &[], false).is_err());
assert!(changed_by(None, &[], &["c"], false).is_err());
assert!(changed_by(Some(&["c", "c"]), &[], &[], false).is_err());
assert!(changed_by(None, &[], &["a", "b"], false).is_err());
assert!(changed_by(Some(&[]), &[], &[], false).is_err());
assert_eq!(changed_by(None, &[], &["a", "b"], true).unwrap(), list(&[]));
assert_eq!(changed_by(Some(&[]), &[], &[], true).unwrap(), list(&[]));
}
/// The federation the client works with: the one `--federation` names; else, without
/// `--config`, the only one there is; none where there is none; and an error where
/// there are several. `init` begins one, with the options given on the command line.
#[test]
fn the_federation_is_the_one_there_is_or_the_one_named() {
let all = crate::files::scratch_dir("party-federations");
let matches = |args: &[&str]| {
super::command()
.try_get_matches_from(["continuum-party"].iter().chain(args).chain(&["proposals"]))
.unwrap()
};
let chosen = |args: &[&str]| super::federation(&matches(args), Some(&all));
assert_eq!(chosen(&[]).unwrap(), None);
std::fs::create_dir(all.join("krebs")).unwrap();
assert_eq!(chosen(&[]).unwrap(), Some(all.join("krebs")));
assert_eq!(chosen(&["--config", "x.toml"]).unwrap(), None);
std::fs::create_dir(all.join("test")).unwrap();
let several = chosen(&[]).unwrap_err().to_string();
assert!(several.contains("krebs, test"), "{several}");
assert_eq!(
chosen(&["--federation", "test"]).unwrap(),
Some(all.join("test"))
);
assert!(chosen(&["--federation", "../x"]).is_err());
assert_eq!(super::federation(&matches(&[]), None).unwrap(), None);
// Begun with the options given on the command line, the default node left out.
let begun = all.join("new");
super::begin_federation(&begun, &matches(&["--token", "t"])).unwrap();
let written = std::fs::read_to_string(begun.join("party.toml")).unwrap();
assert_eq!(written.trim(), r#"token = "t""#);
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(begun.join("party.toml"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
/// Votes, proposals, key sets and node lists are signed with a key the current version
/// names for their party; another key, or a party the version doesn't have, is refused
/// before signing.
#[test]
fn what_only_a_versions_keys_sign_is_signed_with_one() {
use super::{Signer, Signing};
use crate::federation::harness::{Party, Spec};
use crate::federation::version::Version;
let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2));
let current = Version::read(&Spec::first(&[&tv, &lass], &[]).json()).unwrap();
let signer = |key: &Party, party: &str| Signer {
key: Signing::File(key.key.clone()),
party: party.to_owned(),
};
assert!(signer(&tv, "tv").named_by(¤t).is_ok());
assert!(signer(&lass, "tv").named_by(¤t).is_err());
let makefu = Party::new("makefu", 3);
assert!(signer(&makefu, "makefu").named_by(¤t).is_err());
}
/// The next version is the current one numbered on, naming its hash, without its
/// checkpoint: a version changing it, as its parties may pass. With a feature, it
/// follows the revision adding it, never an earlier one than the current version's.
#[test]
fn the_next_version_changes_the_current_one() {
use crate::federation::harness::{Party, Spec};
use crate::federation::revision::{Feature, Revision};
use crate::federation::store::Id;
use crate::federation::version::Version;
let first = Spec::first(&[&Party::new("tv", 1), &Party::new("lass", 2)], &[]);
let mut second = first.after(first.hash());
second.checkpoint = Some(vec![Id::of(b"a head")]);
let current = Version::read(&second.json()).unwrap();
let next = super::next(¤t, None).unwrap();
assert_eq!(next["number"], current.number + 1);
assert_eq!(next["changes"], current.hash.to_string());
assert!(next.get("checkpoint").is_none());
assert!(next.get("revision").is_none());
let next = Version::read(&crate::federation::client::json(&next).unwrap()).unwrap();
next.changes_validly(Some(¤t)).unwrap();
let revised = super::next(¤t, Some("merge-events")).unwrap();
let revised = Version::read(&crate::federation::client::json(&revised).unwrap()).unwrap();
assert_eq!(revised.revision, Feature::MergeEvents.revision());
revised.changes_validly(Some(¤t)).unwrap();
// Kept on, where nothing is said.
let kept = super::next(&revised, None).unwrap();
let kept = Version::read(&crate::federation::client::json(&kept).unwrap()).unwrap();
assert_eq!(kept.revision, revised.revision);
let why = super::next(¤t, Some("elsewhere"))
.unwrap_err()
.to_string();
assert!(why.contains("merge-events"), "{why}");
assert_ne!(revised.revision, Revision::default());
}
/// A change by what it is for makes the next version so: a party let in or taken out
/// (its rules with it), a place given (first, the rule of its path before gone) or
/// taken (to nobody, where another rule still gives it), keys and nodes named anew
/// `since` its number, a checkpoint at heads, a revision; each a version the parties
/// may pass, and a party named that isn't one, or one let in that is, refused.
#[test]
fn a_change_by_what_it_is_for() {
use super::{Intent, intended};
use crate::federation::client;
use crate::federation::harness::{Party, Spec, node_id, str};
use crate::federation::store::Id;
use crate::federation::version::Version;
let (tv, lass, makefu) = (
Party::new("tv", 1),
Party::new("lass", 2),
Party::new("makefu", 3),
);
// Rules: home/{party}/** (as every first version the harness spells), then these.
let current = Version::read(
&Spec::first(
&[&tv, &lass],
&[("names/r/wiki", str("lass")), ("names/**", str("tv"))],
)
.json(),
)
.unwrap();
let made = |intent: Intent| -> Version {
let next = intended(¤t, &intent).unwrap();
client::backable(¤t, &client::json(&next).unwrap()).unwrap()
};
let rules = |version: &Version| -> Vec<String> {
let json: serde_json::Value = serde_json::from_slice(&version.json.bytes()).unwrap();
json["rules"]
.as_array()
.unwrap()
.iter()
.map(|rule| format!("{} {}", rule["path"].as_str().unwrap(), rule["writer"]))
.collect()
};
let admitted = made(Intent::Admit {
party: "makefu".to_owned(),
keys: vec![makefu.key_line()],
nodes: vec![node_id(3)],
});
let given = &admitted.parties["makefu"];
assert_eq!((given.keys_since, given.nodes_since), (1, 1));
assert_eq!(given.nodes, [node_id(3)]);
assert!(
intended(
¤t,
&Intent::Admit {
party: "tv".to_owned(),
keys: vec![tv.key_line()],
nodes: Vec::new(),
},
)
.is_err()
);
let removed = made(Intent::Remove("lass".to_owned()));
assert!(!removed.parties.contains_key("lass"));
assert!(!rules(&removed).iter().any(|rule| rule.contains("\"lass\"")));
assert!(intended(¤t, &Intent::Remove("makefu".to_owned())).is_err());
let given = made(Intent::Give {
path: "names/r/wiki".to_owned(),
writer: "tv".to_owned(),
});
assert_eq!(rules(&given)[0], r#"names/r/wiki "tv""#);
assert_eq!(rules(&given).len(), 3);
let zone = made(Intent::Give {
path: "names/r/{party}".to_owned(),
writer: "{party}".to_owned(),
});
assert_eq!(rules(&zone)[0], r#"names/r/{party} "{party}""#);
assert!(
intended(
¤t,
&Intent::Give {
path: "x".to_owned(),
writer: "makefu".to_owned()
}
)
.is_err()
);
// names/** still gives names/r/wiki once its rule goes: to nobody, first.
let taken = made(Intent::Take("names/r/wiki".to_owned()));
assert_eq!(rules(&taken)[0], "names/r/wiki false");
assert_eq!(
taken.writer(&["names".into(), "r".into(), "wiki".into()]),
None
);
// Every place names/** matches, lass's wiki among them.
let taken = made(Intent::Take("names/**".to_owned()));
assert_eq!(rules(&taken)[0], "names/** false");
assert_eq!(rules(&taken).len(), 3);
// Given by its own rule alone: that rule goes.
let taken = made(Intent::Take("home/{party}/**".to_owned()));
assert_eq!(rules(&taken).len(), 2);
assert!(intended(¤t, &Intent::Take("ip4/10".to_owned())).is_err());
let keys = made(Intent::Keys {
party: "tv".to_owned(),
keys: vec![makefu.key_line()],
});
assert_eq!(keys.parties["tv"].keys, [makefu.key_line()]);
assert_eq!(keys.parties["tv"].keys_since, 1);
let nodes = made(Intent::Nodes {
party: "lass".to_owned(),
nodes: vec![node_id(5)],
});
assert_eq!(nodes.parties["lass"].nodes_since, 1);
let (a, b) = (Id::of(b"a"), Id::of(b"b"));
let moved = made(Intent::Checkpoint(vec![b, a, b]));
let mut heads = vec![a, b];
heads.sort();
assert_eq!(moved.checkpoint, Some(heads));
assert!(moved.only_moves_on(¤t));
let revised = made(Intent::Revision("merge-events".to_owned()));
assert_ne!(revised.revision, current.revision);
}
/// `found` writes a first version from the parties' keys, node lists and rules: each
/// party writing under `home/{party}/` where no rule is given; one rooting a
/// federation, as `root` takes it.
#[test]
fn a_first_version_founded() {
use crate::federation::harness::{Party, node_id};
use crate::federation::version::Version;
let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2));
let dir = crate::files::scratch_dir("party-found");
let lass_file = dir.join("lass.pub");
std::fs::write(&lass_file, format!("{} lass@host\n", lass.key_line())).unwrap();
let founded = |args: &[String]| {
let matches = super::command()
.try_get_matches_from(
["continuum-party", "found"]
.into_iter()
.map(str::to_owned)
.chain(args.iter().cloned()),
)
.unwrap();
let (_, found) = matches.subcommand().unwrap();
super::founded(found)
};
let tv_key = format!("tv={}", tv.key_line());
let lass_key = format!("lass={}", lass_file.display());
let version = founded(&[
tv_key.clone(),
lass_key.clone(),
"--nodes".to_owned(),
format!("tv={},{}", node_id(1), node_id(2)),
])
.unwrap();
assert_eq!(version["number"], 0);
assert_eq!(version["keys"]["lass"]["keys"][0], lass.key_line().as_str());
assert_eq!(version["nodes"]["tv"]["nodes"][1], node_id(2).as_str());
assert_eq!(version["nodes"]["lass"]["nodes"], serde_json::json!([]));
assert_eq!(
version["rules"],
serde_json::json!([{"path": "home/{party}/**", "writer": "{party}"}])
);
let json = crate::federation::client::json(&version).unwrap();
Version::read(&json).unwrap().changes_validly(None).unwrap();
let ruled = founded(&[
tv_key.clone(),
"--rule".to_owned(),
"names/r/wiki=tv".to_owned(),
"--rule".to_owned(),
"names/**=nobody".to_owned(),
"--revision".to_owned(),
"merge-events".to_owned(),
])
.unwrap();
assert_eq!(ruled["rules"][1]["writer"], false);
assert!(ruled.get("revision").is_some());
assert!(founded(&[tv_key.clone(), tv_key.clone()]).is_err());
assert!(
founded(&[
tv_key.clone(),
"--nodes".to_owned(),
format!("lass={}", node_id(2))
])
.is_err()
);
assert!(founded(&[tv_key, "--rule".to_owned(), "names/r/wiki=lass".to_owned()]).is_err());
}
/// The party the client works as: `init`'s, the record's, else `--party`; `--party`
/// naming another is an error.
#[test]
fn the_party_it_works_as() {
use crate::federation::client::Record;
use crate::federation::store::Id;
let dir = crate::files::scratch_dir("party-working-as");
let record = dir.join("tv.record");
Record::before(Id::of(b"a root"), "tv")
.save(&record)
.unwrap();
let working_as = |args: &[&str], record: Option<&std::path::Path>, party: Option<&str>| {
let matches = super::command()
.try_get_matches_from(["continuum-party"].iter().chain(args))
.unwrap();
let (name, sub) = matches.subcommand().unwrap();
let options = super::Options {
node: super::default_node(),
token: None,
key: None,
record: record.map(|path| path.display().to_string()),
party: party.map(str::to_owned),
};
super::working_as(name, sub, &options)
};
assert_eq!(
working_as(&["init", "tv"], None, None).unwrap().as_deref(),
Some("tv")
);
assert!(working_as(&["init", "tv"], None, Some("lass")).is_err());
assert_eq!(
working_as(&["status"], Some(&record), None)
.unwrap()
.as_deref(),
Some("tv")
);
assert!(working_as(&["status"], Some(&record), Some("lass")).is_err());
assert_eq!(
working_as(&["status"], Some(&dir.join("none")), Some("lass"))
.unwrap()
.as_deref(),
Some("lass")
);
assert_eq!(working_as(&["status"], None, None).unwrap(), None);
}
/// `status` says a party's keys and nodes a line each: the version's, its key set's
/// where they differ, `--key`'s marked, and each node with the name it gave itself.
#[test]
fn a_partys_keys_and_nodes_a_line_each() {
use crate::federation::client::fingerprint;
use crate::federation::harness::{key_line, node_id};
let (named, laptop) = (key_line(1), key_line(2));
let counts = serde_json::json!({"parties": {"tv": {
"keys": [laptop],
"nodes": [node_id(1), node_id(2)],
"names": {node_id(1): "alpha"},
}}});
let dir = crate::files::scratch_dir("party-lines");
let given = dir.join("laptop.pub");
std::fs::write(&given, format!("{laptop} tv@laptop\n")).unwrap();
let lines = super::party_lines(&counts, "tv", std::slice::from_ref(&named), given.to_str());
assert_eq!(
lines,
[
"keys the version names (votes, proposals, key set, node list):".to_owned(),
format!(" {}", fingerprint(&named)),
"keys of its key set (writes):".to_owned(),
format!(" {} (--key)", fingerprint(&laptop)),
"nodes:".to_owned(),
format!(" {} (alpha)", node_id(1)),
format!(" {}", node_id(2)),
]
);
let lines = super::party_lines(&counts, "tv", std::slice::from_ref(&laptop), None);
assert_eq!(lines[2], "keys of its key set (writes): the same");
}
/// `get` reads what counts as JSON: a place's value; what lies under a path, places and
/// the values within theirs, as one object; a list's item by its index; a deeper place
/// winning over what a value above it held there.
#[test]
fn what_counts_as_json() {
use serde_json::json;
let values = json!({
"home/tv/motd": "hello",
"home/tv/hosts/laptop": {"ip6": "42::1", "ports": [22, 80]},
"home/tv/hosts": {"desk": {"ip6": "42::2"}, "laptop": {"ip6": "old"}},
"home/lass/motd": "hi",
"home/tvx/motd": "beside",
});
let values = values.as_object().unwrap();
let get = |path: &str| super::at(&super::tree(values, path), path).cloned();
assert_eq!(get("home/tv/motd"), Some(json!("hello")));
assert_eq!(
get("home/tv"),
Some(json!({
"motd": "hello",
"hosts": {
"desk": {"ip6": "42::2"},
"laptop": {"ip6": "42::1", "ports": [22, 80]},
},
}))
);
assert_eq!(get("home/tv/hosts/desk/ip6"), Some(json!("42::2")));
assert_eq!(get("home/tv/hosts/laptop/ports/1"), Some(json!(80)));
assert_eq!(get("home/tv/hosts/laptop/ports/2"), None);
assert_eq!(get("home/tv/elsewhere"), None);
assert_eq!(get("home").unwrap()["lass"], json!({"motd": "hi"}));
assert_eq!(get("").unwrap()["home"]["tvx"]["motd"], "beside");
}
/// Before a vote, the party's votes the node shows are held against the record's: one
/// the node shows that the record lacks refuses the vote, one the record holds that
/// the node doesn't show is said; nothing where they agree.
#[test]
fn a_record_held_against_the_votes_a_node_shows() {
use crate::federation::client::Record;
use crate::federation::harness::{Party, Spec};
use crate::federation::store::Id;
use crate::federation::version::Version;
let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2));
let first = Spec::first(&[&tv, &lass], &[]);
let current = Version::read(&first.json()).unwrap();
let (one, two) = (Id::of(b"one"), Id::of(b"two"));
let mut record = Record::before(Id::of(b"root"), "tv");
record.cast(
¤t,
&tv.vote(&[Id::of(b"root")], first.hash(), one, true),
Vec::new(),
);
let counts = |yes_one: &[&str], no_two: &[&str]| {
serde_json::json!({"proposals": {
one.to_string(): {"yes": yes_one, "no": []},
two.to_string(): {"yes": [], "no": no_two},
}})
};
let agreeing = counts(&["tv", "lass"], &[]);
assert_eq!(
super::unrecorded(&agreeing, ¤t, &record),
(Vec::new(), Vec::new())
);
assert!(super::consistent(&agreeing, ¤t, &record).is_ok());
let elsewhere = counts(&["tv"], &["tv"]);
let (theirs, ours) = super::unrecorded(&elsewhere, ¤t, &record);
assert_eq!(theirs.len(), 1);
assert!(theirs[0].starts_with("`false` on "), "{theirs:?}");
assert!(ours.is_empty());
assert!(super::consistent(&elsewhere, ¤t, &record).is_err());
let behind = counts(&["lass"], &[]);
let (theirs, ours) = super::unrecorded(&behind, ¤t, &record);
assert!(theirs.is_empty());
assert_eq!(ours.len(), 1);
assert!(super::consistent(&behind, ¤t, &record).is_ok());
}
/// What may keep a vote from the node: the party's own nodes not heard from lately;
/// and parties none of whose nodes were, where they are a third of those with nodes.
#[test]
fn nodes_cut_off_are_said() {
let ago = super::LATELY + 1;
let counts = |lass_heard: Option<u64>| {
let lass = match lass_heard {
Some(ago) => serde_json::json!({"n3": ago}),
None => serde_json::json!({}),
};
serde_json::json!({"parties": {
"tv": {"nodes": ["n1", "n2"], "names": {"n2": "beta"}, "heard": {"n1": 0, "n2": ago}},
"lass": {"nodes": ["n3"], "names": {}, "heard": lass},
"makefu": {"nodes": ["n4"], "names": {}, "heard": {"n4": 3}},
"krebs": {"nodes": [], "names": {}, "heard": {}},
}})
};
let lines = super::cut_off(&counts(Some(10)), "tv");
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("n2 (beta)"), "{lines:?}");
let lines = super::cut_off(&counts(None), "makefu");
assert_eq!(lines.len(), 1);
assert!(lines[0].contains("any node of lass"), "{lines:?}");
assert!(super::cut_off(&counts(Some(10)), "makefu").is_empty());
}
/// `values` shows a place and those under it, not those beside it.
#[test]
fn places_under_a_path() {
use super::is_under;
assert!(is_under("home/tv/motd", None));
assert!(is_under("home/tv/motd", Some("home/tv")));
assert!(is_under("home/tv", Some("home/tv")));
assert!(!is_under("home/tvx/motd", Some("home/tv")));
assert!(!is_under("home", Some("home/tv")));
}
/// Two rule paths overlap where some path matches both.
#[test]
fn rule_paths_overlap() {
let path = |text: &str| crate::federation::version::path(text).unwrap();
let overlaps = |a: &str, b: &str| super::overlaps(&path(a), &path(b));
assert!(overlaps("names/r/wiki", "names/**"));
assert!(overlaps("names/r/*", "names/r/wiki"));
assert!(overlaps("home/{party}/**", "home/tv/motd"));
assert!(!overlaps("names/r/wiki", "names/r/wiki/x"));
assert!(!overlaps("names/**", "names"));
assert!(!overlaps("names/r/wiki", "home/**"));
assert!(overlaps("a/**", "a/b/**"));
}
/// Its options come from configuration files as the node's do, arguments winning.
#[test]
fn its_options_come_from_configuration_files_and_arguments() {
use crate::config;
let dir = crate::files::scratch_dir("party-config");
let file = dir.join("party.toml");
std::fs::write(
&file,
"node = \"http://tv:secret@localhost:3001\"\nkey = \"tv.key\"\nrecord = \"tv.record\"\n",
)
.unwrap();
let path = file.to_str().unwrap();
let matches = super::command()
.try_get_matches_from([
"continuum-party",
"--config",
path,
"--key",
"laptop.key",
"proposals",
])
.unwrap();
let (merged, _) = config::merged(&matches, config::PARTY_OPTIONS).unwrap();
let options: super::Options = config::read(&merged).unwrap();
assert_eq!(options.node, "http://tv:secret@localhost:3001");
assert_eq!(options.key.as_deref(), Some("laptop.key"));
assert_eq!(options.record.as_deref(), Some("tv.record"));
assert_eq!(options.token, None);
// A key naming none of the client's options is an error, as in the node's files.
std::fs::write(&file, "bind-addr = \"127.0.0.1:3000\"\n").unwrap();
assert!(config::merged(&matches, config::PARTY_OPTIONS).is_err());
}
}
|