ava1 1.0.1

AVA1: an encrypted, resumable, multi-lane file-transfer protocol (client and node), designed for sending files to a PlayStation 5, with a C implementation tested against it
Documentation
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
//! The AVA1 core messages, structs and constants (SPEC.md §3).
//!
//! Generated by ava1-gen from `schema/ava1.toml`. Do not edit:
//! run `cargo run -p ava1-gen` after changing the schema.
#![allow(clippy::field_reassign_with_default, clippy::single_match, clippy::match_single_binding)]

use crate::wire::{DecodeError, EncodeError, FrameMessage, Message, Reader, SplitMix, Writer};

/// The protocol version this code speaks: the range in `HelloInfo` and the choice in `ServerInfo` (SPEC.md §5).
pub const PROTOCOL_VERSION: u16 = 1;
/// The TCP port a node listens on unless its application picks another (SPEC.md §1).
pub const DEFAULT_PORT: u16 = 9120;
/// Data lanes per session; lane ids are 1..=8, lane 0 is the control connection (SPEC.md §1, §9).
pub const MAX_LANES: u8 = 8;
/// RPC `node.info`: empty request, `NodeInfo` reply (SPEC.md §7.1).
pub const METHOD_NODE_INFO: u16 = 1;
/// RPC `pairing.open`: `PairingOpen` request, empty reply; opens the pairing window (SPEC.md §5, §7.1).
pub const METHOD_PAIRING_OPEN: u16 = 2;
/// RPC `crypto.bench`: `CryptoBench` request, `CryptoBenchResult` reply; a diagnostic (SPEC.md §7.1).
pub const METHOD_CRYPTO_BENCH: u16 = 3;
/// `RpcResponse.status` (and job status) for success (SPEC.md §7).
pub const STATUS_OK: u16 = 0;
/// An RPC or a lane join from a session whose pairing is not accepted (SPEC.md §5, §7.2).
pub const ERR_NOT_PAIRED: u16 = 1;
/// An unknown client while the pairing window is closed, or an unconfirmed session whose window or 60 s ended (SPEC.md §5, §7.2).
pub const ERR_PAIRING_CLOSED: u16 = 2;
/// The two peers' version ranges do not overlap; sent unsealed (SPEC.md §5, §7.2).
pub const ERR_UNSUPPORTED_VERSION: u16 = 3;
/// A frame or body that does not decode or is not allowed where it arrived, or a request the protocol forbids (SPEC.md §7.2).
pub const ERR_PROTOCOL: u16 = 4;
/// A `Join` for an unknown session, a lane id outside 1..=8, a wrong tag or a replayed nonce (SPEC.md §9, §7.2).
pub const ERR_BAD_JOIN: u16 = 5;
/// A method the node does not serve (SPEC.md §7.2, §7.3).
pub const ERR_UNKNOWN_METHOD: u16 = 6;
/// The node failed for a reason that is neither the peer's nor the disk's, such as out of memory (SPEC.md §7.2).
pub const ERR_INTERNAL: u16 = 7;
/// A limit was reached (connections, sessions, in-flight RPCs, jobs, a destination in use, buffer budget); retry later (SPEC.md §7.2, §8).
pub const ERR_BUSY: u16 = 8;
/// `ServerInfo.caps` bit: the node hosts the data plane, jobs and methods 16–19 (SPEC.md §5 step 2).
pub const CAP_DATA_PLANE: u64 = 1;
/// `ServerInfo.caps` bit: the node serves the methods 4 and up other than 16–19, among them `job.run`, `job.list` and the application's (SPEC.md §5 step 2, §7.3).
pub const CAP_MGMT: u64 = 2;
/// `ServerInfo.caps` bit: any paired device may read and cancel a transfer and take over a parked upload (SPEC.md §18.5).
pub const CAP_SHARED_JOBS: u64 = 4;
/// RPC `job.copy`: `JobCopy` request, `Status` reply; a copy or move on the node itself (SPEC.md §7.1, §15.5).
pub const METHOD_JOB_COPY: u16 = 16;
/// RPC `job.status`: `JobRef` request, `Status` reply (SPEC.md §7.1).
pub const METHOD_JOB_STATUS: u16 = 17;
/// RPC `job.cancel`: `JobRef` request, empty reply (SPEC.md §7.1, §11.7).
pub const METHOD_JOB_CANCEL: u16 = 18;
/// RPC `disk.calibrate`: `DiskCalibrate` request, `DiskCalibrateResult` reply (SPEC.md §16.10).
pub const METHOD_DISK_CALIBRATE: u16 = 19;
/// RPC `c2c.allow`, on the receiving node: `C2cAllow` request, `C2cTicket` reply; admits one job from another node (SPEC.md §18.1).
pub const METHOD_C2C_ALLOW: u16 = 22;
/// RPC `c2c.send`, on the sending node: `C2cSend` request, `Status` reply; sends to another node directly (SPEC.md §18.2).
pub const METHOD_C2C_SEND: u16 = 23;
/// A path that breaks SPEC.md §11.2, a root the node's policy refuses, or a source or staging parent that cannot be used (SPEC.md §7.2).
pub const ERR_PATH: u16 = 9;
/// The destination drive is full (SPEC.md §7.2).
pub const ERR_NO_SPACE: u16 = 10;
/// A job the node does not list, or lists for another peer key (SPEC.md §7.2).
pub const ERR_UNKNOWN_JOB: u16 = 11;
/// A disk or filesystem failure on the node's side (SPEC.md §7.2).
pub const ERR_IO: u16 = 12;
/// Bytes that do not match their root and that a `FileRetry` cannot fix (SPEC.md §7.2).
pub const ERR_VERIFY: u16 = 13;
/// A destination that already exists and may not be replaced (SPEC.md §7.2).
pub const ERR_EXISTS: u16 = 14;
/// The job was cancelled (SPEC.md §7.2).
pub const ERR_CANCELLED: u16 = 15;
/// A rename whose two sides are on different devices; never attempted (SPEC.md §7.2).
pub const ERR_CROSS_DEVICE: u16 = 16;
/// A lane frame larger than the credit the receiver granted (SPEC.md §12.4).
pub const ERR_CREDIT: u16 = 17;
/// The receiver ended a job whose sender kept the link alive but sent no file data (SPEC.md §12.8).
pub const ERR_STALLED: u16 = 18;
/// Client side: the node refused the typed pairing code, or could not prove it knows it (SPEC.md §5.5, §7.2).
pub const ERR_PAIRING_CODE: u16 = 19;
/// Job kind: the node that receives the `JobOpen` receives the files (SPEC.md §11.3).
pub const JOB_UPLOAD: u8 = 1;
/// Job kind: the node that receives the `JobOpen` sends the files (SPEC.md §11.3).
pub const JOB_DOWNLOAD: u8 = 2;
/// Job kind: the node copies `src` to the root locally (`job.copy`, SPEC.md §11.3, §15.5).
pub const JOB_COPY: u8 = 3;
/// Job policy: send everything the receiver's map does not list (SPEC.md §11.4).
pub const POLICY_REPLACE: u8 = 0;
/// Job policy: the receiver marks a file done when one of the same size and mtime seconds exists (SPEC.md §11.4).
pub const POLICY_SKIP_EXISTING: u8 = 1;
/// Job policy: the receiver marks a file done when an existing file of the same size hashes to the root in `ManifestEntry.root` (SPEC.md §11.4).
pub const POLICY_VERIFY: u8 = 2;
/// Job flag: the root is a file path and the manifest has one file entry (SPEC.md §11.8).
pub const JF_SINGLE_FILE: u32 = 1;
/// Job flag: the receiver consumes the files in manifest order, as a download into a zip (SPEC.md §11.8).
pub const JF_ORDERED: u32 = 2;
/// Job flag: the sender may read outside the roots its read policy allows, such as system files (SPEC.md §11.8).
pub const JF_UNSAFE_READ: u32 = 4;
/// Job flag, `job.copy` only: delete each source file once its copy is durable (SPEC.md §11.8).
pub const JF_MOVE: u32 = 8;
/// Job flag, `job.copy` only: replace destination files that already exist; unset, an existing destination root is refused with `ERR_EXISTS` (SPEC.md §11.8).
pub const JF_OVERWRITE: u32 = 16;
/// `ManifestEntry.kind`: a file (SPEC.md §11.3).
pub const ENTRY_FILE: u8 = 0;
/// `ManifestEntry.kind`: a directory (SPEC.md §11.3).
pub const ENTRY_DIR: u8 = 1;
/// log2 of the verification group size: files are hashed in groups of 1 MiB (SPEC.md §13.1).
pub const GROUP_SHIFT: u8 = 20;
/// Bytes: a file of at least this size is a large file and travels in `Chunk`s; smaller files
/// travel whole as `BundleRecord`s. A protocol constant both sides use (SPEC.md §12.2).
pub const LARGE_CUTOFF: u32 = 262144;
/// Bottleneck: none reported yet (SPEC.md §16).
pub const BN_NONE: u8 = 0;
/// Bottleneck: the network (SPEC.md §16).
pub const BN_NETWORK: u8 = 1;
/// Bottleneck: the sender's source reads (SPEC.md §16).
pub const BN_SOURCE: u8 = 2;
/// Bottleneck: the receiver's disk; its workers are at their maximum or adding one did not help (SPEC.md §16.9).
pub const BN_DISK: u8 = 3;
/// Bottleneck: the receiver's workers, while it is still adding them (SPEC.md §16.9).
pub const BN_WORKERS: u8 = 4;
/// Bottleneck: the sender waits for credit and the receiver reported no bottleneck of its own (SPEC.md §16).
pub const BN_CREDIT: u8 = 5;
/// `FileRetry.reason`: the file's root did not match (SPEC.md §11.9).
pub const RETRY_VERIFY: u16 = 1;
/// `FileRetry.reason`: the receiver lost the part file or outboard (SPEC.md §11.9).
pub const RETRY_IO: u16 = 2;
/// `FileRetry.reason`: the record's length disagrees with the manifest (SPEC.md §11.9).
pub const RETRY_CHANGED: u16 = 3;
/// RPC `job.run`: `JobRun` request, `Status` reply; starts an application operation as a job (SPEC.md §7.1.1).
pub const METHOD_JOB_RUN: u16 = 20;
/// RPC `job.list`: empty request, `JobListResult` reply (SPEC.md §7.1.1).
pub const METHOD_JOB_LIST: u16 = 21;
/// The largest `MgmtText` text in a reply, in bytes: the 256 KiB reply cap minus 16 (SPEC.md §7.3).
pub const RPC_TEXT_MAX: u32 = 262128;

/// Handshake step 1, client to node, unsealed (SPEC.md §5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Hs1 {
    /// Noise XX message 1; its payload is a `HelloInfo`, in plaintext.
    pub noise: Vec<u8>,
}

impl Message for Hs1 {
    const NAME: &'static str = "Hs1";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.bytes(&self.noise)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.noise = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Hs1 {
    const TYPE: u8 = 0x01;
}

/// Handshake step 2, node to client (SPEC.md §5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Hs2 {
    /// Noise XX message 2; its payload is a `ServerInfo`, encrypted.
    pub noise: Vec<u8>,
}

impl Message for Hs2 {
    const NAME: &'static str = "Hs2";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.bytes(&self.noise)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.noise = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Hs2 {
    const TYPE: u8 = 0x02;
}

/// Handshake step 3, client to node; every later frame on lane 0 is sealed (SPEC.md §5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Hs3 {
    /// Noise XX message 3; its payload is a `ClientInfo`, encrypted.
    pub noise: Vec<u8>,
}

impl Message for Hs3 {
    const NAME: &'static str = "Hs3";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.bytes(&self.noise)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.noise = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Hs3 {
    const TYPE: u8 = 0x03;
}

/// The node's first sealed frame, after `Hs3`: whether it knows the client's key (SPEC.md §5 step 4).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Welcome {
    /// Nonzero when the node already trusts the client's key (or a ticket admits it, SPEC.md §18.2); 0 means the client must pair.
    pub knows_you: u8,
    /// The reveal of `ServerInfo.pair_commit`: BLAKE2b-256 of it must equal that commit (SPEC.md §4.6). Required, so it cannot be stripped.
    pub nonce_s: [u8; 16],
    /// Proof of the launch token, sent only to the key in this node's trust slot when the slot carries a token (SPEC.md §5.2). Older clients skip it.
    pub launch_proof: Option<[u8; 16]>,
}

impl Message for Welcome {
    const NAME: &'static str = "Welcome";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u8(self.knows_you);
        w.fixed(&self.nonce_s);
        let mut ext_n: u16 = 0;
        if self.launch_proof.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.launch_proof { w.ext(1, |w| { w.fixed(v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.knows_you = r.u8()?;
        m.nonce_s = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.launch_proof.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.launch_proof = Some(vr.fixed::<16>()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Welcome {
    const TYPE: u8 = 0x04;
}

/// Pairing step 1, client to node: the client's CPace public value (SPEC.md §4.6, §5.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairPakeClient {
    /// `X25519(x, G)` for a fresh scalar x, with G derived from the handshake hash and the code.
    pub y: [u8; 32],
}

impl Message for PairPakeClient {
    const NAME: &'static str = "PairPakeClient";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.y);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.y = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for PairPakeClient {
    const TYPE: u8 = 0x0d;
}

/// Pairing step 2, node to client: the node's CPace public value (SPEC.md §4.6, §5.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairPakeServer {
    /// `X25519(x, G)` for the node's fresh scalar x.
    pub y: [u8; 32],
}

impl Message for PairPakeServer {
    const NAME: &'static str = "PairPakeServer";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.y);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.y = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for PairPakeServer {
    const TYPE: u8 = 0x0e;
}

/// Pairing step 3, client to node: the client's key confirmation (SPEC.md §4.6, §5.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairConfirm {
    /// Keyed BLAKE2b-256(key = K, "client" || h). Required.
    pub mac: [u8; 32],
}

impl Message for PairConfirm {
    const NAME: &'static str = "PairConfirm";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.mac);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.mac = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for PairConfirm {
    const TYPE: u8 = 0x05;
}

/// Pairing step 4, node to client: the outcome; the session ends unless accepted (SPEC.md §4.6, §5.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairResult {
    /// 1 when the node verified the client's `mac` and stored its key, else 0.
    pub accepted: u8,
    /// Keyed BLAKE2b-256(key = K, "server" || h) when accepted, else zero: the node's key confirmation, which the client checks before it stores the node.
    pub mac: [u8; 32],
}

impl Message for PairResult {
    const NAME: &'static str = "PairResult";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u8(self.accepted);
        w.fixed(&self.mac);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.accepted = r.u8()?;
        m.mac = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for PairResult {
    const TYPE: u8 = 0x06;
}

/// Opens a data lane: the first frame on a new connection, client to node, unsealed (SPEC.md §9).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Join {
    /// The session's id, from `ServerInfo`.
    pub session_id: [u8; 16],
    /// The lane, 1..=8.
    pub lane_id: u16,
    /// Fresh random per join; feeds the lane keys (SPEC.md §4.3).
    pub client_nonce: [u8; 16],
    /// The Join proof (SPEC.md §4.5).
    pub tag: [u8; 16],
}

impl Message for Join {
    const NAME: &'static str = "Join";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.session_id);
        w.u16(self.lane_id);
        w.fixed(&self.client_nonce);
        w.fixed(&self.tag);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.session_id = r.fixed::<16>()?;
        m.lane_id = r.u16()?;
        m.client_nonce = r.fixed::<16>()?;
        m.tag = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Join {
    const TYPE: u8 = 0x07;
}

/// Accepts a `Join`, node to client, unsealed; both sides then seal under the lane's keys (SPEC.md §9).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JoinAck {
    /// The lane, as in the `Join`.
    pub lane_id: u16,
    /// Fresh random per join; feeds the lane keys (SPEC.md §4.3).
    pub server_nonce: [u8; 16],
    /// The JoinAck proof (SPEC.md §4.5).
    pub tag: [u8; 16],
}

impl Message for JoinAck {
    const NAME: &'static str = "JoinAck";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.lane_id);
        w.fixed(&self.server_nonce);
        w.fixed(&self.tag);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.lane_id = r.u16()?;
        m.server_nonce = r.fixed::<16>()?;
        m.tag = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JoinAck {
    const TYPE: u8 = 0x08;
}

/// Heartbeat, every 2 s by default on every connection, channel 0; answered by `Pong` (SPEC.md §6).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Ping {
    /// The sender's sequence number, echoed in the `Pong`.
    pub seq: u32,
    /// The sender's monotonic clock in microseconds when the Ping was written; RTT = now - t_us.
    pub t_us: u64,
}

impl Message for Ping {
    const NAME: &'static str = "Ping";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.seq);
        w.u64(self.t_us);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.seq = r.u32()?;
        m.t_us = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Ping {
    const TYPE: u8 = 0x09;
}

/// Answer to a `Ping`, with its values (SPEC.md §6).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pong {
    /// The Ping's `seq`.
    pub seq: u32,
    /// The Ping's `t_us`.
    pub t_us: u64,
}

impl Message for Pong {
    const NAME: &'static str = "Pong";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.seq);
        w.u64(self.t_us);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.seq = r.u32()?;
        m.t_us = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Pong {
    const TYPE: u8 = 0x0a;
}

/// Reports why the connection ends; the sender then closes it (SPEC.md §6, §7.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Error {
    /// An `ERR_*` code.
    pub code: u16,
    /// The cause, as text.
    pub message: String,
}

impl Message for Error {
    const NAME: &'static str = "Error";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.code);
        w.str(&self.message)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.code = r.u16()?;
        m.message = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Error {
    const TYPE: u8 = 0x0b;
}

/// Ends the session (SPEC.md §6).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Bye {
    /// Not interpreted by version 1; implementations send 0.
    pub reason: u8,
}

impl Message for Bye {
    const NAME: &'static str = "Bye";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u8(self.reason);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.reason = r.u8()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Bye {
    const TYPE: u8 = 0x0c;
}

/// An RPC call on the control connection; the frame's channel is the request id (SPEC.md §7).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RpcRequest {
    /// A `METHOD_*` number, or an application's (SPEC.md §7.1, §7.3).
    pub method: u16,
    /// The method's request body, at most 56 KiB (SPEC.md §7.4).
    pub body: Vec<u8>,
}

impl Message for RpcRequest {
    const NAME: &'static str = "RpcRequest";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.method);
        w.bytes(&self.body)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.method = r.u16()?;
        m.body = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for RpcRequest {
    const TYPE: u8 = 0x60;
}

/// The answer to an `RpcRequest`, on the request's channel (SPEC.md §7).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RpcResponse {
    /// `STATUS_OK` or an `ERR_*` code (SPEC.md §7.2).
    pub status: u16,
    /// On `STATUS_OK` the method's reply body; on an error the cause as UTF-8 text. At most 256 KiB (SPEC.md §7.4).
    pub body: Vec<u8>,
}

impl Message for RpcResponse {
    const NAME: &'static str = "RpcResponse";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.status);
        w.bytes(&self.body)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.status = r.u16()?;
        m.body = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for RpcResponse {
    const TYPE: u8 = 0x61;
}

/// Opens a job, or reopens a known one to resume it; opener to peer, control connection (SPEC.md §11.3, §11.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobOpen {
    /// The job's id, chosen by the opener (SPEC.md §11.1).
    pub job_id: [u8; 16],
    /// A `JOB_*` kind, as seen by the node that receives this.
    pub kind: u8,
    /// A `POLICY_*`.
    pub policy: u8,
    /// `JF_*` bits (SPEC.md §11.8).
    pub flags: u32,
    /// Upload: the destination; download: the source.
    pub root: String,
    /// `JOB_COPY`: the source.
    pub src: Option<String>,
    /// `JOB_DOWNLOAD`: the credit the opener grants, in bytes (SPEC.md §12.4).
    pub credit: Option<u64>,
}

impl Message for JobOpen {
    const NAME: &'static str = "JobOpen";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u8(self.kind);
        w.u8(self.policy);
        w.u32(self.flags);
        w.str(&self.root)?;
        let mut ext_n: u16 = 0;
        if self.src.is_some() { ext_n += 1; }
        if self.credit.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.src { w.ext(1, |w| { w.str(v) })?; }
        if let Some(v) = &self.credit { w.ext(2, |w| { w.u64(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.kind = r.u8()?;
        m.policy = r.u8()?;
        m.flags = r.u32()?;
        m.root = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.src.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.src = Some(vr.str()?);
                    vr.finish()?;
                }
                2 => {
                    if m.credit.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.credit = Some(vr.u64()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JobOpen {
    const TYPE: u8 = 0x20;
}

/// The answer to a `JobOpen` (SPEC.md §11.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobOpenAck {
    /// The job.
    pub job_id: [u8; 16],
    /// `STATUS_OK` or an `ERR_*` refusal.
    pub status: u16,
    /// `JOB_UPLOAD`: lane-frame body bytes the sender may have outstanding (SPEC.md §12.4).
    pub credit: u64,
    /// 1 when the receiver writes under `<root>.ava-part/` and renames at the end (SPEC.md §11.6).
    pub staged: u8,
    /// The receiver's current number of write workers.
    pub workers: u8,
    /// The cause of a refusal, as text.
    pub message: Option<String>,
}

impl Message for JobOpenAck {
    const NAME: &'static str = "JobOpenAck";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(self.status);
        w.u64(self.credit);
        w.u8(self.staged);
        w.u8(self.workers);
        let mut ext_n: u16 = 0;
        if self.message.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.message { w.ext(1, |w| { w.str(v) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.status = r.u16()?;
        m.credit = r.u64()?;
        m.staged = r.u8()?;
        m.workers = r.u8()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.message.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.message = Some(vr.str()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JobOpenAck {
    const TYPE: u8 = 0x21;
}

/// One page of the manifest, sender to receiver; pages are sized to fit a control frame (SPEC.md §11.3, §11.7).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ManifestPage {
    /// The job.
    pub job_id: [u8; 16],
    /// The next entries, in manifest order.
    pub entries: Vec<ManifestEntry>,
}

impl Message for ManifestPage {
    const NAME: &'static str = "ManifestPage";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.records(&self.entries)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.entries = r.records::<ManifestEntry>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for ManifestPage {
    const TYPE: u8 = 0x22;
}

/// Ends the manifest, sender to receiver (SPEC.md §11.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ManifestEnd {
    /// The job.
    pub job_id: [u8; 16],
    /// How many entries are files.
    pub files: u32,
    /// The files' total size in bytes.
    pub bytes: u64,
    /// BLAKE3 over every entry, without its ext (SPEC.md §11.3).
    pub manifest_hash: [u8; 32],
}

impl Message for ManifestEnd {
    const NAME: &'static str = "ManifestEnd";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u32(self.files);
        w.u64(self.bytes);
        w.fixed(&self.manifest_hash);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.files = r.u32()?;
        m.bytes = r.u64()?;
        m.manifest_hash = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for ManifestEnd {
    const TYPE: u8 = 0x23;
}

/// What the receiver already has, receiver to sender; everything else is needed. May span pages (SPEC.md §11.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobMap {
    /// The job.
    pub job_id: [u8; 16],
    /// `STATUS_OK`, or an `ERR_*` such as `ERR_UNKNOWN_JOB` for a `Resume` the receiver cannot serve.
    pub status: u16,
    /// 1 on the final page.
    pub last: u8,
    /// Files the receiver already has whole.
    pub done: Vec<FileRun>,
    /// Durable ranges of unfinished files.
    pub partial: Vec<FileRange>,
    /// The cause of an error status, as text.
    pub message: Option<String>,
    /// Final page: bytes the drive already holds for this job's unfinished large files (the allocated
    /// blocks of their part files, at most each file's size). A sender that checks free space credits it;
    /// absent means none is claimed (SPEC.md §11.5).
    pub held: Option<u64>,
}

impl Message for JobMap {
    const NAME: &'static str = "JobMap";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(self.status);
        w.u8(self.last);
        w.records(&self.done)?;
        w.records(&self.partial)?;
        let mut ext_n: u16 = 0;
        if self.message.is_some() { ext_n += 1; }
        if self.held.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.message { w.ext(1, |w| { w.str(v) })?; }
        if let Some(v) = &self.held { w.ext(2, |w| { w.u64(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.status = r.u16()?;
        m.last = r.u8()?;
        m.done = r.records::<FileRun>()?;
        m.partial = r.records::<FileRange>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.message.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.message = Some(vr.str()?);
                    vr.finish()?;
                }
                2 => {
                    if m.held.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.held = Some(vr.u64()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JobMap {
    const TYPE: u8 = 0x24;
}

/// Fast-path resume when the sender still holds the same manifest; answered by `JobMap` (SPEC.md §11.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Resume {
    /// The job.
    pub job_id: [u8; 16],
    /// The hash of the manifest the sender holds.
    pub manifest_hash: [u8; 32],
}

impl Message for Resume {
    const NAME: &'static str = "Resume";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.fixed(&self.manifest_hash);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.manifest_hash = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Resume {
    const TYPE: u8 = 0x25;
}

/// Part of a large file, on a lane only (SPEC.md §12.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Chunk {
    /// The job.
    pub job_id: [u8; 16],
    /// The file.
    pub file_id: u32,
    /// Where `data` starts in the file: a multiple of 1 MiB.
    pub offset: u64,
    /// Whole 1 MiB groups, except at the end of the file.
    pub data: Vec<u8>,
}

impl Message for Chunk {
    const NAME: &'static str = "Chunk";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u32(self.file_id);
        w.u64(self.offset);
        w.bytes(&self.data)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.file_id = r.u32()?;
        m.offset = r.u64()?;
        m.data = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Chunk {
    const TYPE: u8 = 0x26;
}

/// Small files, whole, on a lane only (SPEC.md §12.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Bundle {
    /// The job.
    pub job_id: [u8; 16],
    /// One record per file.
    pub records: Vec<BundleRecord>,
}

impl Message for Bundle {
    const NAME: &'static str = "Bundle";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.records(&self.records)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.records = r.records::<BundleRecord>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Bundle {
    const TYPE: u8 = 0x27;
}

/// A lane frame is in the receiver's memory, before any disk work (SPEC.md §12.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Received {
    /// The job.
    pub job_id: [u8; 16],
    /// The lane the frame arrived on.
    pub lane: u16,
    /// The frame's header channel: the sender's per-job sequence number (SPEC.md §12.1).
    pub seq: u32,
}

impl Message for Received {
    const NAME: &'static str = "Received";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(self.lane);
        w.u32(self.seq);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.lane = r.u16()?;
        m.seq = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Received {
    const TYPE: u8 = 0x28;
}

/// Buffer space returned to the sender; adds to its window (SPEC.md §12.4).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Credit {
    /// The job.
    pub job_id: [u8; 16],
    /// Lane-frame body bytes freed.
    pub bytes: u64,
}

impl Message for Credit {
    const NAME: &'static str = "Credit";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u64(self.bytes);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.bytes = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Credit {
    const TYPE: u8 = 0x29;
}

/// Data synced and journaled, receiver to sender; never paged (SPEC.md §12.6).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Durable {
    /// The job.
    pub job_id: [u8; 16],
    /// Files now complete and durable.
    pub files: Vec<FileRun>,
    /// Newly durable ranges of unfinished files.
    pub ranges: Vec<FileRange>,
}

impl Message for Durable {
    const NAME: &'static str = "Durable";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.records(&self.files)?;
        w.records(&self.ranges)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.files = r.records::<FileRun>()?;
        m.ranges = r.records::<FileRange>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Durable {
    const TYPE: u8 = 0x2a;
}

/// A large file's BLAKE3 root, sender to receiver, once its last group is read (SPEC.md §13.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FileRoot {
    /// The job.
    pub job_id: [u8; 16],
    /// The file.
    pub file_id: u32,
    /// Its BLAKE3 root (SPEC.md §13.1).
    pub root: [u8; 32],
}

impl Message for FileRoot {
    const NAME: &'static str = "FileRoot";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u32(self.file_id);
        w.fixed(&self.root);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.file_id = r.u32()?;
        m.root = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for FileRoot {
    const TYPE: u8 = 0x2b;
}

/// The receiver dropped this file; send all of it again (SPEC.md §11.9, §13.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FileRetry {
    /// The job.
    pub job_id: [u8; 16],
    /// The file.
    pub file_id: u32,
    /// A `RETRY_*` code.
    pub reason: u16,
}

impl Message for FileRetry {
    const NAME: &'static str = "FileRetry";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u32(self.file_id);
        w.u16(self.reason);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.file_id = r.u32()?;
        m.reason = r.u16()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for FileRetry {
    const TYPE: u8 = 0x2c;
}

/// A job's progress: sent by the receiver every 250 ms, IGNORABLE; also the reply body of `job.status` and the job-starting methods (SPEC.md §7.1, §16.9).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Status {
    /// The job.
    pub job_id: [u8; 16],
    /// Files finished.
    pub files_done: u32,
    /// Files in the job; 0 while unknown.
    pub files_total: u32,
    /// Bytes the receiver has received.
    pub bytes_received: u64,
    /// Bytes durable on the receiver.
    pub bytes_durable: u64,
    /// Bytes in the job; 0 while unknown.
    pub bytes_total: u64,
    /// The receiver's own `BN_*` bottleneck.
    pub bottleneck: u8,
    /// The receiver's write workers.
    pub workers: u8,
    /// Data lanes in use.
    pub lanes: u8,
    /// Reserved for the sender's sequential choice (SPEC.md §16); version 1 receivers send 0.
    pub sequential: u8,
    /// The current step; on a failed job, the cause.
    pub current: Option<String>,
    /// RPC replies: 0 running, 1 finished OK, 2 failed (SPEC.md §7.1).
    pub state: Option<u8>,
    /// `job.run`: the finished operation's reply body, at most 128 KiB (SPEC.md §7.1.1).
    pub result: Option<Vec<u8>>,
    /// A failed job's `ERR_*` code.
    pub code: Option<u16>,
    /// Durable-by-log: done files not yet durable in place; absent means 0 (SPEC.md §15.7).
    pub unswept: Option<u32>,
}

impl Message for Status {
    const NAME: &'static str = "Status";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u32(self.files_done);
        w.u32(self.files_total);
        w.u64(self.bytes_received);
        w.u64(self.bytes_durable);
        w.u64(self.bytes_total);
        w.u8(self.bottleneck);
        w.u8(self.workers);
        w.u8(self.lanes);
        w.u8(self.sequential);
        let mut ext_n: u16 = 0;
        if self.current.is_some() { ext_n += 1; }
        if self.state.is_some() { ext_n += 1; }
        if self.result.is_some() { ext_n += 1; }
        if self.code.is_some() { ext_n += 1; }
        if self.unswept.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.current { w.ext(1, |w| { w.str(v) })?; }
        if let Some(v) = &self.state { w.ext(2, |w| { w.u8(*v); Ok(()) })?; }
        if let Some(v) = &self.result { w.ext(3, |w| { w.bytes(v) })?; }
        if let Some(v) = &self.code { w.ext(4, |w| { w.u16(*v); Ok(()) })?; }
        if let Some(v) = &self.unswept { w.ext(5, |w| { w.u32(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.files_done = r.u32()?;
        m.files_total = r.u32()?;
        m.bytes_received = r.u64()?;
        m.bytes_durable = r.u64()?;
        m.bytes_total = r.u64()?;
        m.bottleneck = r.u8()?;
        m.workers = r.u8()?;
        m.lanes = r.u8()?;
        m.sequential = r.u8()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.current.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.current = Some(vr.str()?);
                    vr.finish()?;
                }
                2 => {
                    if m.state.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.state = Some(vr.u8()?);
                    vr.finish()?;
                }
                3 => {
                    if m.result.is_some() { return Err(DecodeError::DupExt(3)); }
                    let mut vr = Reader::new(v);
                    m.result = Some(vr.bytes()?);
                    vr.finish()?;
                }
                4 => {
                    if m.code.is_some() { return Err(DecodeError::DupExt(4)); }
                    let mut vr = Reader::new(v);
                    m.code = Some(vr.u16()?);
                    vr.finish()?;
                }
                5 => {
                    if m.unswept.is_some() { return Err(DecodeError::DupExt(5)); }
                    let mut vr = Reader::new(v);
                    m.unswept = Some(vr.u32()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for Status {
    const TYPE: u8 = 0x2d;
}

/// The job ended, receiver to sender; sent after the last durable commit (SPEC.md §12.6).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobDone {
    /// The job.
    pub job_id: [u8; 16],
    /// `STATUS_OK` or the `ERR_*` the job ended with.
    pub status: u16,
    /// Files done.
    pub files: u32,
    /// Bytes durable.
    pub bytes: u64,
    /// The cause of a failure, as text.
    pub message: Option<String>,
    /// 1: the log is durable but files are still being made durable in place (SPEC.md §15.7).
    pub settling: Option<u8>,
}

impl Message for JobDone {
    const NAME: &'static str = "JobDone";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(self.status);
        w.u32(self.files);
        w.u64(self.bytes);
        let mut ext_n: u16 = 0;
        if self.message.is_some() { ext_n += 1; }
        if self.settling.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.message { w.ext(1, |w| { w.str(v) })?; }
        if let Some(v) = &self.settling { w.ext(2, |w| { w.u8(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.status = r.u16()?;
        m.files = r.u32()?;
        m.bytes = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.message.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.message = Some(vr.str()?);
                    vr.finish()?;
                }
                2 => {
                    if m.settling.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.settling = Some(vr.u8()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JobDone {
    const TYPE: u8 = 0x2e;
}

/// Ends a job; either peer may send it, and the receiver keeps the journal (SPEC.md §11.7).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobCancel {
    /// The job.
    pub job_id: [u8; 16],
    /// The `ERR_*` code the ender wants reported, such as `ERR_CANCELLED` for a user's cancel.
    pub reason: u16,
}

impl Message for JobCancel {
    const NAME: &'static str = "JobCancel";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(self.reason);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.reason = r.u16()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for JobCancel {
    const TYPE: u8 = 0x2f;
}

/// Job-scoped liveness (SPEC.md §12.8): a sender reading past data the receiver already holds (a
/// solid archive decoded from its start on resume) sends this at least every 10 s; the receiver
/// counts it as progress for that job.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SkipProgress {
    /// The job.
    pub job_id: [u8; 16],
    /// Running total of bytes the sender has read past for this job; informational.
    pub bytes_skipped: u64,
}

impl Message for SkipProgress {
    const NAME: &'static str = "SkipProgress";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u64(self.bytes_skipped);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.bytes_skipped = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

impl FrameMessage for SkipProgress {
    const TYPE: u8 = 0x30;
}

/// The `node.info` reply (SPEC.md §7.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct NodeInfo {
    /// The node software's version.
    pub version: String,
    /// The platform the node runs on.
    pub platform: String,
    /// The node's name.
    pub name: String,
    /// The platform's system software version.
    pub firmware: Option<String>,
}

impl Message for NodeInfo {
    const NAME: &'static str = "NodeInfo";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.str(&self.version)?;
        w.str(&self.platform)?;
        w.str(&self.name)?;
        let mut ext_n: u16 = 0;
        if self.firmware.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.firmware { w.ext(1, |w| { w.str(v) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.version = r.str()?;
        m.platform = r.str()?;
        m.name = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.firmware.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.firmware = Some(vr.str()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// The payload of `Hs1`: the protocol versions the client speaks (SPEC.md §5 step 1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HelloInfo {
    /// The lowest protocol version the client speaks.
    pub version_min: u16,
    /// The highest protocol version the client speaks.
    pub version_max: u16,
    /// Client capabilities; 0 in version 1.
    pub caps: u64,
}

impl Message for HelloInfo {
    const NAME: &'static str = "HelloInfo";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.version_min);
        w.u16(self.version_max);
        w.u64(self.caps);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.version_min = r.u16()?;
        m.version_max = r.u16()?;
        m.caps = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The payload of `Hs2` (SPEC.md §5 step 2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ServerInfo {
    /// The protocol version the node chose from the client's range.
    pub version: u16,
    /// The node's `CAP_*` bits.
    pub caps: u64,
    /// Random id of this session; lanes name it in `Join`.
    pub session_id: [u8; 16],
    /// BLAKE2b-256(nonce_s), revealed in `Welcome` (SPEC.md §4.6). Kept for wire stability.
    pub pair_commit: [u8; 32],
    /// The node's name, for the client to show.
    pub name: Option<String>,
}

impl Message for ServerInfo {
    const NAME: &'static str = "ServerInfo";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.version);
        w.u64(self.caps);
        w.fixed(&self.session_id);
        w.fixed(&self.pair_commit);
        let mut ext_n: u16 = 0;
        if self.name.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.name { w.ext(1, |w| { w.str(v) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.version = r.u16()?;
        m.caps = r.u64()?;
        m.session_id = r.fixed::<16>()?;
        m.pair_commit = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.name.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.name = Some(vr.str()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// The payload of `Hs3` (SPEC.md §5 step 3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ClientInfo {
    /// The client's pairing nonce (SPEC.md §4.6). Required; kept for wire stability.
    pub nonce_c: [u8; 16],
    /// The client's name, which the node stores with its key when they pair.
    pub name: Option<String>,
    /// A node sending to another node shows the ticket that node's `c2c.allow` handed out; it admits that one key for that one job (SPEC.md §18.2).
    pub token: Option<[u8; 16]>,
}

impl Message for ClientInfo {
    const NAME: &'static str = "ClientInfo";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.nonce_c);
        let mut ext_n: u16 = 0;
        if self.name.is_some() { ext_n += 1; }
        if self.token.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.name { w.ext(1, |w| { w.str(v) })?; }
        if let Some(v) = &self.token { w.ext(2, |w| { w.fixed(v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.nonce_c = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.name.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.name = Some(vr.str()?);
                    vr.finish()?;
                }
                2 => {
                    if m.token.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.token = Some(vr.fixed::<16>()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `pairing.open` request (SPEC.md §5 step 6, §7.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairingOpen {
    /// How long to keep the pairing window open, in seconds; at most 600.
    pub seconds: u16,
}

impl Message for PairingOpen {
    const NAME: &'static str = "PairingOpen";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.seconds);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.seconds = r.u16()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `crypto.bench` request (SPEC.md §7.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CryptoBench {
    /// How much data to seal and open, in MiB.
    pub mib: u16,
}

impl Message for CryptoBench {
    const NAME: &'static str = "CryptoBench";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.mib);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.mib = r.u16()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `crypto.bench` reply, a diagnostic (SPEC.md §7.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CryptoBenchResult {
    /// The bytes measured.
    pub bytes: u64,
    /// Microseconds to seal `bytes` as 1 MiB frames.
    pub micros: u64,
    /// Microseconds to open them.
    pub open_micros: Option<u64>,
    /// The ChaCha20 implementation in use: "avx2" or "portable".
    pub backend: Option<String>,
}

impl Message for CryptoBenchResult {
    const NAME: &'static str = "CryptoBenchResult";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u64(self.bytes);
        w.u64(self.micros);
        let mut ext_n: u16 = 0;
        if self.open_micros.is_some() { ext_n += 1; }
        if self.backend.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.open_micros { w.ext(1, |w| { w.u64(*v); Ok(()) })?; }
        if let Some(v) = &self.backend { w.ext(2, |w| { w.str(v) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.bytes = r.u64()?;
        m.micros = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.open_micros.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.open_micros = Some(vr.u64()?);
                    vr.finish()?;
                }
                2 => {
                    if m.backend.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.backend = Some(vr.str()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// One manifest entry, a file or a directory (SPEC.md §11.2, §11.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ManifestEntry {
    /// The entry's index in manifest order, from 0.
    pub file_id: u32,
    /// `ENTRY_FILE` or `ENTRY_DIR`.
    pub kind: u8,
    /// Unix permission bits.
    pub mode: u32,
    /// Size in bytes.
    pub size: u64,
    /// Last modification, in seconds since the Unix epoch; 0 when unknown, and always 0 for a directory (SPEC.md §11.4).
    pub mtime: u64,
    /// Relative to the job root, '/'-separated (SPEC.md §11.2).
    pub path: String,
    /// The file's BLAKE3 root, under `POLICY_VERIFY` only (SPEC.md §11.4).
    pub root: Option<[u8; 32]>,
}

impl Message for ManifestEntry {
    const NAME: &'static str = "ManifestEntry";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.file_id);
        w.u8(self.kind);
        w.u32(self.mode);
        w.u64(self.size);
        w.u64(self.mtime);
        w.str(&self.path)?;
        let mut ext_n: u16 = 0;
        if self.root.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.root { w.ext(1, |w| { w.fixed(v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.file_id = r.u32()?;
        m.kind = r.u8()?;
        m.mode = r.u32()?;
        m.size = r.u64()?;
        m.mtime = r.u64()?;
        m.path = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.root.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.root = Some(vr.fixed::<32>()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// Files `first..first + count` (records item).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FileRun {
    /// The first file id.
    pub first: u32,
    /// How many consecutive file ids.
    pub count: u32,
}

impl Message for FileRun {
    const NAME: &'static str = "FileRun";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.first);
        w.u32(self.count);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.first = r.u32()?;
        m.count = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Bytes `offset..offset + len` of one file (records item).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FileRange {
    /// The file.
    pub file_id: u32,
    /// The first byte.
    pub offset: u64,
    /// The length in bytes.
    pub len: u64,
}

impl Message for FileRange {
    const NAME: &'static str = "FileRange";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.file_id);
        w.u64(self.offset);
        w.u64(self.len);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.file_id = r.u32()?;
        m.offset = r.u64()?;
        m.len = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// One whole small file, inside a `Bundle` (SPEC.md §12.2, §15.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct BundleRecord {
    /// The file.
    pub file_id: u32,
    /// BLAKE3 of `data` (SPEC.md §13.2).
    pub root: [u8; 32],
    /// The file's whole content.
    pub data: Vec<u8>,
}

impl Message for BundleRecord {
    const NAME: &'static str = "BundleRecord";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.file_id);
        w.fixed(&self.root);
        w.bytes(&self.data)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.file_id = r.u32()?;
        m.root = r.fixed::<32>()?;
        m.data = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// A file's BLAKE3 root, as the journal records it (records item, SPEC.md §14.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RootItem {
    /// The file.
    pub file_id: u32,
    /// Its BLAKE3 root (SPEC.md §13.1).
    pub root: [u8; 32],
}

impl Message for RootItem {
    const NAME: &'static str = "RootItem";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.file_id);
        w.fixed(&self.root);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.file_id = r.u32()?;
        m.root = r.fixed::<32>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `job.copy` request: copy or move on the node itself (SPEC.md §15.5).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobCopy {
    /// The job's id, chosen by the caller; a repeat with the same parameters answers the existing job.
    pub job_id: [u8; 16],
    /// The source path.
    pub src: String,
    /// The destination root.
    pub dest: String,
    /// `JF_*` bits, such as `JF_MOVE` and `JF_OVERWRITE` (SPEC.md §11.8).
    pub flags: u32,
}

impl Message for JobCopy {
    const NAME: &'static str = "JobCopy";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.str(&self.src)?;
        w.str(&self.dest)?;
        w.u32(self.flags);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.src = r.str()?;
        m.dest = r.str()?;
        m.flags = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `job.status` and `job.cancel` request (SPEC.md §7.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobRef {
    /// The job.
    pub job_id: [u8; 16],
}

impl Message for JobRef {
    const NAME: &'static str = "JobRef";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `disk.calibrate` request (SPEC.md §16.10).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DiskCalibrate {
    /// Where to write the test files; must pass the node's write policy.
    pub dir: String,
    /// Files to write per measurement, at most 20,000.
    pub files: u32,
    /// Bytes per file, at most 1 MiB.
    pub size: u32,
}

impl Message for DiskCalibrate {
    const NAME: &'static str = "DiskCalibrate";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.str(&self.dir)?;
        w.u32(self.files);
        w.u32(self.size);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.dir = r.str()?;
        m.files = r.u32()?;
        m.size = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// One `disk.calibrate` measurement (SPEC.md §16.10).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CalPoint {
    /// The number of workers writing at once.
    pub workers: u8,
    /// Files written and synced per second.
    pub files_per_s: u32,
    /// Mean microseconds to create and write one file.
    pub create_us: u32,
    /// Mean microseconds to fsync one file.
    pub fsync_us: u32,
}

impl Message for CalPoint {
    const NAME: &'static str = "CalPoint";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u8(self.workers);
        w.u32(self.files_per_s);
        w.u32(self.create_us);
        w.u32(self.fsync_us);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.workers = r.u8()?;
        m.files_per_s = r.u32()?;
        m.create_us = r.u32()?;
        m.fsync_us = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `disk.calibrate` reply: a hint for a client's starting worker count, not a contract (SPEC.md §16.10).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DiskCalibrateResult {
    /// One measurement each at 1, 2, 4, 8 and 16 workers.
    pub points: Vec<CalPoint>,
}

impl Message for DiskCalibrateResult {
    const NAME: &'static str = "DiskCalibrateResult";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.records(&self.points)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.points = r.records::<CalPoint>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `c2c.allow` request, on the receiving node (SPEC.md §18.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct C2cAllow {
    /// The one job the ticket admits.
    pub job_id: [u8; 16],
    /// The sending node's identity (its static X25519 key).
    pub key: [u8; 32],
    /// Where the job may write.
    pub root: String,
}

impl Message for C2cAllow {
    const NAME: &'static str = "C2cAllow";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.fixed(&self.key);
        w.str(&self.root)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.key = r.fixed::<32>()?;
        m.root = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `c2c.allow` reply; the sending node shows the token in its `ClientInfo` (SPEC.md §18.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct C2cTicket {
    /// 16 random bytes; valid for 10 minutes from its last use.
    pub token: [u8; 16],
}

impl Message for C2cTicket {
    const NAME: &'static str = "C2cTicket";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.token);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.token = r.fixed::<16>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `c2c.send` request, on the sending node (SPEC.md §18.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct C2cSend {
    /// The job, as allowed on the receiving node.
    pub job_id: [u8; 16],
    /// The receiving node's IPv4 address.
    pub host: String,
    /// Its TCP port.
    pub port: u16,
    /// Its identity; the handshake must prove it.
    pub key: [u8; 32],
    /// The ticket from its `c2c.allow`.
    pub token: [u8; 16],
    /// The source path on the sending node.
    pub src: String,
    /// The destination root on the receiving node.
    pub dest: String,
    /// `JF_*` bits (SPEC.md §11.8).
    pub flags: u32,
}

impl Message for C2cSend {
    const NAME: &'static str = "C2cSend";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.str(&self.host)?;
        w.u16(self.port);
        w.fixed(&self.key);
        w.fixed(&self.token);
        w.str(&self.src)?;
        w.str(&self.dest)?;
        w.u32(self.flags);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.host = r.str()?;
        m.port = r.u16()?;
        m.key = r.fixed::<32>()?;
        m.token = r.fixed::<16>()?;
        m.src = r.str()?;
        m.dest = r.str()?;
        m.flags = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// An application method's opaque text body, in practice UTF-8 JSON (SPEC.md §7.3).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MgmtText {
    /// The text, carried unchanged.
    pub body: Vec<u8>,
    /// 1: call again with the next offset (paged methods); absent or 0 when the reply is complete.
    pub more: Option<u8>,
}

impl Message for MgmtText {
    const NAME: &'static str = "MgmtText";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.bytes(&self.body)?;
        let mut ext_n: u16 = 0;
        if self.more.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.more { w.ext(1, |w| { w.u8(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.body = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.more.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.more = Some(vr.u8()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `job.run` request (SPEC.md §7.1.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobRun {
    /// The job's id, chosen by the caller.
    pub job_id: [u8; 16],
    /// The operation, a number the application registered.
    pub op: u8,
    /// The operation's request body, opaque to the protocol; at most 60 KiB.
    pub args: Vec<u8>,
}

impl Message for JobRun {
    const NAME: &'static str = "JobRun";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u8(self.op);
        w.bytes(&self.args)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.op = r.u8()?;
        m.args = r.bytes()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// One job in a `job.list` reply (SPEC.md §7.1.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobEntry {
    /// The job.
    pub job_id: [u8; 16],
    /// 1 upload, 2 download, 3 copy, 4 operation.
    pub kind: u8,
    /// 0 running, 1 finished OK, 2 failed.
    pub state: u8,
    /// Files finished.
    pub files_done: u32,
    /// Files in the job; 0 while unknown.
    pub files_total: u32,
    /// Bytes done (durable, for a transfer).
    pub bytes_done: u64,
    /// Bytes in the job; 0 while unknown.
    pub bytes_total: u64,
}

impl Message for JobEntry {
    const NAME: &'static str = "JobEntry";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.u8(self.kind);
        w.u8(self.state);
        w.u32(self.files_done);
        w.u32(self.files_total);
        w.u64(self.bytes_done);
        w.u64(self.bytes_total);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.kind = r.u8()?;
        m.state = r.u8()?;
        m.files_done = r.u32()?;
        m.files_total = r.u32()?;
        m.bytes_done = r.u64()?;
        m.bytes_total = r.u64()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// The `job.list` reply: the caller's jobs of every kind (SPEC.md §7.1.1).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JobListResult {
    /// One entry per job.
    pub jobs: Vec<JobEntry>,
}

impl Message for JobListResult {
    const NAME: &'static str = "JobListResult";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.records(&self.jobs)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.jobs = r.records::<JobEntry>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 1: the job as opened (SPEC.md §14.1). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlOpen {
    /// The job.
    pub job_id: [u8; 16],
    /// The hash of the stored manifest.
    pub manifest_hash: [u8; 32],
    /// The job's `JOB_*` kind.
    pub kind: u8,
    /// The job's `JF_*` flags.
    pub flags: u32,
    /// Bit 0: the tree is written under `<root>.ava-part`; bit 1: the receiver took `<root>` with `mkdir` (SPEC.md §11.6).
    pub staged: u8,
    /// The destination root.
    pub root: String,
}

impl Message for JnlOpen {
    const NAME: &'static str = "JnlOpen";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.fixed(&self.job_id);
        w.fixed(&self.manifest_hash);
        w.u8(self.kind);
        w.u32(self.flags);
        w.u8(self.staged);
        w.str(&self.root)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.job_id = r.fixed::<16>()?;
        m.manifest_hash = r.fixed::<32>()?;
        m.kind = r.u8()?;
        m.flags = r.u32()?;
        m.staged = r.u8()?;
        m.root = r.str()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 2: one sync batch (SPEC.md §14.2). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlBatch {
    /// Files now done; their ranges are dropped.
    pub files: Vec<FileRun>,
    /// Durable ranges added.
    pub ranges: Vec<FileRange>,
    /// Roots recorded.
    pub roots: Vec<RootItem>,
    /// Durable-by-log: the pack segment `pack.<n>` that holds this batch's `PackFile` records (SPEC.md §15.7).
    pub pack_segment: Option<u32>,
    /// Where those records start in the segment, in bytes.
    pub pack_offset: Option<u64>,
    /// Their length in bytes.
    pub pack_len: Option<u64>,
}

impl Message for JnlBatch {
    const NAME: &'static str = "JnlBatch";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.records(&self.files)?;
        w.records(&self.ranges)?;
        w.records(&self.roots)?;
        let mut ext_n: u16 = 0;
        if self.pack_segment.is_some() { ext_n += 1; }
        if self.pack_offset.is_some() { ext_n += 1; }
        if self.pack_len.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.pack_segment { w.ext(1, |w| { w.u32(*v); Ok(()) })?; }
        if let Some(v) = &self.pack_offset { w.ext(2, |w| { w.u64(*v); Ok(()) })?; }
        if let Some(v) = &self.pack_len { w.ext(3, |w| { w.u64(*v); Ok(()) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.files = r.records::<FileRun>()?;
        m.ranges = r.records::<FileRange>()?;
        m.roots = r.records::<RootItem>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.pack_segment.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.pack_segment = Some(vr.u32()?);
                    vr.finish()?;
                }
                2 => {
                    if m.pack_offset.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.pack_offset = Some(vr.u64()?);
                    vr.finish()?;
                }
                3 => {
                    if m.pack_len.is_some() { return Err(DecodeError::DupExt(3)); }
                    let mut vr = Reader::new(v);
                    m.pack_len = Some(vr.u64()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// Where a batch's `PackFile` records live; in journal snapshots only (SPEC.md §14.2, §15.7).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PackRef {
    /// The pack segment `pack.<n>`.
    pub segment: u32,
    /// Where the records start, in bytes.
    pub offset: u64,
    /// Their length in bytes.
    pub len: u64,
    /// The first file id the records cover.
    pub first_file: u32,
    /// File ids covered: `first_file..first_file + count`.
    pub count: u32,
}

impl Message for PackRef {
    const NAME: &'static str = "PackRef";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.segment);
        w.u64(self.offset);
        w.u64(self.len);
        w.u32(self.first_file);
        w.u32(self.count);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.segment = r.u32()?;
        m.offset = r.u64()?;
        m.len = r.u64()?;
        m.first_file = r.u32()?;
        m.count = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 6: these files are now durable in place (SPEC.md §14.2, §15.7). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlSweep {
    /// The files swept.
    pub files: Vec<FileRun>,
}

impl Message for JnlSweep {
    const NAME: &'static str = "JnlSweep";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.records(&self.files)?;
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.files = r.records::<FileRun>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 3: forget one file's progress (SPEC.md §14.2). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlReset {
    /// The file.
    pub file_id: u32,
}

impl Message for JnlReset {
    const NAME: &'static str = "JnlReset";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u32(self.file_id);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.file_id = r.u32()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 4: the whole state, written when the journal is compacted (SPEC.md §14.1, §14.2). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlSnapshot {
    /// Files done.
    pub done: Vec<FileRun>,
    /// Durable ranges of unfinished files.
    pub ranges: Vec<FileRange>,
    /// Roots recorded.
    pub roots: Vec<RootItem>,
    /// The `FileRun` item stream of done files not yet swept (SPEC.md §14.2).
    pub unswept: Option<Vec<u8>>,
    /// The `PackRef` item stream of the pack ranges whose files are not all swept (SPEC.md §14.2).
    pub segments: Option<Vec<u8>>,
}

impl Message for JnlSnapshot {
    const NAME: &'static str = "JnlSnapshot";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.records(&self.done)?;
        w.records(&self.ranges)?;
        w.records(&self.roots)?;
        let mut ext_n: u16 = 0;
        if self.unswept.is_some() { ext_n += 1; }
        if self.segments.is_some() { ext_n += 1; }
        w.u16(ext_n);
        if let Some(v) = &self.unswept { w.ext(1, |w| { w.bytes(v) })?; }
        if let Some(v) = &self.segments { w.ext(2, |w| { w.bytes(v) })?; }
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.done = r.records::<FileRun>()?;
        m.ranges = r.records::<FileRange>()?;
        m.roots = r.records::<RootItem>()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            match tag {
                1 => {
                    if m.unswept.is_some() { return Err(DecodeError::DupExt(1)); }
                    let mut vr = Reader::new(v);
                    m.unswept = Some(vr.bytes()?);
                    vr.finish()?;
                }
                2 => {
                    if m.segments.is_some() { return Err(DecodeError::DupExt(2)); }
                    let mut vr = Reader::new(v);
                    m.segments = Some(vr.bytes()?);
                    vr.finish()?;
                }
                _ => {}
            }
        }
        r.finish()?;
        Ok(m)
    }
}

/// Journal record kind 5: the job's final status (SPEC.md §14.2). Never on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JnlDone {
    /// `STATUS_OK` or an `ERR_*` code.
    pub status: u16,
}

impl Message for JnlDone {
    const NAME: &'static str = "JnlDone";

    fn encode_into(&self, w: &mut Writer) -> Result<(), EncodeError> {
        w.u16(self.status);
        w.u16(0);
        Ok(())
    }

    fn decode(b: &[u8]) -> Result<Self, DecodeError> {
        let mut r = Reader::new(b);
        let mut m = Self::default();
        m.status = r.u16()?;
        let ext_n = r.u16()?;
        for _ in 0..ext_n {
            let tag = r.u16()?;
            let len = r.u32()? as usize;
            let v = r.take(len)?;
            let _ = (tag, v);
        }
        r.finish()?;
        Ok(m)
    }
}

/// Every message and struct, by name (conformance tests).
pub const ALL: &[&str] = &["Hs1", "Hs2", "Hs3", "Welcome", "PairPakeClient", "PairPakeServer", "PairConfirm", "PairResult", "Join", "JoinAck", "Ping", "Pong", "Error", "Bye", "RpcRequest", "RpcResponse", "JobOpen", "JobOpenAck", "ManifestPage", "ManifestEnd", "JobMap", "Resume", "Chunk", "Bundle", "Received", "Credit", "Durable", "FileRoot", "FileRetry", "Status", "JobDone", "JobCancel", "SkipProgress", "NodeInfo", "HelloInfo", "ServerInfo", "ClientInfo", "PairingOpen", "CryptoBench", "CryptoBenchResult", "ManifestEntry", "FileRun", "FileRange", "BundleRecord", "RootItem", "JobCopy", "JobRef", "DiskCalibrate", "CalPoint", "DiskCalibrateResult", "C2cAllow", "C2cTicket", "C2cSend", "MgmtText", "JobRun", "JobEntry", "JobListResult", "JnlOpen", "JnlBatch", "PackRef", "JnlSweep", "JnlReset", "JnlSnapshot", "JnlDone", ];

#[doc(hidden)]
pub fn sample(name: &str, rng: &mut SplitMix) -> Option<Vec<u8>> {
    match name {
        "Hs1" => Hs1 { noise: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "Hs2" => Hs2 { noise: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "Hs3" => Hs3 { noise: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "Welcome" => Welcome { knows_you: rng.next_u64() as u8, nonce_s: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, launch_proof: if rng.below(2) == 1 { Some({ let mut a = [0u8; 16]; rng.fill(&mut a); a }) } else { None }, }.to_bytes().ok(),
        "PairPakeClient" => PairPakeClient { y: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "PairPakeServer" => PairPakeServer { y: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "PairConfirm" => PairConfirm { mac: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "PairResult" => PairResult { accepted: rng.next_u64() as u8, mac: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "Join" => Join { session_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, lane_id: rng.next_u64() as u16, client_nonce: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, tag: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "JoinAck" => JoinAck { lane_id: rng.next_u64() as u16, server_nonce: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, tag: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "Ping" => Ping { seq: rng.next_u64() as u32, t_us: rng.next_u64(), }.to_bytes().ok(),
        "Pong" => Pong { seq: rng.next_u64() as u32, t_us: rng.next_u64(), }.to_bytes().ok(),
        "Error" => Error { code: rng.next_u64() as u16, message: rng.ascii(20), }.to_bytes().ok(),
        "Bye" => Bye { reason: rng.next_u64() as u8, }.to_bytes().ok(),
        "RpcRequest" => RpcRequest { method: rng.next_u64() as u16, body: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "RpcResponse" => RpcResponse { status: rng.next_u64() as u16, body: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "JobOpen" => JobOpen { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, kind: rng.next_u64() as u8, policy: rng.next_u64() as u8, flags: rng.next_u64() as u32, root: rng.ascii(20), src: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, credit: if rng.below(2) == 1 { Some(rng.next_u64()) } else { None }, }.to_bytes().ok(),
        "JobOpenAck" => JobOpenAck { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, status: rng.next_u64() as u16, credit: rng.next_u64(), staged: rng.next_u64() as u8, workers: rng.next_u64() as u8, message: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, }.to_bytes().ok(),
        "ManifestPage" => ManifestPage { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, entries: vec![ManifestEntry::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "ManifestEnd" => ManifestEnd { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, files: rng.next_u64() as u32, bytes: rng.next_u64(), manifest_hash: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "JobMap" => JobMap { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, status: rng.next_u64() as u16, last: rng.next_u64() as u8, done: vec![FileRun::default(); rng.below(3) as usize], partial: vec![FileRange::default(); rng.below(3) as usize], message: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, held: if rng.below(2) == 1 { Some(rng.next_u64()) } else { None }, }.to_bytes().ok(),
        "Resume" => Resume { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, manifest_hash: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "Chunk" => Chunk { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, file_id: rng.next_u64() as u32, offset: rng.next_u64(), data: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "Bundle" => Bundle { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, records: vec![BundleRecord::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "Received" => Received { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, lane: rng.next_u64() as u16, seq: rng.next_u64() as u32, }.to_bytes().ok(),
        "Credit" => Credit { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, bytes: rng.next_u64(), }.to_bytes().ok(),
        "Durable" => Durable { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, files: vec![FileRun::default(); rng.below(3) as usize], ranges: vec![FileRange::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "FileRoot" => FileRoot { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, file_id: rng.next_u64() as u32, root: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "FileRetry" => FileRetry { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, file_id: rng.next_u64() as u32, reason: rng.next_u64() as u16, }.to_bytes().ok(),
        "Status" => Status { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, files_done: rng.next_u64() as u32, files_total: rng.next_u64() as u32, bytes_received: rng.next_u64(), bytes_durable: rng.next_u64(), bytes_total: rng.next_u64(), bottleneck: rng.next_u64() as u8, workers: rng.next_u64() as u8, lanes: rng.next_u64() as u8, sequential: rng.next_u64() as u8, current: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, state: if rng.below(2) == 1 { Some(rng.next_u64() as u8) } else { None }, result: if rng.below(2) == 1 { Some({ let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }) } else { None }, code: if rng.below(2) == 1 { Some(rng.next_u64() as u16) } else { None }, unswept: if rng.below(2) == 1 { Some(rng.next_u64() as u32) } else { None }, }.to_bytes().ok(),
        "JobDone" => JobDone { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, status: rng.next_u64() as u16, files: rng.next_u64() as u32, bytes: rng.next_u64(), message: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, settling: if rng.below(2) == 1 { Some(rng.next_u64() as u8) } else { None }, }.to_bytes().ok(),
        "JobCancel" => JobCancel { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, reason: rng.next_u64() as u16, }.to_bytes().ok(),
        "SkipProgress" => SkipProgress { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, bytes_skipped: rng.next_u64(), }.to_bytes().ok(),
        "NodeInfo" => NodeInfo { version: rng.ascii(20), platform: rng.ascii(20), name: rng.ascii(20), firmware: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, }.to_bytes().ok(),
        "HelloInfo" => HelloInfo { version_min: rng.next_u64() as u16, version_max: rng.next_u64() as u16, caps: rng.next_u64(), }.to_bytes().ok(),
        "ServerInfo" => ServerInfo { version: rng.next_u64() as u16, caps: rng.next_u64(), session_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, pair_commit: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, name: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, }.to_bytes().ok(),
        "ClientInfo" => ClientInfo { nonce_c: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, name: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, token: if rng.below(2) == 1 { Some({ let mut a = [0u8; 16]; rng.fill(&mut a); a }) } else { None }, }.to_bytes().ok(),
        "PairingOpen" => PairingOpen { seconds: rng.next_u64() as u16, }.to_bytes().ok(),
        "CryptoBench" => CryptoBench { mib: rng.next_u64() as u16, }.to_bytes().ok(),
        "CryptoBenchResult" => CryptoBenchResult { bytes: rng.next_u64(), micros: rng.next_u64(), open_micros: if rng.below(2) == 1 { Some(rng.next_u64()) } else { None }, backend: if rng.below(2) == 1 { Some(rng.ascii(20)) } else { None }, }.to_bytes().ok(),
        "ManifestEntry" => ManifestEntry { file_id: rng.next_u64() as u32, kind: rng.next_u64() as u8, mode: rng.next_u64() as u32, size: rng.next_u64(), mtime: rng.next_u64(), path: rng.ascii(20), root: if rng.below(2) == 1 { Some({ let mut a = [0u8; 32]; rng.fill(&mut a); a }) } else { None }, }.to_bytes().ok(),
        "FileRun" => FileRun { first: rng.next_u64() as u32, count: rng.next_u64() as u32, }.to_bytes().ok(),
        "FileRange" => FileRange { file_id: rng.next_u64() as u32, offset: rng.next_u64(), len: rng.next_u64(), }.to_bytes().ok(),
        "BundleRecord" => BundleRecord { file_id: rng.next_u64() as u32, root: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, data: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "RootItem" => RootItem { file_id: rng.next_u64() as u32, root: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "JobCopy" => JobCopy { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, src: rng.ascii(20), dest: rng.ascii(20), flags: rng.next_u64() as u32, }.to_bytes().ok(),
        "JobRef" => JobRef { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "DiskCalibrate" => DiskCalibrate { dir: rng.ascii(20), files: rng.next_u64() as u32, size: rng.next_u64() as u32, }.to_bytes().ok(),
        "CalPoint" => CalPoint { workers: rng.next_u64() as u8, files_per_s: rng.next_u64() as u32, create_us: rng.next_u64() as u32, fsync_us: rng.next_u64() as u32, }.to_bytes().ok(),
        "DiskCalibrateResult" => DiskCalibrateResult { points: vec![CalPoint::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "C2cAllow" => C2cAllow { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, key: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, root: rng.ascii(20), }.to_bytes().ok(),
        "C2cTicket" => C2cTicket { token: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, }.to_bytes().ok(),
        "C2cSend" => C2cSend { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, host: rng.ascii(20), port: rng.next_u64() as u16, key: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, token: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, src: rng.ascii(20), dest: rng.ascii(20), flags: rng.next_u64() as u32, }.to_bytes().ok(),
        "MgmtText" => MgmtText { body: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, more: if rng.below(2) == 1 { Some(rng.next_u64() as u8) } else { None }, }.to_bytes().ok(),
        "JobRun" => JobRun { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, op: rng.next_u64() as u8, args: { let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }, }.to_bytes().ok(),
        "JobEntry" => JobEntry { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, kind: rng.next_u64() as u8, state: rng.next_u64() as u8, files_done: rng.next_u64() as u32, files_total: rng.next_u64() as u32, bytes_done: rng.next_u64(), bytes_total: rng.next_u64(), }.to_bytes().ok(),
        "JobListResult" => JobListResult { jobs: vec![JobEntry::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "JnlOpen" => JnlOpen { job_id: { let mut a = [0u8; 16]; rng.fill(&mut a); a }, manifest_hash: { let mut a = [0u8; 32]; rng.fill(&mut a); a }, kind: rng.next_u64() as u8, flags: rng.next_u64() as u32, staged: rng.next_u64() as u8, root: rng.ascii(20), }.to_bytes().ok(),
        "JnlBatch" => JnlBatch { files: vec![FileRun::default(); rng.below(3) as usize], ranges: vec![FileRange::default(); rng.below(3) as usize], roots: vec![RootItem::default(); rng.below(3) as usize], pack_segment: if rng.below(2) == 1 { Some(rng.next_u64() as u32) } else { None }, pack_offset: if rng.below(2) == 1 { Some(rng.next_u64()) } else { None }, pack_len: if rng.below(2) == 1 { Some(rng.next_u64()) } else { None }, }.to_bytes().ok(),
        "PackRef" => PackRef { segment: rng.next_u64() as u32, offset: rng.next_u64(), len: rng.next_u64(), first_file: rng.next_u64() as u32, count: rng.next_u64() as u32, }.to_bytes().ok(),
        "JnlSweep" => JnlSweep { files: vec![FileRun::default(); rng.below(3) as usize], }.to_bytes().ok(),
        "JnlReset" => JnlReset { file_id: rng.next_u64() as u32, }.to_bytes().ok(),
        "JnlSnapshot" => JnlSnapshot { done: vec![FileRun::default(); rng.below(3) as usize], ranges: vec![FileRange::default(); rng.below(3) as usize], roots: vec![RootItem::default(); rng.below(3) as usize], unswept: if rng.below(2) == 1 { Some({ let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }) } else { None }, segments: if rng.below(2) == 1 { Some({ let n = rng.below(41) as usize; let mut v = vec![0u8; n]; rng.fill(&mut v); v }) } else { None }, }.to_bytes().ok(),
        "JnlDone" => JnlDone { status: rng.next_u64() as u16, }.to_bytes().ok(),
        _ => None,
    }
}

#[doc(hidden)]
pub fn roundtrip(name: &str, bytes: &[u8]) -> Option<Result<Vec<u8>, String>> {
    fn rt<M: Message>(b: &[u8]) -> Result<Vec<u8>, String> {
        M::decode(b).map_err(|e| e.to_string())?.to_bytes().map_err(|e| e.to_string())
    }
    Some(match name {
        "Hs1" => rt::<Hs1>(bytes),
        "Hs2" => rt::<Hs2>(bytes),
        "Hs3" => rt::<Hs3>(bytes),
        "Welcome" => rt::<Welcome>(bytes),
        "PairPakeClient" => rt::<PairPakeClient>(bytes),
        "PairPakeServer" => rt::<PairPakeServer>(bytes),
        "PairConfirm" => rt::<PairConfirm>(bytes),
        "PairResult" => rt::<PairResult>(bytes),
        "Join" => rt::<Join>(bytes),
        "JoinAck" => rt::<JoinAck>(bytes),
        "Ping" => rt::<Ping>(bytes),
        "Pong" => rt::<Pong>(bytes),
        "Error" => rt::<Error>(bytes),
        "Bye" => rt::<Bye>(bytes),
        "RpcRequest" => rt::<RpcRequest>(bytes),
        "RpcResponse" => rt::<RpcResponse>(bytes),
        "JobOpen" => rt::<JobOpen>(bytes),
        "JobOpenAck" => rt::<JobOpenAck>(bytes),
        "ManifestPage" => rt::<ManifestPage>(bytes),
        "ManifestEnd" => rt::<ManifestEnd>(bytes),
        "JobMap" => rt::<JobMap>(bytes),
        "Resume" => rt::<Resume>(bytes),
        "Chunk" => rt::<Chunk>(bytes),
        "Bundle" => rt::<Bundle>(bytes),
        "Received" => rt::<Received>(bytes),
        "Credit" => rt::<Credit>(bytes),
        "Durable" => rt::<Durable>(bytes),
        "FileRoot" => rt::<FileRoot>(bytes),
        "FileRetry" => rt::<FileRetry>(bytes),
        "Status" => rt::<Status>(bytes),
        "JobDone" => rt::<JobDone>(bytes),
        "JobCancel" => rt::<JobCancel>(bytes),
        "SkipProgress" => rt::<SkipProgress>(bytes),
        "NodeInfo" => rt::<NodeInfo>(bytes),
        "HelloInfo" => rt::<HelloInfo>(bytes),
        "ServerInfo" => rt::<ServerInfo>(bytes),
        "ClientInfo" => rt::<ClientInfo>(bytes),
        "PairingOpen" => rt::<PairingOpen>(bytes),
        "CryptoBench" => rt::<CryptoBench>(bytes),
        "CryptoBenchResult" => rt::<CryptoBenchResult>(bytes),
        "ManifestEntry" => rt::<ManifestEntry>(bytes),
        "FileRun" => rt::<FileRun>(bytes),
        "FileRange" => rt::<FileRange>(bytes),
        "BundleRecord" => rt::<BundleRecord>(bytes),
        "RootItem" => rt::<RootItem>(bytes),
        "JobCopy" => rt::<JobCopy>(bytes),
        "JobRef" => rt::<JobRef>(bytes),
        "DiskCalibrate" => rt::<DiskCalibrate>(bytes),
        "CalPoint" => rt::<CalPoint>(bytes),
        "DiskCalibrateResult" => rt::<DiskCalibrateResult>(bytes),
        "C2cAllow" => rt::<C2cAllow>(bytes),
        "C2cTicket" => rt::<C2cTicket>(bytes),
        "C2cSend" => rt::<C2cSend>(bytes),
        "MgmtText" => rt::<MgmtText>(bytes),
        "JobRun" => rt::<JobRun>(bytes),
        "JobEntry" => rt::<JobEntry>(bytes),
        "JobListResult" => rt::<JobListResult>(bytes),
        "JnlOpen" => rt::<JnlOpen>(bytes),
        "JnlBatch" => rt::<JnlBatch>(bytes),
        "PackRef" => rt::<PackRef>(bytes),
        "JnlSweep" => rt::<JnlSweep>(bytes),
        "JnlReset" => rt::<JnlReset>(bytes),
        "JnlSnapshot" => rt::<JnlSnapshot>(bytes),
        "JnlDone" => rt::<JnlDone>(bytes),
        _ => return None,
    })
}