derec-library 0.1.0

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Time-driven work.
//!
//! Nothing in the protocol runs on its own clock: [`DeRecProtocol::tick`] is
//! the application handing over control so deadlines can be checked. A round
//! that never completes, an unpair that is never acknowledged, a recovery
//! still waiting on a silent helper, and a channel that outlives its pairing
//! window are all settled from here.

use super::DeRecProtocol;
use super::context::local;
use super::events::DeRecEvent;
use super::handlers::replicas::discovery;
use super::handlers::{recovery, unpairing};
use super::stores::borrow_stores;
use super::traits::{
    DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecStateStore, DeRecTransport,
    DeRecUserSecretStore,
};
use super::types::{SecretKind, StateItem, StateKey, StateKind};
use crate::{Result, types::ChannelId};
use derec_proto::{CommittedDeRecShare, DeRecShare, StatusEnum};

use crate::extensions::channel_store::ChannelStoreExt as _;
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
use crate::protocol::ExpiredChannelCleanup;
use crate::protocol::types::{
    ChannelQuery, ChannelStatus, HelperFilter, ReplicaFilter, ReplicaMember, SharingRoundState,
};
use crate::types::ReplicaId;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;
use std::collections::HashSet;
use std::mem;

impl<
    Ch: DeRecChannelStore,
    Sh: DeRecShareStore,
    Ss: DeRecSecretStore,
    Us: DeRecUserSecretStore,
    T: DeRecTransport,
    St: DeRecStateStore,
> DeRecProtocol<Ch, Sh, Ss, Us, St, T>
{
    /// Check if any channels in the active sharing round have timed out.
    ///
    /// Returns `ShareRejected` events for timed-out channels and moves them
    /// from `pending` to `failed` in the round tracker.
    /// Advance every time-driven part of the protocol without an inbound
    /// message, returning whatever that produced.
    ///
    /// # Why this exists
    ///
    /// Timeouts are otherwise only evaluated inside [`Self::process`], so they
    /// advance only when traffic arrives. A publish whose helpers all go quiet
    /// has nothing left to trigger it: the round stays open, no
    /// [`DeRecEvent::SharingComplete`] is ever emitted, and an application
    /// waiting on that event waits forever. The same applies to an
    /// unacknowledged unpair.
    ///
    /// A long-lived embedded application could rely on incidental traffic. A
    /// service that rebuilds the protocol per request has no background loop
    /// at all, so this is the entry point its scheduler calls — a cron tick, a
    /// timer task, a queue heartbeat.
    ///
    /// # What it does
    ///
    /// Exactly what [`Self::process`] does about time, minus the message:
    ///
    /// 1. Expired-channel cleanup, if
    ///    [`Timeouts::expired_channels`](crate::protocol::types::Timeouts::expired_channels)
    ///    enabled it — which it is **by default**
    ///    (`Enabled { timeout_in_secs: 300 }`). Setting it to
    ///    [`crate::protocol::ExpiredChannelCleanup::Disabled`]
    ///    skips this step and leaves [`Self::remove_expired_channels`] for
    ///    explicit control.
    /// 2. Sharing-round timeouts — every helper still pending past the
    ///    configured window is failed with
    ///    [`DeRecEvent::ShareRejected`], every member still pending is
    ///    reported [`DeRecEvent::ReplicaSyncFailed`].
    /// 3. Unpair-acknowledgement timeouts.
    /// 4. Recovery timeouts — a recovery still waiting on a helper past
    ///    [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response)
    ///    reports each silent helper as [`DeRecEvent::RecoverSecretFailed`]
    ///    and decides on the shares it holds.
    /// 5. Replica version-check timeouts — a check still waiting on a member
    ///    past the same budget concludes on the versions already reported.
    /// 6. The round tally, which is what turns a fully-drained round into
    ///    [`DeRecEvent::SharingComplete`] and clears its state row. Step 2
    ///    only marks the participants; without this the round would report
    ///    failures and still never close.
    ///
    /// # Calling it
    ///
    /// Idempotent and safe to call at any time: with nothing in flight it
    /// touches no state and returns an empty vector. Store failures are
    /// swallowed the same way [`Self::process`] swallows them, so a transient
    /// backend error means work is retried on the next call rather than
    /// surfaced here.
    ///
    /// Cadence should be shorter than
    /// [`Timeouts`](crate::protocol::types::Timeouts), since that bounds how long a
    /// stalled round can sit before this notices it.
    ///
    /// Concurrency is the caller's, as everywhere else: this mutates the same
    /// round state an inbound response does, so it must be serialized against
    /// [`Self::process`] for the same `secret_id`. See
    /// [`DeRecStateStore`].
    #[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
    pub async fn tick(&mut self) -> Vec<DeRecEvent> {
        let mut events = self.run_timeout_sweeps().await;
        self.update_sharing_round(&mut events).await;
        events
    }

    /// Remove `Pending` channels older than `older_than_secs`, along with
    /// their channel key and pairing material. Returns the ids that were
    /// removed.
    ///
    /// No key outlives the pairing it was agreed for: without the record, the
    /// key would decrypt the peer's messages again.
    ///
    /// This is **independent of**
    /// [`Timeouts::expired_channels`](crate::protocol::types::Timeouts::expired_channels): it sweeps at
    /// the threshold it is given even when the policy is
    /// [`crate::protocol::ExpiredChannelCleanup::Disabled`]. That is what
    /// makes `Disabled` mean "the application drives cleanup itself".
    ///
    /// `older_than_secs` is not clamped. The minimum-of-one-second rule
    /// exists to stop the *automatic* sweep from deleting just-started
    /// pairings on every [`process`](Self::process) call; an explicit call
    /// is a deliberate act, so `remove_expired_channels(0)` is permitted
    /// and sweeps the most aggressively the predicate allows.
    ///
    /// The comparison is strict — a channel is removed when its age is
    /// **greater than** `older_than_secs`. Ages are whole seconds, taken
    /// from `created_at`, so `remove_expired_channels(0)` removes every
    /// `Pending` channel created in an earlier second but leaves one
    /// created within the current second.
    ///
    /// Called automatically during [`process`](Self::process) when the
    /// configured policy is
    /// [`crate::protocol::ExpiredChannelCleanup::Enabled`].
    ///
    /// Replica rows are swept on the same clock: a replica pairing that never
    /// completed leaves a `Pending` member row behind. Members of a group share
    /// one channel and one key, so the key goes only once no peer is recorded
    /// on the channel. This device's own row is swept only when it is `Pending`
    /// and no peer remains on its channel — the remainder of a pairing that
    /// never completed; a `Paired` own row is its place in the group and is
    /// never swept.
    ///
    /// Removing a record never removes a key by itself: a channel's key and
    /// pairing material go only once nothing else is recorded on the channel,
    /// so an expired `Pending` helper record on a replica group's channel
    /// leaves the group key in place.
    pub async fn remove_expired_channels(
        &mut self,
        older_than_secs: u64,
    ) -> Result<Vec<ChannelId>> {
        let now = now_secs();
        let timeout = older_than_secs;
        let channels = self
            .channel_store
            .helpers_matching(
                self.secret_id,
                HelperFilter {
                    status: vec![ChannelStatus::Pending],
                    ..Default::default()
                },
            )
            .await?;

        let mut removed = Vec::new();
        for channel in channels {
            if now.saturating_sub(channel.created_at) > timeout {
                self.channel_store
                    .remove(
                        self.secret_id,
                        ChannelQuery::Helper {
                            channel_id: channel.channel_id,
                        },
                    )
                    .await?;

                #[cfg(feature = "logging")]
                tracing::info!(
                    channel_id = channel.channel_id.0,
                    elapsed_secs = now.saturating_sub(channel.created_at),
                    "expired pending channel removed"
                );

                removed.push(channel.channel_id);
            }
        }

        let expiring = self
            .channel_store
            .replicas_matching(
                self.secret_id,
                ReplicaFilter {
                    status: vec![ChannelStatus::Pending],
                    exclude: self.exclude_self(),
                    ..Default::default()
                },
            )
            .await?;
        for member in expiring {
            if now.saturating_sub(member.created_at) > timeout {
                self.channel_store
                    .remove(
                        self.secret_id,
                        ChannelQuery::Replica {
                            channel_id: member.channel_id,
                            replica_id: member.replica_id,
                        },
                    )
                    .await?;

                #[cfg(feature = "logging")]
                tracing::info!(
                    channel_id = member.channel_id.0,
                    replica_id = member.replica_id.0,
                    elapsed_secs = now.saturating_sub(member.created_at),
                    "expired pending replica member removed"
                );

                if !removed.contains(&member.channel_id) {
                    removed.push(member.channel_id);
                }
            }
        }

        if let Some(own) = self.own_member().await?
            && own.status == ChannelStatus::Pending
            && now.saturating_sub(own.created_at) > timeout
            && self.release_if_unused(own.channel_id).await?
            && !removed.contains(&own.channel_id)
        {
            removed.push(own.channel_id);
        }
        for channel_id in removed.clone() {
            self.release_if_unused(channel_id).await?;
        }
        Ok(removed)
    }

    /// This device's own member row, whichever channel it is on.
    async fn own_member(&self) -> Result<Option<ReplicaMember>> {
        let Some(own) = self.replica_id else {
            return Ok(None);
        };
        Ok(self
            .channel_store
            .replicas_matching(
                self.secret_id,
                ReplicaFilter {
                    ids: vec![ReplicaId(own)],
                    ..Default::default()
                },
            )
            .await?
            .into_iter()
            .next())
    }

    /// Drop what is left of a channel no peer is recorded on any more.
    ///
    /// A channel's key outlives no pairing: once no helper and no other member
    /// is recorded on `channel_id`, a `Pending` own row there is the remainder
    /// of an unconfirmed pairing and goes, and so do the channel key and the
    /// pairing material. A `Paired` own row is the device's place in a group
    /// and keeps the channel. Returns whether the channel was released.
    pub(super) async fn release_if_unused(&mut self, channel_id: ChannelId) -> Result<bool> {
        if self
            .channel_store
            .load(self.secret_id, ChannelQuery::Helper { channel_id })
            .await?
            .and_then(|r| r.as_helper().cloned())
            .is_some()
        {
            return Ok(false);
        }
        let on_channel: Vec<_> = self
            .channel_store
            .replicas_matching(self.secret_id, Default::default())
            .await?
            .into_iter()
            .filter(|m| m.channel_id == channel_id)
            .collect();
        let own = self.replica_id.map(ReplicaId);
        if on_channel
            .iter()
            .any(|m| Some(m.replica_id) != own || m.status == ChannelStatus::Paired)
        {
            return Ok(false);
        }
        for member in on_channel {
            self.channel_store
                .remove(
                    self.secret_id,
                    ChannelQuery::Replica {
                        channel_id,
                        replica_id: member.replica_id,
                    },
                )
                .await?;
        }
        self.remove_channel_secrets(channel_id).await;
        Ok(true)
    }

    /// Remove the channel key and the pairing material held for `channel_id`.
    ///
    /// Absence is not an error: a pairing that never completed holds no key,
    /// and one that completed holds no pairing material.
    async fn remove_channel_secrets(&mut self, channel_id: ChannelId) {
        for kind in [
            SecretKind::SharedKey,
            SecretKind::PairingSecret,
            SecretKind::PairingContact,
        ] {
            let _ = self
                .secret_store
                .remove(self.secret_id, channel_id, kind)
                .await;
        }
    }

    /// The time-driven sweeps, shared by [`Self::tick`] and [`Self::process`]
    /// so the two cannot drift.
    ///
    /// Deliberately does **not** run the round tally: `process` runs it once
    /// at the end, over these events together with the message's own, and
    /// running it here as well would reorder what `process` reports.
    pub(super) async fn run_timeout_sweeps(&mut self) -> Vec<DeRecEvent> {
        if let ExpiredChannelCleanup::Enabled { timeout_in_secs } = self.timeouts.expired_channels {
            // Best effort: a cleanup failure must not fail the `process` or
            // `tick` that ran it, or a store hiccup would reject a message
            // that has nothing to do with expiry. Logged rather than dropped
            // silently — a store failing every sweep is worth seeing.
            if let Err(_error) = self.remove_expired_channels(timeout_in_secs).await {
                #[cfg(feature = "logging")]
                tracing::warn!(
                    error = %_error,
                    "expired-channel sweep failed; channels stay until the next one"
                );
            }
        }

        let mut events = self.check_sharing_round_timeouts().await;
        events.append(&mut self.check_unpair_timeouts().await);
        events.append(&mut self.check_recovery_timeouts().await);
        events.append(&mut self.check_replica_discovery_timeout().await);
        events
    }

    /// Conclude a replica version check whose members have stayed silent
    /// longer than
    /// [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response),
    /// on the versions already reported.
    async fn check_replica_discovery_timeout(&mut self) -> Vec<DeRecEvent> {
        let timeout = self.timeouts.get_share_response;
        let concluded =
            discovery::conclude_if_expired(&mut borrow_stores!(self), &local!(self), timeout).await;
        #[cfg(feature = "logging")]
        if let Err(error) = &concluded {
            tracing::warn!(
                error = %error,
                "replica discovery: concluding the timed-out check failed"
            );
        }
        concluded.unwrap_or_default()
    }

    /// Close every recovery whose share requests have waited longer than
    /// [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response),
    /// deciding it on the shares it holds.
    ///
    /// Each Helper still silent is reported as
    /// [`DeRecEvent::RecoverSecretFailed`] with error `"timeout"`, followed by
    /// the recovery's decision. The row is removed before the decision is
    /// reported, so a store failure leaves the recovery open for the next
    /// sweep rather than deciding it twice.
    async fn check_recovery_timeouts(&mut self) -> Vec<DeRecEvent> {
        let Ok(recoveries) = self
            .state_store
            .load_all(self.secret_id, StateKind::PendingRecovery)
            .await
        else {
            return vec![];
        };

        let now = now_secs();
        let mut events = Vec::new();
        for item in recoveries {
            let StateItem::PendingRecovery {
                secret_id,
                version,
                shares,
                pending,
                started_at,
            } = item
            else {
                continue;
            };
            if now.saturating_sub(started_at) <= self.timeouts.get_share_response.as_secs() {
                continue;
            }
            let Ok(helpers) =
                recovery::describe_helpers(&self.channel_store, self.secret_id, &shares).await
            else {
                continue;
            };
            if self
                .state_store
                .remove(
                    self.secret_id,
                    StateKey::PendingRecovery { secret_id, version },
                )
                .await
                .is_err()
            {
                continue;
            }

            let mut silent: Vec<ChannelId> = pending.into_iter().collect();
            silent.sort_unstable_by_key(|c| c.0);
            for channel_id in silent {
                #[cfg(feature = "logging")]
                tracing::warn!(
                    channel_id = channel_id.0,
                    secret_id,
                    version,
                    "recovery: helper timed out"
                );
                events.push(DeRecEvent::RecoverSecretFailed {
                    channel_id,
                    version,
                    error: "timeout".to_owned(),
                });
            }
            events.extend(recovery::settle(secret_id, version, &shares, &helpers));
        }
        events
    }

    /// Drop the owner's stored proof for every helper channel in `channels`
    /// that just settled round `version` as failed.
    ///
    /// Keeps the invariant in
    /// [`dispatch_share_to_helper`](crate::protocol::handlers::sharing): a
    /// stored proof is either confirmed by its helper or belongs to a round
    /// that is still open. Once a channel is failed — by an inbound
    /// rejection of any status, or by timing out — its proof for `version`
    /// can never be confirmed, so it is removed. Replica legs of a round
    /// have no proof and are never passed here.
    ///
    /// Per-channel store errors are swallowed: a cleanup failure must not
    /// fail the sweep that found the failure, and a straggling proof is
    /// retried the next time this channel fails a round.
    async fn drop_failed_proofs(&mut self, version: u32, channels: &[ChannelId]) {
        for &channel_id in channels {
            if let Err(_error) = self
                .share_store
                .remove_versions(self.secret_id, channel_id, &[version])
                .await
            {
                #[cfg(feature = "logging")]
                tracing::warn!(
                    channel_id = channel_id.0,
                    version,
                    error = %_error,
                    "failed-round proof cleanup failed; proof left in store"
                );
            }
        }
    }

    /// Drop the owner's proofs for the versions `channel_id` removed when it
    /// confirmed round `version`.
    ///
    /// A Helper that accepts a share applies the request's `keepVersion`: it
    /// removes every version it holds on the channel other than the accepted
    /// one and `keepVersion`, so the owner's proofs of those versions can no
    /// longer be answered. This mirrors that rule on the owner, and errs only
    /// towards keeping a proof:
    ///
    /// - A round with no recorded `keep_version` removes nothing.
    /// - A Helper ignores the `keepVersion` of a request older than a version it
    ///   already holds. When the owner holds a proof newer than `version` for
    ///   this channel the Helper may have accepted that one first, so nothing
    ///   is removed.
    /// - A version whose round is still waiting on this Helper may reach it
    ///   after `version` and be stored without pruning, so its proof stays.
    ///
    /// A proof left behind this way is removed by a later confirmation whose
    /// `keepVersion` is not that version. A confirmation arriving after its
    /// round has closed carries no `keepVersion` to apply and removes nothing.
    ///
    /// A store error is logged and swallowed, as in
    /// [`Self::drop_failed_proofs`].
    async fn drop_pruned_proofs(
        &mut self,
        channel_id: ChannelId,
        version: u32,
        keep_version: Option<u32>,
        unanswered: &[(u32, HashSet<ChannelId>)],
    ) {
        let Some(keep_version) = keep_version else {
            return;
        };
        let stored = match self.share_store.load(self.secret_id, channel_id, &[]).await {
            Ok(stored) => stored,
            Err(_error) => {
                #[cfg(feature = "logging")]
                tracing::warn!(
                    channel_id = channel_id.0,
                    version,
                    error = %_error,
                    "keep-version proof cleanup could not load the channel's proofs"
                );
                return;
            }
        };
        if stored.iter().any(|share| share.version > version) {
            return;
        }
        let mut dropped: Vec<u32> = stored
            .iter()
            .map(|share| share.version)
            .filter(|v| *v != version && *v != keep_version)
            .filter(|v| {
                !unanswered
                    .iter()
                    .any(|(round, pending)| round == v && pending.contains(&channel_id))
            })
            .collect();
        dropped.sort_unstable();
        dropped.dedup();
        if dropped.is_empty() {
            return;
        }
        if let Err(_error) = self
            .share_store
            .remove_versions(self.secret_id, channel_id, &dropped)
            .await
        {
            #[cfg(feature = "logging")]
            tracing::warn!(
                channel_id = channel_id.0,
                version,
                error = %_error,
                "keep-version proof cleanup failed; proofs left in store"
            );
        } else {
            #[cfg(feature = "logging")]
            tracing::debug!(
                channel_id = channel_id.0,
                version,
                removed = ?dropped,
                "owner proofs other than the confirmed keepVersion removed"
            );
        }
    }

    /// The number of subshares this device dispatched to `channel_id` at
    /// `version`, read from the tracking share it kept: the length of `subshares` in
    /// the `DeRecShare` inside the stored `CommittedDeRecShare`.
    ///
    /// A tracking share that is missing, fails to load, does not decode or
    /// holds no subshare (no valid share does) counts as one subshare, the weight
    /// every Helper holds by default.
    async fn tracked_weight(&self, channel_id: ChannelId, version: u32) -> u64 {
        use prost::Message as _;
        let Ok(shares) = self
            .share_store
            .load(self.secret_id, channel_id, &[version])
            .await
        else {
            return 1;
        };
        shares
            .iter()
            .find(|share| share.version == version)
            .and_then(|share| CommittedDeRecShare::decode(share.bytes.as_slice()).ok())
            .and_then(|committed| DeRecShare::decode(committed.de_rec_share.as_slice()).ok())
            .map(|share| share.subshares.len() as u64)
            .filter(|&subshares| subshares > 0)
            .unwrap_or(1)
    }

    /// Update the active sharing round based on events produced by `process_inner`.
    ///
    /// Moves channels from `pending` to `confirmed` or `failed` as
    /// `ShareConfirmed` / `ShareRejected` events arrive. When no channels
    /// remain pending, appends a [`DeRecEvent::SharingComplete`] summary.
    ///
    /// Every open round is offered the same event list and takes only the
    /// entries carrying its own version. Rounds overlap whenever a publish
    /// fires from an inbound path, so settling just one of them would strand
    /// the rest.
    pub(super) async fn update_sharing_round(&mut self, events: &mut Vec<DeRecEvent>) {
        let Ok(rounds) = self
            .state_store
            .load_all(self.secret_id, StateKind::SharingRound)
            .await
        else {
            return;
        };

        let mut produced: Vec<DeRecEvent> = Vec::new();

        // Which helpers each open round is still waiting on, as loaded and
        // before any of this batch is applied: a version a helper has not
        // yet answered may still reach it, so its proof is never pruned.
        let unanswered: Vec<(u32, HashSet<ChannelId>)> = rounds
            .iter()
            .filter_map(|item| match item {
                StateItem::SharingRound(round) => Some((round.version, round.pending.clone())),
                _ => None,
            })
            .collect();

        for item in rounds {
            let StateItem::SharingRound(round) = item else {
                continue;
            };
            let SharingRoundState {
                version: round_version,
                mut pending,
                mut confirmed,
                mut failed,
                mut pending_replicas,
                mut synced_replicas,
                mut behind_replicas,
                started_at,
                keep_version,
                threshold,
            } = *round;

            self.settle_one_round(
                events,
                &mut produced,
                round_version,
                &mut pending,
                &mut confirmed,
                &mut failed,
                &mut pending_replicas,
                &mut synced_replicas,
                &mut behind_replicas,
                started_at,
                keep_version,
                threshold,
                &unanswered,
            )
            .await;
        }

        events.append(&mut produced);
    }

    /// Settle every sharing round whose window has elapsed.
    ///
    /// More than one round can be open at a time: the pair-completion hook and
    /// the promotion inside [`verify_fingerprint`](Self::verify_fingerprint)
    /// both publish, and either can fire while an application-initiated round
    /// is still in flight. Each is keyed by its version and ages on its own
    /// clock, so they are swept independently rather than as one row.
    ///
    /// Members age on the same clock as helpers. A member that never answered
    /// settles as behind rather than failing the round — see
    /// `ReplicaSyncComplete`.
    async fn check_sharing_round_timeouts(&mut self) -> Vec<DeRecEvent> {
        let Ok(rounds) = self
            .state_store
            .load_all(self.secret_id, StateKind::SharingRound)
            .await
        else {
            return vec![];
        };

        let now = now_secs();
        let mut events = Vec::new();

        for item in rounds {
            let StateItem::SharingRound(round) = item else {
                continue;
            };
            let SharingRoundState {
                version,
                mut pending,
                confirmed,
                mut failed,
                mut pending_replicas,
                synced_replicas,
                mut behind_replicas,
                started_at,
                keep_version,
                threshold,
            } = *round;

            if now.saturating_sub(started_at) <= self.timeouts.sharing_round.as_secs() {
                continue;
            }
            let timed_out: Vec<ChannelId> = pending.drain().collect();
            for &channel_id in &timed_out {
                failed.insert(channel_id);
                events.push(DeRecEvent::ShareRejected {
                    channel_id,
                    version,
                    status: StatusEnum::Fail as i32,
                    memo: "timeout".to_owned(),
                });

                #[cfg(feature = "logging")]
                tracing::warn!(
                    channel_id = channel_id.0,
                    version,
                    "sharing round: helper timed out"
                );
            }
            self.drop_failed_proofs(version, &timed_out).await;
            let timed_out_replicas: Vec<ReplicaId> = pending_replicas.drain().collect();
            for replica_id in timed_out_replicas {
                behind_replicas.insert(replica_id);
                events.push(DeRecEvent::ReplicaSyncFailed {
                    replica_id: replica_id.0,
                    version,
                    reason: "timeout".to_owned(),
                });

                #[cfg(feature = "logging")]
                tracing::warn!(
                    replica_id = replica_id.0,
                    version,
                    "sharing round: replica timed out"
                );
            }

            let _ = self
                .state_store
                .save(
                    self.secret_id,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version,
                        pending,
                        confirmed,
                        failed,
                        pending_replicas,
                        synced_replicas,
                        behind_replicas,
                        started_at,
                        keep_version,
                        threshold,
                    })),
                )
                .await;
        }
        events
    }

    /// Drop local state for any pending unpair whose acknowledgement window has
    /// elapsed, returning an `Unpaired` event per dropped channel.
    async fn check_unpair_timeouts(&mut self) -> Vec<DeRecEvent> {
        let now = now_secs();
        let all = match self
            .state_store
            .load_all(self.secret_id, StateKind::PendingUnpair)
            .await
        {
            Ok(items) => items,
            Err(_) => return Vec::new(),
        };
        let expired: Vec<ChannelId> = all
            .into_iter()
            .filter_map(|item| match item {
                StateItem::PendingUnpair {
                    channel_id,
                    started_at,
                    ..
                } if now.saturating_sub(started_at) > self.timeouts.unpair_ack.as_secs() => {
                    Some(channel_id)
                }
                _ => None,
            })
            .collect();

        let mut events = Vec::with_capacity(expired.len());
        for cid in expired {
            let _ = self
                .state_store
                .remove(self.secret_id, StateKey::PendingUnpair { channel_id: cid })
                .await;
            if unpairing::drop_channel_state(&mut borrow_stores!(self), &local!(self), cid)
                .await
                .is_ok()
            {
                events.push(DeRecEvent::Unpaired { channel_id: cid });
            }
        }
        events
    }

    /// Apply `inbound` to one round and either complete it or persist it.
    ///
    /// Split out of [`Self::update_sharing_round`] so the per-round body stays
    /// readable now that several rounds can be open at once.
    ///
    /// Also carries the publisher-side half of the removal rule: a member told
    /// to leave completes its departure when it acknowledges the version that
    /// excludes it, which is what `synced_replicas` records. Receive-side
    /// reconciliation cannot do this — a publisher never receives the roster it
    /// just sent — so without it the device that ran the removal would keep the
    /// row forever and go on addressing a member that has already torn down.
    ///
    /// The replica leg is reported under its own event: different success rule,
    /// different key, and emitted only when the round had a replica leg at all,
    /// so a helpers-only publish stays silent there.
    #[allow(clippy::too_many_arguments)]
    async fn settle_one_round(
        &mut self,
        inbound: &[DeRecEvent],
        produced: &mut Vec<DeRecEvent>,
        round_version: u32,
        pending: &mut HashSet<ChannelId>,
        confirmed: &mut HashSet<ChannelId>,
        failed: &mut HashSet<ChannelId>,
        pending_replicas: &mut HashSet<ReplicaId>,
        synced_replicas: &mut HashSet<ReplicaId>,
        behind_replicas: &mut HashSet<ReplicaId>,
        started_at: u64,
        keep_version: Option<u32>,
        threshold: Option<u32>,
        unanswered: &[(u32, HashSet<ChannelId>)],
    ) {
        let events = inbound;
        let mut newly_failed: Vec<ChannelId> = Vec::new();
        let mut newly_confirmed: Vec<ChannelId> = Vec::new();
        for event in events.iter() {
            match event {
                DeRecEvent::ShareConfirmed {
                    channel_id,
                    version,
                } if *version == round_version => {
                    // Only a channel still `pending` is newly confirmed here.
                    // A channel already settled as `failed` — rejected or
                    // timed out, its proof already dropped — must not also
                    // land in `confirmed`: without this guard it is counted
                    // in both sets and `threshold_met` can include a channel
                    // whose proof no longer exists.
                    if pending.remove(channel_id) {
                        confirmed.insert(*channel_id);
                        newly_confirmed.push(*channel_id);
                    }
                }
                DeRecEvent::ShareRejected {
                    channel_id,
                    version,
                    ..
                } if *version == round_version => {
                    // Only a channel still `pending` is newly failed here. A
                    // timeout already drained it from `pending` and dropped
                    // its proof before this event list was built; without
                    // this guard the same `ShareRejected` — timeout-born or a
                    // genuine duplicate — would drop it a second time.
                    if pending.remove(channel_id) {
                        failed.insert(*channel_id);
                        newly_failed.push(*channel_id);
                    }
                }
                DeRecEvent::ReplicaSecretAcked {
                    from_replica_id,
                    version,
                    ..
                } if *version == round_version => {
                    if let Ok(replica_id) = ReplicaId::try_from(*from_replica_id) {
                        pending_replicas.remove(&replica_id);
                        synced_replicas.insert(replica_id);
                    }
                }
                DeRecEvent::ReplicaSyncRejected {
                    replica_id,
                    version,
                    ..
                } if *version == round_version => {
                    if let Ok(replica_id) = ReplicaId::try_from(*replica_id) {
                        pending_replicas.remove(&replica_id);
                        behind_replicas.insert(replica_id);
                    }
                }
                _ => {}
            }
        }

        self.drop_failed_proofs(round_version, &newly_failed).await;
        for channel_id in newly_confirmed {
            self.drop_pruned_proofs(channel_id, round_version, keep_version, unanswered)
                .await;
        }

        let is_complete = pending.is_empty() && pending_replicas.is_empty();
        let confirmed_count = confirmed.len();
        let failed_count = failed.len();

        if is_complete {
            let mut confirmed_weight: u64 = 0;
            for channel_id in confirmed.iter() {
                confirmed_weight += self.tracked_weight(*channel_id, round_version).await;
            }
            // A round written before its threshold was recorded is judged
            // against the builder's.
            let round_threshold = threshold.map_or(self.threshold as u64, u64::from);
            let threshold_met = confirmed_weight >= round_threshold;
            let _ = self
                .state_store
                .remove(
                    self.secret_id,
                    StateKey::SharingRound {
                        version: round_version,
                    },
                )
                .await;
            produced.push(DeRecEvent::SharingComplete {
                version: round_version,
                confirmed_count,
                failed_count,
                threshold_met,
            });

            if !synced_replicas.is_empty() || !behind_replicas.is_empty() {
                let mut synced: Vec<u64> = synced_replicas.iter().map(|r| r.0).collect();
                let mut behind: Vec<u64> = behind_replicas.iter().map(|r| r.0).collect();
                // Sets are unordered; sort so the event is reproducible.
                synced.sort_unstable();
                behind.sort_unstable();

                #[cfg(feature = "logging")]
                tracing::info!(
                    version = round_version,
                    synced_count = synced.len(),
                    behind_count = behind.len(),
                    "replica sync round complete"
                );

                produced.push(DeRecEvent::ReplicaSyncComplete {
                    version: round_version,
                    synced,
                    behind,
                });
            }

            #[cfg(feature = "logging")]
            tracing::info!(
                version = round_version,
                confirmed_count,
                failed_count,
                threshold_met,
                "sharing round complete"
            );
        } else {
            let _ = self
                .state_store
                .save(
                    self.secret_id,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: round_version,
                        pending: mem::take(pending),
                        confirmed: mem::take(confirmed),
                        failed: mem::take(failed),
                        pending_replicas: mem::take(pending_replicas),
                        synced_replicas: mem::take(synced_replicas),
                        behind_replicas: mem::take(behind_replicas),
                        started_at,
                        keep_version,
                        threshold,
                    })),
                )
                .await;
        }
    }
}

#[cfg(test)]
mod expired_channel_sweep_tests {
    use super::*;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
        InMemUserSecretStore, NoopTransport, run_async,
    };
    use crate::protocol::types::{
        ChannelRecord, ChannelStatus, ExpiredChannelCleanup, HelperChannel, ReplicaMember,
        ReplicaRole, SecretValue, Timeouts,
    };
    use crate::types::ReplicaId;
    use derec_proto::{Protocol, SenderKind, TransportProtocol};
    use std::collections::HashMap;
    use std::time::Duration;

    const SECRET_ID: u64 = 0xC1;

    fn endpoint() -> TransportProtocol {
        TransportProtocol {
            uri: "https://peer.example.com".to_owned(),
            protocol: Protocol::Https as i32,
        }
    }

    /// Seed one channel whose `created_at` is `age_secs` in the past.
    async fn seed(
        channels: &mut InMemChannelStore,
        cid: u64,
        status: ChannelStatus,
        age_secs: u64,
    ) {
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Helper(HelperChannel {
                    channel_id: ChannelId(cid),
                    transports: vec![endpoint()],
                    communication_info: HashMap::new(),
                    status,
                    created_at: now_secs().saturating_sub(age_secs),
                    peer_role: SenderKind::Helper,
                    weight: 1,
                }),
            )
            .await
            .expect("seed channel");
    }

    fn build(
        channels: InMemChannelStore,
        policy: ExpiredChannelCleanup,
        timeout_in_secs: u64,
    ) -> DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemStateStore,
        NoopTransport,
    > {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(channels)
            .with_share_store(InMemShareStore::default())
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemStateStore)
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(2)
            .with_timeouts(Timeouts {
                sharing_round: Duration::from_secs(timeout_in_secs),
                unpair_ack: Duration::from_secs(timeout_in_secs),
                inbound_message: Duration::from_secs(timeout_in_secs),
                get_share_response: Duration::from_secs(timeout_in_secs),
                pairing: Duration::from_secs(timeout_in_secs),
                expired_channels: policy,
            })
            .build()
            .expect("test protocol builds")
    }

    /// The manual sweep honours its own argument, not the configured
    /// policy — `Disabled` means "I drive this myself", not "off".
    #[test]
    fn manual_sweep_works_under_disabled_policy() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
            let removed = protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert_eq!(removed, vec![ChannelId(1)]);
            assert!(channels.helper_rows.lock().unwrap().is_empty());
        });
    }

    /// Seed one replica member on the group channel.
    async fn seed_member(
        channels: &mut InMemChannelStore,
        replica_id: u64,
        status: ChannelStatus,
        age_secs: u64,
    ) {
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: ChannelId(9000),
                    replica_id: ReplicaId(replica_id),
                    transports: vec![endpoint()],
                    communication_info: HashMap::new(),
                    role: ReplicaRole::Destination,
                    status,
                    created_at: now_secs().saturating_sub(age_secs),
                    handover_channel: None,
                }),
            )
            .await
            .expect("seed member");
    }

    /// A replica pairing that never completed expires like any other, but
    /// this device's own row is exempt: it is a roster entry, not a pending
    /// handshake, and sweeping it would erase the group's self-reference.
    #[test]
    fn sweep_removes_expired_replica_members_but_never_this_device() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed_member(&mut seeded, 7, ChannelStatus::Pending, 600).await;
            seed_member(&mut seeded, 8, ChannelStatus::Paired, 600).await;
            seed_member(&mut seeded, 9, ChannelStatus::Pending, 600).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
            protocol.replica_id = Some(9);
            let removed = protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert_eq!(
                removed,
                vec![ChannelId(9000)],
                "members share one channel, so the group is reported once"
            );
            let rows = channels.member_rows.lock().unwrap();
            assert!(
                !rows.contains_key(&(SECRET_ID, 7)),
                "expired pending member"
            );
            assert!(rows.contains_key(&(SECRET_ID, 8)), "paired member survives");
            assert!(rows.contains_key(&(SECRET_ID, 9)), "own row is exempt");
        });
    }

    /// `Disabled` suppresses the automatic sweep inside `process()`, so an
    /// over-age channel survives because nothing swept it.
    #[test]
    fn disabled_policy_leaves_channel_for_manual_sweep() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
            let _ = protocol.process(&[]).await;

            assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
        });
    }

    /// The policy's timeout governs the automatic sweep, not
    /// `timeout_in_secs` — verified by setting them to different values
    /// and choosing an age between the two.
    #[test]
    fn policy_timeout_governs_not_protocol_timeout() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 120).await;

            let mut protocol = build(
                channels.clone(),
                ExpiredChannelCleanup::Enabled {
                    timeout_in_secs: 60,
                },
                3600,
            );
            let _ = protocol.process(&[]).await;

            assert!(channels.helper_rows.lock().unwrap().is_empty());
        });
    }

    /// `Paired` channels are never swept, regardless of age.
    #[test]
    fn paired_channels_are_never_removed() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Paired, 99_999).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::default(), 300);
            let removed = protocol
                .remove_expired_channels(1)
                .await
                .expect("sweep succeeds");

            assert!(removed.is_empty());
            assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
        });
    }

    /// Removing a channel also drops its pairing material, so a stale
    /// handshake leaves nothing behind in the secret store.
    #[test]
    fn removal_drops_pairing_material() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let secrets = InMemSecretStore::default();
            let mut seeded = channels.clone();
            let mut seeded_secrets = secrets.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;
            seeded_secrets
                .save(
                    SECRET_ID,
                    ChannelId(1),
                    SecretValue::PairingContact(Default::default()),
                )
                .await
                .expect("seed pairing contact");

            let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
                .with_channel_store(channels.clone())
                .with_share_store(InMemShareStore::default())
                .with_secret_store(secrets.clone())
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_transport(NoopTransport)
                .with_state_store(InMemStateStore)
                .with_own_transports(["https://owner.example.com"])
                .with_threshold(2)
                .with_timeouts(Timeouts {
                    expired_channels: ExpiredChannelCleanup::Disabled,
                    ..Default::default()
                })
                .build()
                .expect("test protocol builds");

            let removed = protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert_eq!(removed, vec![ChannelId(1)]);
            assert!(secrets.data.lock().unwrap().is_empty());
        });
    }

    /// An explicit zero is not clamped — the minimum-of-1 rule guards the
    /// automatic sweep only. A `Pending` channel from an earlier second
    /// goes; the `Paired` one stays.
    #[test]
    fn explicit_zero_sweeps_pending_from_earlier_seconds() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 1).await;
            seed(&mut seeded, 2, ChannelStatus::Paired, 1).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
            let removed = protocol
                .remove_expired_channels(0)
                .await
                .expect("sweep succeeds");

            assert_eq!(removed, vec![ChannelId(1)]);
            assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
        });
    }

    /// The comparison is strict, so a channel created within the current
    /// second survives even the most aggressive threshold. This pins the
    /// boundary the automatic sweep relies on to avoid deleting pairings
    /// the instant they start.
    #[test]
    fn zero_age_channel_survives_zero_threshold() {
        run_async(async {
            let channels = InMemChannelStore::default();
            let mut seeded = channels.clone();
            seed(&mut seeded, 1, ChannelStatus::Pending, 0).await;

            let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
            let removed = protocol
                .remove_expired_channels(0)
                .await
                .expect("sweep succeeds");

            assert!(removed.is_empty());
            assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
        });
    }

    fn build_with_secrets(
        channels: InMemChannelStore,
        secrets: InMemSecretStore,
    ) -> DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemStateStore,
        NoopTransport,
    > {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(channels)
            .with_share_store(InMemShareStore::default())
            .with_secret_store(secrets)
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemStateStore)
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(2)
            .with_timeouts(Timeouts {
                expired_channels: ExpiredChannelCleanup::Disabled,
                ..Default::default()
            })
            .build()
            .expect("test protocol builds")
    }

    async fn seed_member_on(
        channels: &mut InMemChannelStore,
        channel_id: u64,
        replica_id: u64,
        status: ChannelStatus,
        age_secs: u64,
    ) {
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: ChannelId(channel_id),
                    replica_id: ReplicaId(replica_id),
                    transports: vec![endpoint()],
                    communication_info: HashMap::new(),
                    role: ReplicaRole::Destination,
                    status,
                    created_at: now_secs().saturating_sub(age_secs),
                    handover_channel: None,
                }),
            )
            .await
            .expect("seed member");
    }

    async fn seed_key(secrets: &mut InMemSecretStore, channel_id: u64) {
        secrets
            .save(
                SECRET_ID,
                ChannelId(channel_id),
                SecretValue::SharedKey([3u8; 32]),
            )
            .await
            .expect("seed shared key");
    }

    fn has_key(secrets: &InMemSecretStore, channel_id: u64) -> bool {
        secrets.data.lock().unwrap().contains_key(&(
            SECRET_ID,
            channel_id,
            SecretKind::SharedKey as u8,
        ))
    }

    /// A pairing that expired unconfirmed leaves no channel key: with the
    /// record gone, a retained key would decrypt the peer's messages again.
    #[test]
    fn an_expired_helper_pairing_loses_its_channel_key() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let (mut c, mut s) = (channels.clone(), secrets.clone());
            seed(&mut c, 1, ChannelStatus::Pending, 600).await;
            seed_key(&mut s, 1).await;

            let mut protocol = build_with_secrets(channels, secrets.clone());
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(!has_key(&secrets, 1));
        });
    }

    /// A replica pairing whose only peer expired leaves no channel key.
    #[test]
    fn an_expired_replica_pairing_loses_its_channel_key() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let (mut c, mut s) = (channels.clone(), secrets.clone());
            seed_member_on(&mut c, 9100, 7, ChannelStatus::Pending, 600).await;
            seed_key(&mut s, 9100).await;

            let mut protocol = build_with_secrets(channels, secrets.clone());
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(!has_key(&secrets, 9100));
        });
    }

    /// Members of a group share one channel and one key, so an expired
    /// member does not take the key the remaining members still use.
    #[test]
    fn an_expired_member_leaves_the_key_of_a_channel_still_in_use() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let (mut c, mut s) = (channels.clone(), secrets.clone());
            seed_member_on(&mut c, 9000, 7, ChannelStatus::Pending, 600).await;
            seed_member_on(&mut c, 9000, 8, ChannelStatus::Paired, 600).await;
            seed_key(&mut s, 9000).await;

            let mut protocol = build_with_secrets(channels.clone(), secrets.clone());
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(has_key(&secrets, 9000));
            assert!(
                channels
                    .member_rows
                    .lock()
                    .unwrap()
                    .contains_key(&(SECRET_ID, 8))
            );
        });
    }

    /// This device's own `Pending` row belongs to the pairing, not to a
    /// group: once no peer remains on its channel and it has expired, it goes
    /// with the key.
    #[test]
    fn an_expired_own_row_with_no_peer_left_goes_with_the_key() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let (mut c, mut s) = (channels.clone(), secrets.clone());
            seed_member_on(&mut c, 9100, 7, ChannelStatus::Pending, 600).await;
            seed_member_on(&mut c, 9100, 9, ChannelStatus::Pending, 600).await;
            seed_key(&mut s, 9100).await;

            let mut protocol = build_with_secrets(channels.clone(), secrets.clone());
            protocol.replica_id = Some(9);
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(channels.member_rows.lock().unwrap().is_empty());
            assert!(!has_key(&secrets, 9100));
        });
    }

    /// A pending pairing recorded on the group channel expires without taking
    /// the group key: the channel is still in use by the group.
    #[test]
    fn an_expired_pairing_on_the_group_channel_leaves_the_group_key() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let (mut c, mut s) = (channels.clone(), secrets.clone());
            seed_member_on(&mut c, 9000, 9, ChannelStatus::Paired, 600).await;
            seed_member_on(&mut c, 9000, 8, ChannelStatus::Paired, 600).await;
            seed(&mut c, 9000, ChannelStatus::Pending, 600).await;
            seed_key(&mut s, 9000).await;

            let mut protocol = build_with_secrets(channels.clone(), secrets.clone());
            protocol.replica_id = Some(9);
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(channels.helper_rows.lock().unwrap().is_empty());
            assert_eq!(channels.member_rows.lock().unwrap().len(), 2);
            assert!(has_key(&secrets, 9000), "the group key survives the sweep");
        });
    }

    /// An initiator waiting for its peer holds only its own `Pending` row; a
    /// pairing that has not expired is not swept.
    #[test]
    fn a_fresh_own_row_awaiting_its_peer_survives() {
        run_async(async {
            let (channels, secrets) = (InMemChannelStore::default(), InMemSecretStore::default());
            let mut c = channels.clone();
            seed_member_on(&mut c, 9100, 9, ChannelStatus::Pending, 0).await;

            let mut protocol = build_with_secrets(channels.clone(), secrets);
            protocol.replica_id = Some(9);
            protocol
                .remove_expired_channels(60)
                .await
                .expect("sweep succeeds");

            assert!(
                channels
                    .member_rows
                    .lock()
                    .unwrap()
                    .contains_key(&(SECRET_ID, 9))
            );
        });
    }
}

#[cfg(test)]
mod sharing_round_outcome_tests {
    use super::*;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, NoopTransport, run_async,
    };
    use crate::types::ReplicaId;

    use crate::primitives::sharing::request;
    use crate::protocol::types::{
        ChannelRecord, ChannelStatus, HelperChannel, HelperFilter, Secret, SharingRoundState,
        UserSecret,
    };
    use crate::protocol::{CollectedShare, ExpiredChannelCleanup};
    use derec_proto::{
        DeRecResult, DeRecSecret, GetShareResponseMessage, Protocol, SenderKind, StatusEnum,
        TransportProtocol,
    };
    use std::collections::{HashMap, HashSet};
    use std::time::Duration;

    const SECRET_ID: u64 = 0xF00D;

    // The persisting double: the accumulator reads back what it wrote, so a
    // no-op state store would make every assertion here vacuous.
    type TestProtocol = DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        NoopTransport,
    >;

    fn build(threshold: usize) -> TestProtocol {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(InMemChannelStore::default())
            .with_share_store(InMemShareStore::default())
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemPersistedStateStore::default())
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(threshold)
            .build()
            .expect("test protocol builds")
    }

    async fn seed_round(
        protocol: &mut TestProtocol,
        version: u32,
        helpers: &[u64],
        members: &[u64],
    ) {
        protocol
            .state_store
            .save(
                SECRET_ID,
                StateItem::SharingRound(Box::new(SharingRoundState {
                    version,
                    pending: helpers.iter().copied().map(ChannelId).collect(),
                    confirmed: HashSet::new(),
                    failed: HashSet::new(),
                    pending_replicas: members.iter().copied().map(ReplicaId).collect(),
                    synced_replicas: HashSet::new(),
                    behind_replicas: HashSet::new(),
                    started_at: now_secs(),
                    keep_version: None,
                    threshold: None,
                })),
            )
            .await
            .expect("seed round");
    }

    /// Two rounds open at once each settle on their own.
    ///
    /// Rounds are not started only by `start(ProtectSecret)`: the
    /// pair-completion hook and the promotion inside `verify_fingerprint` both
    /// publish while handling an *inbound* message, so a second round can open
    /// under an application that never asked for one. When the row was keyed by
    /// `secret_id` alone the newcomer replaced its predecessor and **neither**
    /// finished — responses for the replaced round landed against state that no
    /// longer existed, and no `SharingComplete` was emitted for either. The
    /// application could not defend against it, having no view of round state.
    #[test]
    fn two_open_rounds_settle_independently() {
        run_async(async {
            let mut protocol = build(2);
            seed_round(&mut protocol, 7, &[9001], &[]).await;
            seed_round(&mut protocol, 8, &[9002], &[]).await;

            // Both rows survive; the second did not displace the first.
            for version in [7u32, 8] {
                assert!(
                    protocol
                        .state_store
                        .load(SECRET_ID, StateKey::SharingRound { version })
                        .await
                        .expect("load")
                        .is_some(),
                    "round v{version} must still be in flight"
                );
            }

            // Answer only v7. Its event carries the version, so v8 must ignore it.
            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(9001),
                version: 7,
            }];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 7, .. })),
                "v7 completes once its only helper confirms; got {events:?}"
            );
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 8, .. })),
                "v8 has an outstanding helper and must not complete; got {events:?}"
            );
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::SharingRound { version: 7 })
                    .await
                    .expect("load")
                    .is_none(),
                "a completed round leaves no row"
            );

            // v8 is untouched and still settles on its own answer.
            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(9002),
                version: 8,
            }];
            protocol.update_sharing_round(&mut events).await;
            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 8, .. })),
                "v8 completes when its own helper answers; got {events:?}"
            );
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::SharingRound { version: 8 })
                    .await
                    .expect("load")
                    .is_none(),
                "a completed round leaves no row"
            );
        });
    }

    /// A round with no further traffic still reaches a terminal state.
    ///
    /// Timeouts are otherwise only evaluated inside `process`, so a publish
    /// whose helpers all go quiet has nothing left to trigger it. `tick` is
    /// the entry point a scheduler calls, and it must both fail the silent
    /// participants *and* close the round: reporting failures while leaving
    /// the round open would still strand an application waiting on
    /// `SharingComplete`.
    #[test]
    fn tick_closes_a_round_that_no_message_will_ever_finish() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.sharing_round = Duration::from_secs(60);

            // A round started well outside the timeout window, with one helper
            // and one member that never answered.
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 3,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: [ChannelId(9002)].into_iter().collect(),
                        failed: HashSet::new(),
                        pending_replicas: [ReplicaId(1002)].into_iter().collect(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs().saturating_sub(600),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let events = protocol.tick().await;

            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::ShareRejected { channel_id, memo, .. }
                        if *channel_id == ChannelId(9001) && memo == "timeout"
                )),
                "the silent helper is failed; got {events:?}"
            );
            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::ReplicaSyncFailed { replica_id, reason, .. }
                        if *replica_id == 1002 && reason == "timeout"
                )),
                "the silent member is reported behind; got {events:?}"
            );
            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 3, .. })),
                "the round must actually close, not just report failures; got {events:?}"
            );
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::SharingRound { version: 3 })
                    .await
                    .expect("load")
                    .is_none(),
                "a closed round leaves no state row behind"
            );
        });
    }

    /// The sweep inside `process` saves the failed participants before the
    /// message is even decoded, so a message that then fails must still
    /// hand back the timeouts and the closed round.
    #[test]
    fn a_failing_process_still_reports_the_timeouts_it_settled() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.sharing_round = Duration::from_secs(60);
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 3,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: [ChannelId(9002)].into_iter().collect(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs().saturating_sub(600),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let error = protocol
                .process(&[0xFF, 0xFF, 0xFF])
                .await
                .expect_err("garbage bytes do not decode");

            assert!(error.channel_id.is_none());
            assert!(
                error.events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::ShareRejected { channel_id, memo, .. }
                        if *channel_id == ChannelId(9001) && memo == "timeout"
                )),
                "the timeout travels with the error; got {:?}",
                error.events
            );
            assert!(
                error
                    .events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 3, .. })),
                "the round closes on the failing call; got {:?}",
                error.events
            );
            assert!(
                protocol.tick().await.is_empty(),
                "settled deadlines are not reported twice"
            );
        });
    }

    /// `tick` runs the unpair sweep too, not only the sharing round.
    ///
    /// An unpair sent under `UnpairAck::Required` keeps local state alive
    /// until the peer acknowledges. A peer that never answers would otherwise
    /// pin that state forever, since nothing else would arrive to trigger the
    /// check.
    #[test]
    fn tick_expires_an_unacknowledged_unpair() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.unpair_ack = Duration::from_secs(60);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingUnpair {
                        channel_id: ChannelId(4242),
                        started_at: now_secs().saturating_sub(600),
                        drop_on_rejection: false,
                    },
                )
                .await
                .expect("seed pending unpair");

            let events = protocol.tick().await;

            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::Unpaired { channel_id } if *channel_id == ChannelId(4242)
                )),
                "the unacknowledged unpair completes on the timeout; got {events:?}"
            );
            assert!(
                protocol
                    .state_store
                    .load(
                        SECRET_ID,
                        StateKey::PendingUnpair {
                            channel_id: ChannelId(4242)
                        }
                    )
                    .await
                    .expect("load")
                    .is_none(),
                "the pending row is consumed"
            );
        });
    }

    /// A pending unpair still inside its window survives a `tick`.
    #[test]
    fn tick_leaves_a_recent_unpair_pending() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.unpair_ack = Duration::from_secs(600);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingUnpair {
                        channel_id: ChannelId(4242),
                        started_at: now_secs(),
                        drop_on_rejection: false,
                    },
                )
                .await
                .expect("seed pending unpair");

            let events = protocol.tick().await;

            assert!(events.is_empty(), "got {events:?}");
            assert!(
                protocol
                    .state_store
                    .load(
                        SECRET_ID,
                        StateKey::PendingUnpair {
                            channel_id: ChannelId(4242)
                        }
                    )
                    .await
                    .expect("load")
                    .is_some(),
                "the acknowledgement window has not elapsed"
            );
        });
    }

    /// Shares of a recoverable secret named `name`, split at threshold 2
    /// over `channels`, as the Helpers on those channels would answer them.
    fn recovery_shares(name: &str, channels: &[u64]) -> Vec<CollectedShare> {
        use crate::extensions::derec_result::DeRecResultExt as _;
        use prost::Message as _;
        let secret = Secret {
            secrets: vec![UserSecret {
                id: vec![0x01],
                name: name.to_owned(),
                data: b"seed".to_vec(),
            }],
            threshold: Some(2),
            ..Default::default()
        };
        let payload = DeRecSecret {
            secret_data: secret.encode(),
            creation_time: None,
            helper_threshold_for_recovery: 2,
            helper_threshold_for_confirming_share_receipt: 2,
            helpers: Vec::new(),
        }
        .encode_to_vec();
        let weighted: Vec<_> = channels.iter().map(|&c| (ChannelId(c), 1)).collect();
        let split = request::split(&weighted, 77, 1, &payload, 2).expect("split");
        channels
            .iter()
            .map(|&c| CollectedShare {
                channel_id: ChannelId(c),
                response: GetShareResponseMessage {
                    result: Some(DeRecResult::ok()),
                    committed_de_rec_share: split.shares[&ChannelId(c)].encode_to_vec(),
                    secret_id: 77,
                    version: 1,
                    ..Default::default()
                },
            })
            .collect()
    }

    /// A recovery whose Helpers go quiet still decides. `tick` reports each
    /// silent Helper as timed out and settles on the shares already in hand.
    #[test]
    fn tick_settles_a_recovery_whose_helpers_went_silent() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.get_share_response = Duration::from_secs(60);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingRecovery {
                        secret_id: 77,
                        version: 1,
                        shares: recovery_shares("real", &[9001, 9002]),
                        pending: [ChannelId(9003)].into_iter().collect(),
                        started_at: now_secs().saturating_sub(600),
                    },
                )
                .await
                .expect("seed pending recovery");

            let events = protocol.tick().await;

            match events.as_slice() {
                [
                    DeRecEvent::RecoverSecretFailed {
                        channel_id,
                        version: 1,
                        error,
                    },
                    DeRecEvent::SecretRecovered { secret },
                ] => {
                    assert_eq!(*channel_id, ChannelId(9003));
                    assert_eq!(error, "timeout");
                    assert_eq!(secret.secrets[0].name, "real");
                }
                other => panic!("expected a timeout then SecretRecovered, got {other:?}"),
            }
            assert!(
                protocol
                    .state_store
                    .load(
                        SECRET_ID,
                        StateKey::PendingRecovery {
                            secret_id: 77,
                            version: 1
                        }
                    )
                    .await
                    .expect("load")
                    .is_none(),
                "the recovery is closed"
            );
        });
    }

    /// The timeout settles a recovery holding two complete secrets as a
    /// conflict, never by picking one.
    #[test]
    fn tick_settles_conflicting_shares_as_a_conflict() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.get_share_response = Duration::from_secs(60);

            let mut shares = recovery_shares("forged", &[9001, 9002]);
            shares.extend(recovery_shares("real", &[9003, 9004]));
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingRecovery {
                        secret_id: 77,
                        version: 1,
                        shares,
                        pending: [ChannelId(9005)].into_iter().collect(),
                        started_at: now_secs().saturating_sub(600),
                    },
                )
                .await
                .expect("seed pending recovery");

            let events = protocol.tick().await;

            assert!(
                matches!(
                    events.as_slice(),
                    [
                        DeRecEvent::RecoverSecretFailed { .. },
                        DeRecEvent::RecoveryConflict { version: 1, candidates, disputed_by },
                    ] if candidates.len() == 2 && disputed_by.is_empty()
                ),
                "got {events:?}"
            );
        });
    }

    /// A recovery still inside its window survives a `tick`.
    #[test]
    fn tick_leaves_a_recent_recovery_open() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.get_share_response = Duration::from_secs(600);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingRecovery {
                        secret_id: 77,
                        version: 1,
                        shares: recovery_shares("real", &[9001, 9002]),
                        pending: [ChannelId(9003)].into_iter().collect(),
                        started_at: now_secs(),
                    },
                )
                .await
                .expect("seed pending recovery");

            let events = protocol.tick().await;

            assert!(events.is_empty(), "got {events:?}");
            assert!(
                protocol
                    .state_store
                    .load(
                        SECRET_ID,
                        StateKey::PendingRecovery {
                            secret_id: 77,
                            version: 1
                        }
                    )
                    .await
                    .expect("load")
                    .is_some(),
                "a Helper's answer is still due"
            );
        });
    }

    /// A version check whose members go quiet still concludes. Past
    /// `get_share_response`, `tick` closes it on the versions already
    /// reported; a member that never answered contributes nothing.
    #[test]
    fn tick_concludes_a_discovery_whose_members_went_silent() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.get_share_response = Duration::from_secs(60);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingReplicaDiscovery {
                        local_version: 3,
                        pending: HashSet::from([ReplicaId(1003)]),
                        reported: HashMap::from([(ReplicaId(1002), 2)]),
                        started_at: now_secs().saturating_sub(600),
                    },
                )
                .await
                .expect("seed pending discovery");

            let events = protocol.tick().await;

            assert!(
                matches!(
                    events.as_slice(),
                    [DeRecEvent::ReplicaDiscoveryComplete {
                        local_version: 3,
                        group_version: 2,
                        fetched_from: None,
                    }]
                ),
                "got {events:?}"
            );
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::PendingReplicaDiscovery)
                    .await
                    .expect("load")
                    .is_none(),
                "the check is closed"
            );
        });
    }

    /// A version check still inside its window survives a `tick`.
    #[test]
    fn tick_leaves_a_recent_discovery_open() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.get_share_response = Duration::from_secs(600);

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::PendingReplicaDiscovery {
                        local_version: 3,
                        pending: HashSet::from([ReplicaId(1003)]),
                        reported: HashMap::new(),
                        started_at: now_secs(),
                    },
                )
                .await
                .expect("seed pending discovery");

            let events = protocol.tick().await;

            assert!(events.is_empty(), "got {events:?}");
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::PendingReplicaDiscovery)
                    .await
                    .expect("load")
                    .is_some(),
                "a member's answer is still due"
            );
        });
    }

    /// Expired-channel cleanup is part of `tick`, and follows the same
    /// configuration `process` honours rather than a rule of its own.
    ///
    /// Disabled is the default, so a `tick` on a protocol that never opted in
    /// must leave a stale pending channel alone; `remove_expired_channels`
    /// stays available for callers that want to sweep explicitly.
    #[test]
    fn tick_honours_the_expired_channel_policy() {
        run_async(async {
            for (cleanup, expect_removed) in [
                (ExpiredChannelCleanup::Disabled, false),
                (ExpiredChannelCleanup::Enabled { timeout_in_secs: 1 }, true),
            ] {
                let mut protocol = build(2);
                protocol.timeouts.expired_channels = cleanup;
                protocol
                    .channel_store
                    .save(
                        SECRET_ID,
                        ChannelRecord::Helper(HelperChannel {
                            channel_id: ChannelId(77),
                            transports: vec![TransportProtocol {
                                uri: "https://stale.example".to_owned(),
                                protocol: Protocol::Https as i32,
                            }],
                            communication_info: HashMap::new(),
                            peer_role: SenderKind::Helper,
                            status: ChannelStatus::Pending,
                            created_at: now_secs().saturating_sub(3600),
                            weight: 1,
                        }),
                    )
                    .await
                    .expect("seed stale pending channel");

                let _ = protocol.tick().await;

                let gone = protocol
                    .channel_store
                    .helpers(SECRET_ID, HelperFilter::default())
                    .await
                    .expect("helpers")
                    .is_empty();
                assert_eq!(
                    gone, expect_removed,
                    "cleanup {cleanup:?}: expected removed={expect_removed}"
                );
            }
        });
    }

    /// `tick` is safe to call on an idle protocol — the common case for a
    /// scheduler firing on a quiet partition.
    #[test]
    fn tick_on_an_idle_protocol_does_nothing() {
        run_async(async {
            let mut protocol = build(2);
            let events = protocol.tick().await;
            assert!(events.is_empty(), "got {events:?}");
        });
    }

    /// A round still inside its window is left alone: `tick` must not cut
    /// short a publish whose helpers are merely slow.
    #[test]
    fn tick_leaves_a_round_inside_its_window_open() {
        run_async(async {
            let mut protocol = build(2);
            protocol.timeouts.sharing_round = Duration::from_secs(600);
            seed_round(&mut protocol, 4, &[9001], &[1002]).await;

            let events = protocol.tick().await;

            assert!(events.is_empty(), "got {events:?}");
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::SharingRound { version: 4 })
                    .await
                    .expect("load")
                    .is_some(),
                "the round is still in flight"
            );
        });
    }

    /// The regression a shared group channel creates: two members answering on
    /// one channel must settle independently. Keyed on `ChannelId` they would
    /// collapse, and the first ack would complete the round for both.
    #[test]
    fn members_on_one_channel_settle_independently() {
        run_async(async {
            let mut protocol = build(2);
            seed_round(&mut protocol, 4, &[9001], &[1002, 1003]).await;

            // Only member 1002 answers.
            let mut events = vec![
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9001),
                    version: 4,
                },
                DeRecEvent::ReplicaSecretAcked {
                    channel_id: ChannelId(5001),
                    from_replica_id: 1002,
                    secret_id: SECRET_ID,
                    version: 4,
                    status: 0,
                    memo: String::new(),
                },
            ];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { .. })),
                "the round must stay open while member 1003 has not answered"
            );

            // 1003 answers on the same channel; now the round closes.
            let mut events = vec![DeRecEvent::ReplicaSecretAcked {
                channel_id: ChannelId(5001),
                from_replica_id: 1003,
                secret_id: SECRET_ID,
                version: 4,
                status: 0,
                memo: String::new(),
            }];
            protocol.update_sharing_round(&mut events).await;

            let sync = events
                .iter()
                .find_map(|e| match e {
                    DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
                        Some((synced.clone(), behind.clone()))
                    }
                    _ => None,
                })
                .expect("replica leg must report its own completion");
            assert_eq!(sync, (vec![1002, 1003], vec![]));
        });
    }

    /// F2: a member that never answers is `behind`, and does not fail the
    /// round — the helper leg alone decides `threshold_met`.
    #[test]
    fn an_unreachable_member_leaves_the_round_successful() {
        run_async(async {
            let mut protocol = build(2);
            seed_round(&mut protocol, 4, &[9001, 9002], &[1003]).await;

            let mut events = vec![
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9001),
                    version: 4,
                },
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9002),
                    version: 4,
                },
                DeRecEvent::ReplicaSyncFailed {
                    replica_id: 1003,
                    version: 4,
                    reason: "transport unreachable".to_owned(),
                },
            ];
            // A dispatch failure never entered `pending_replicas`, so the round
            // is settled by the helper leg alone; drain the member by hand to
            // mirror what `start` records at dispatch time.
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 4,
                        pending: HashSet::from([ChannelId(9001), ChannelId(9002)]),
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::from([ReplicaId(1003)]),
                        started_at: now_secs(),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed");
            protocol.update_sharing_round(&mut events).await;

            let complete = events
                .iter()
                .find_map(|e| match e {
                    DeRecEvent::SharingComplete { threshold_met, .. } => Some(*threshold_met),
                    _ => None,
                })
                .expect("helper leg must complete");
            assert!(
                complete,
                "an unreachable replica must not fail the helper round"
            );

            let sync = events
                .iter()
                .find_map(|e| match e {
                    DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
                        Some((synced.clone(), behind.clone()))
                    }
                    _ => None,
                })
                .expect("replica leg must report its own completion");
            assert_eq!(sync, (vec![], vec![1003]), "the member is reported behind");
        });
    }

    /// F1: a member refusing with a conflict lands in `behind`, reported
    /// separately from the helper leg's own verdict.
    #[test]
    fn a_conflicting_member_is_reported_behind() {
        run_async(async {
            let mut protocol = build(3);
            seed_round(&mut protocol, 4, &[9001, 9002, 9003], &[1002, 1003]).await;

            let mut events = vec![
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9001),
                    version: 4,
                },
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9002),
                    version: 4,
                },
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9003),
                    version: 4,
                    status: StatusEnum::VersionConflict as i32,
                    memo: "conflict".to_owned(),
                },
                DeRecEvent::ReplicaSyncRejected {
                    replica_id: 1002,
                    secret_id: SECRET_ID,
                    version: 4,
                    status: StatusEnum::VersionConflict as i32,
                    memo: "conflict".to_owned(),
                },
                DeRecEvent::ReplicaSecretAcked {
                    channel_id: ChannelId(5001),
                    from_replica_id: 1003,
                    secret_id: SECRET_ID,
                    version: 4,
                    status: 0,
                    memo: String::new(),
                },
            ];
            protocol.update_sharing_round(&mut events).await;

            let (confirmed, failed, threshold_met) = events
                .iter()
                .find_map(|e| match e {
                    DeRecEvent::SharingComplete {
                        confirmed_count,
                        failed_count,
                        threshold_met,
                        ..
                    } => Some((*confirmed_count, *failed_count, *threshold_met)),
                    _ => None,
                })
                .expect("helper leg must complete");
            assert_eq!((confirmed, failed), (2, 1));
            assert!(!threshold_met, "2 of 3 helpers is under a threshold of 3");

            let sync = events
                .iter()
                .find_map(|e| match e {
                    DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
                        Some((synced.clone(), behind.clone()))
                    }
                    _ => None,
                })
                .expect("replica leg must report its own completion");
            assert_eq!(sync, (vec![1003], vec![1002]));
        });
    }

    /// A publish with no replica group stays silent on the replica leg rather
    /// than reporting an empty one.
    #[test]
    fn a_helpers_only_round_emits_no_replica_summary() {
        run_async(async {
            let mut protocol = build(2);
            seed_round(&mut protocol, 2, &[9001], &[]).await;

            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(9001),
                version: 2,
            }];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { .. })),
                "the helper leg still completes"
            );
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::ReplicaSyncComplete { .. })),
                "a round with no replica leg must not report one"
            );
        });
    }
}

#[cfg(test)]
mod timeout_tests {
    use super::*;
    use crate::protocol::ExpiredChannelCleanup;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, NoopTransport, run_async,
    };
    use crate::protocol::types::{SharingRoundState, Timeouts};
    use derec_proto::DeRecMessage;
    use std::collections::HashSet;
    use std::time::Duration;

    const SECRET_ID: u64 = 0x7180;

    type TestProtocol = DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        NoopTransport,
    >;

    fn build_with(timeouts: Timeouts) -> TestProtocol {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(InMemChannelStore::default())
            .with_share_store(InMemShareStore::default())
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemPersistedStateStore::default())
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(2)
            .with_timeouts(timeouts)
            .build()
            .expect("test protocol builds")
    }

    /// An envelope whose timestamp is `age_secs` in the past.
    fn envelope_aged(age_secs: u64) -> DeRecMessage {
        DeRecMessage {
            timestamp: Some(prost_types::Timestamp {
                seconds: now_secs().saturating_sub(age_secs) as i64,
                nanos: 0,
            }),
            ..Default::default()
        }
    }

    /// The defaults are load-bearing — every binding omits fields and relies
    /// on these, so a change here changes behaviour for all seven surfaces.
    #[test]
    fn defaults_are_the_documented_values() {
        let d = Timeouts::default();
        assert_eq!(d.inbound_message, Duration::from_secs(300));
        assert_eq!(d.sharing_round, Duration::from_secs(60));
        assert_eq!(d.unpair_ack, Duration::from_secs(60));
        assert_eq!(d.pairing, Duration::from_secs(30));
        assert_eq!(
            d.expired_channels,
            ExpiredChannelCleanup::Enabled {
                timeout_in_secs: 300
            }
        );
    }

    /// The staleness boundary had no test at all before the split, despite
    /// being the replay-defence window.
    #[test]
    fn inbound_message_bounds_how_stale_an_envelope_may_be() {
        let protocol = build_with(Timeouts {
            inbound_message: Duration::from_secs(120),
            ..Default::default()
        });

        assert!(
            !protocol.is_message_expired(&envelope_aged(60), ChannelId(1)),
            "an envelope inside the window is accepted"
        );
        assert!(
            !protocol.is_message_expired(&envelope_aged(120), ChannelId(1)),
            "the boundary itself is inclusive"
        );
        assert!(
            protocol.is_message_expired(&envelope_aged(121), ChannelId(1)),
            "an envelope past the window is discarded"
        );
    }

    /// A timestampless envelope is not judged stale — the timestamp
    /// invariant is enforced elsewhere, and treating "absent" as "expired"
    /// here would mask it.
    #[test]
    fn an_envelope_without_a_timestamp_is_not_expired() {
        let protocol = build_with(Timeouts::default());
        let envelope = DeRecMessage {
            timestamp: None,
            ..Default::default()
        };
        assert!(!protocol.is_message_expired(&envelope, ChannelId(1)));
    }

    /// **The point of the split.** Shortening the liveness budgets must not
    /// narrow the security boundary. Under the old single knob, asking for a
    /// 1-second sharing round also meant refusing every message more than a
    /// second old.
    #[test]
    fn shortening_the_liveness_budgets_leaves_the_replay_window_alone() {
        let protocol = build_with(Timeouts {
            sharing_round: Duration::from_secs(1),
            unpair_ack: Duration::from_secs(1),
            ..Default::default()
        });

        assert_eq!(protocol.timeouts.inbound_message, Duration::from_secs(300));
        assert!(
            !protocol.is_message_expired(&envelope_aged(290), ChannelId(1)),
            "a message well inside the default replay window is still accepted \
             even though both liveness budgets are one second"
        );
    }

    /// And the converse: a long replay window does not keep a stalled round
    /// open. Both directions matter — one knob meant either mistake was
    /// reachable by tuning the other concern.
    #[test]
    fn a_long_replay_window_does_not_extend_the_sharing_round() {
        run_async(async {
            let mut protocol = build_with(Timeouts {
                inbound_message: Duration::from_secs(3600),
                sharing_round: Duration::from_secs(1),
                ..Default::default()
            });

            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 1,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs().saturating_sub(30),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let events = protocol.tick().await;
            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::SharingComplete { version: 1, .. })),
                "the round times out on its own budget, not the replay window; got {events:?}"
            );
        });
    }
}

#[cfg(test)]
mod proof_cleanup_tests {
    use super::*;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, NoopTransport, run_async,
    };
    use crate::protocol::traits::ShareStoreFuture;
    use crate::protocol::types::{Share, SharingRoundState};
    use std::collections::HashSet;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    const SECRET_ID: u64 = 0xBEEF;

    /// Wraps [`InMemShareStore`] and counts `remove_versions` calls per
    /// `(channel_id, version)`, to catch a cleanup path invoked more than
    /// once for the same channel failure.
    #[derive(Default, Clone)]
    struct CountingShareStore {
        inner: InMemShareStore,
        remove_versions_calls: Arc<Mutex<Vec<(ChannelId, u32)>>>,
    }

    impl CountingShareStore {
        fn remove_versions_call_count(&self, channel_id: ChannelId, version: u32) -> usize {
            self.remove_versions_calls
                .lock()
                .unwrap()
                .iter()
                .filter(|(c, v)| *c == channel_id && *v == version)
                .count()
        }
    }

    impl DeRecShareStore for CountingShareStore {
        fn load(
            &self,
            secret_id: u64,
            channel_id: ChannelId,
            versions: &[u32],
        ) -> ShareStoreFuture<'_, Vec<Share>> {
            self.inner.load(secret_id, channel_id, versions)
        }
        fn load_many(
            &self,
            secret_id: u64,
            channel_ids: &[ChannelId],
            versions: &[u32],
        ) -> ShareStoreFuture<'_, Vec<Share>> {
            self.inner.load_many(secret_id, channel_ids, versions)
        }
        fn load_all(
            &self,
            secret_id: u64,
            channel_ids: &[ChannelId],
        ) -> ShareStoreFuture<'_, Vec<Share>> {
            self.inner.load_all(secret_id, channel_ids)
        }
        fn latest_version(&self, secret_id: u64) -> ShareStoreFuture<'_, Option<u32>> {
            self.inner.latest_version(secret_id)
        }
        fn save(
            &mut self,
            secret_id: u64,
            channel_id: ChannelId,
            share: Share,
        ) -> ShareStoreFuture<'_, ()> {
            self.inner.save(secret_id, channel_id, share)
        }
        fn remove_channel(
            &mut self,
            secret_id: u64,
            channel_id: ChannelId,
        ) -> ShareStoreFuture<'_, ()> {
            self.inner.remove_channel(secret_id, channel_id)
        }
        fn remove_versions(
            &mut self,
            secret_id: u64,
            channel_id: ChannelId,
            versions: &[u32],
        ) -> ShareStoreFuture<'_, ()> {
            {
                let mut calls = self.remove_versions_calls.lock().unwrap();
                for v in versions {
                    calls.push((channel_id, *v));
                }
            }
            self.inner.remove_versions(secret_id, channel_id, versions)
        }
        fn keep_version(&self, secret_id: u64, version: u32) -> ShareStoreFuture<'_, u32> {
            self.inner.keep_version(secret_id, version)
        }
    }

    type CountingTestProtocol = DeRecProtocol<
        InMemChannelStore,
        CountingShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        NoopTransport,
    >;

    fn build_counting(threshold: usize, shares: CountingShareStore) -> CountingTestProtocol {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(InMemChannelStore::default())
            .with_share_store(shares)
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemPersistedStateStore::default())
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(threshold)
            .build()
            .expect("test protocol builds")
    }

    type TestProtocol = DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        NoopTransport,
    >;

    fn build(threshold: usize, shares: InMemShareStore) -> TestProtocol {
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(InMemChannelStore::default())
            .with_share_store(shares)
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemPersistedStateStore::default())
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(threshold)
            .build()
            .expect("test protocol builds")
    }

    async fn seed_round(protocol: &mut TestProtocol, version: u32, helpers: &[u64]) {
        protocol
            .state_store
            .save(
                SECRET_ID,
                StateItem::SharingRound(Box::new(SharingRoundState {
                    version,
                    pending: helpers.iter().copied().map(ChannelId).collect(),
                    confirmed: HashSet::new(),
                    failed: HashSet::new(),
                    pending_replicas: HashSet::new(),
                    synced_replicas: HashSet::new(),
                    behind_replicas: HashSet::new(),
                    started_at: now_secs(),
                    keep_version: None,
                    threshold: None,
                })),
            )
            .await
            .expect("seed round");
    }

    /// Seed the owner's proof for `channel_id` at `version`.
    fn seed_proof(shares: &InMemShareStore, channel_id: u64, version: u32) {
        shares.data.lock().unwrap().insert(
            (SECRET_ID, channel_id, version),
            Share {
                secret_id: SECRET_ID,
                version,
                bytes: vec![0xAB],
                subshares: None,
                threshold: None,
            },
        );
    }

    fn has_proof(shares: &InMemShareStore, channel_id: u64, version: u32) -> bool {
        shares
            .data
            .lock()
            .unwrap()
            .contains_key(&(SECRET_ID, channel_id, version))
    }

    /// An inbound rejection removes the failed channel's proof; the
    /// confirmed channel's proof is untouched.
    #[test]
    fn rejected_channel_proof_is_removed_and_confirmed_kept() {
        run_async(async {
            let shares = InMemShareStore::default();
            seed_proof(&shares, 9001, 4);
            seed_proof(&shares, 9002, 4);
            let mut protocol = build(2, shares.clone());
            seed_round(&mut protocol, 4, &[9001, 9002]).await;

            let mut events = vec![
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9001),
                    version: 4,
                },
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9002),
                    version: 4,
                    status: StatusEnum::Fail as i32,
                    memo: "rejected".to_owned(),
                },
            ];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                has_proof(&shares, 9001, 4),
                "the confirmed channel's proof survives"
            );
            assert!(
                !has_proof(&shares, 9002, 4),
                "the rejected channel's proof is removed"
            );
        });
    }

    /// A channel that times out loses its proof exactly like an explicit
    /// rejection does.
    #[test]
    fn timed_out_channel_proof_is_removed() {
        run_async(async {
            let shares = InMemShareStore::default();
            seed_proof(&shares, 9001, 4);
            let mut protocol = build(2, shares.clone());
            protocol.timeouts.sharing_round = Duration::from_secs(60);
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 4,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs().saturating_sub(600),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let _events = protocol.tick().await;

            assert!(
                !has_proof(&shares, 9001, 4),
                "the timed-out channel's proof is removed"
            );
        });
    }

    /// Any rejection status removes the proof, not only `Fail` — a store
    /// rate limit (`TooFrequent`) is just as final for the owner's proof
    /// as an explicit failure, and only the round's version is touched.
    #[test]
    fn store_refusal_rejection_removes_the_proof() {
        run_async(async {
            let shares = InMemShareStore::default();
            seed_proof(&shares, 9002, 4);
            seed_proof(&shares, 9002, 3);
            let mut protocol = build(2, shares.clone());
            seed_round(&mut protocol, 4, &[9001, 9002]).await;

            let mut events = vec![DeRecEvent::ShareRejected {
                channel_id: ChannelId(9002),
                version: 4,
                status: StatusEnum::TooFrequent as i32,
                memo: "too frequent".to_owned(),
            }];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                !has_proof(&shares, 9002, 4),
                "a TooFrequent rejection removes the proof just like Fail does"
            );
            assert!(
                has_proof(&shares, 9002, 3),
                "an older version's proof is untouched by this round settling"
            );
        });
    }

    /// A late `ShareConfirmed` for a channel whose round already settled as
    /// failed must not bring its proof back.
    #[test]
    fn late_confirmation_after_failure_does_not_restore_a_proof() {
        run_async(async {
            let shares = InMemShareStore::default();
            seed_proof(&shares, 9001, 4);
            seed_proof(&shares, 9002, 4);
            let mut protocol = build(2, shares.clone());
            seed_round(&mut protocol, 4, &[9001, 9002]).await;

            let mut events = vec![
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9001),
                    version: 4,
                },
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9002),
                    version: 4,
                    status: StatusEnum::Fail as i32,
                    memo: "rejected".to_owned(),
                },
            ];
            protocol.update_sharing_round(&mut events).await;
            assert!(
                protocol
                    .state_store
                    .load(SECRET_ID, StateKey::SharingRound { version: 4 })
                    .await
                    .expect("load")
                    .is_none(),
                "the round closed: both channels are settled"
            );
            assert!(!has_proof(&shares, 9002, 4));

            // The round row is gone, so this reply is late: nothing matches
            // it, and it must not resurrect the proof that was just removed.
            let mut late = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(9002),
                version: 4,
            }];
            protocol.update_sharing_round(&mut late).await;

            assert!(
                !has_proof(&shares, 9002, 4),
                "a late confirmation after the failure must not re-create the proof"
            );
        });
    }

    /// A channel rejected and then confirmed in the same batch, while the
    /// round is still open (other channels still pending), must count only
    /// as failed — not in both `failed` and `confirmed`, which would let
    /// `threshold_met` include a channel whose proof was just removed.
    #[test]
    fn rejected_then_confirmed_within_open_round_counts_only_as_failed() {
        run_async(async {
            let shares = InMemShareStore::default();
            seed_proof(&shares, 9002, 4);
            let mut protocol = build(2, shares.clone());
            seed_round(&mut protocol, 4, &[9001, 9002, 9003]).await;

            let mut events = vec![
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9002),
                    version: 4,
                    status: StatusEnum::Fail as i32,
                    memo: "rejected".to_owned(),
                },
                DeRecEvent::ShareConfirmed {
                    channel_id: ChannelId(9002),
                    version: 4,
                },
            ];
            protocol.update_sharing_round(&mut events).await;

            assert!(
                !has_proof(&shares, 9002, 4),
                "the rejection still removes the proof"
            );

            let round = protocol
                .state_store
                .load(SECRET_ID, StateKey::SharingRound { version: 4 })
                .await
                .expect("load")
                .expect("round still open: 9001 and 9003 have not answered");
            let StateItem::SharingRound(round) = round else {
                panic!("expected a SharingRound state item");
            };
            assert!(
                round.failed.contains(&ChannelId(9002)),
                "the channel is recorded as failed"
            );
            assert!(
                !round.confirmed.contains(&ChannelId(9002)),
                "the later confirmation must not also count it as confirmed"
            );
        });
    }

    /// A `tick()` first fails a timed-out channel in the timeout sweep, then
    /// hands the very `ShareRejected` it just produced to round settlement.
    /// The channel must be dropped from the store exactly once, not once by
    /// each stage.
    #[test]
    fn timed_out_channel_proof_is_removed_once() {
        run_async(async {
            let shares = CountingShareStore::default();
            let mut protocol = build_counting(2, shares.clone());
            protocol.timeouts.sharing_round = Duration::from_secs(60);
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 4,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs().saturating_sub(600),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let _events = protocol.tick().await;

            assert_eq!(
                shares.remove_versions_call_count(ChannelId(9001), 4),
                1,
                "the timeout sweep and round settlement must not both drop the same proof"
            );
        });
    }

    /// Two `ShareRejected` events for the same channel and version in one
    /// batch — a genuine duplicate, not a timeout echo — must still only
    /// remove the proof once: the second one finds the channel already out
    /// of `pending`.
    #[test]
    fn duplicate_share_rejected_does_not_double_remove_the_proof() {
        run_async(async {
            let shares = CountingShareStore::default();
            let mut protocol = build_counting(2, shares.clone());
            protocol
                .state_store
                .save(
                    SECRET_ID,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version: 4,
                        pending: [ChannelId(9001)].into_iter().collect(),
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas: HashSet::new(),
                        synced_replicas: HashSet::new(),
                        behind_replicas: HashSet::new(),
                        started_at: now_secs(),
                        keep_version: None,
                        threshold: None,
                    })),
                )
                .await
                .expect("seed round");

            let mut events = vec![
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9001),
                    version: 4,
                    status: StatusEnum::Fail as i32,
                    memo: "rejected".to_owned(),
                },
                DeRecEvent::ShareRejected {
                    channel_id: ChannelId(9001),
                    version: 4,
                    status: StatusEnum::Fail as i32,
                    memo: "duplicate".to_owned(),
                },
            ];
            protocol.update_sharing_round(&mut events).await;

            assert_eq!(
                shares.remove_versions_call_count(ChannelId(9001), 4),
                1,
                "a duplicated inbound rejection must not remove the proof twice"
            );
        });
    }
}

/// `SharingComplete.threshold_met` counts the subshares the confirmed
/// helpers hold, not the helpers themselves.
#[cfg(test)]
mod weighted_tally_tests {
    use super::*;
    use crate::primitives::sharing::request;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, NoopTransport, run_async,
    };
    use crate::protocol::types::{Share, SharingRoundState};
    use prost::Message as _;
    use std::collections::HashSet;

    const SECRET_ID: u64 = 0x5EED;
    const VERSION: u32 = 3;
    const THRESHOLD: usize = 3;
    const A: u64 = 31;
    const B: u64 = 32;
    const C: u64 = 33;
    const D: u64 = 34;

    type TestProtocol = DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        NoopTransport,
    >;

    /// A protocol whose share store holds the owner's tracking share for each
    /// of `A`..`D` at [`VERSION`], split with `A` at weight 2, and an open
    /// round awaiting all four.
    async fn rig() -> (TestProtocol, InMemShareStore) {
        rig_with(THRESHOLD, None).await
    }

    /// [`rig`] with the builder's threshold and the round's recorded one set
    /// separately. The shares are always split at [`THRESHOLD`].
    async fn rig_with(
        builder_threshold: usize,
        round_threshold: Option<u32>,
    ) -> (TestProtocol, InMemShareStore) {
        let channels = [
            (ChannelId(A), 2),
            (ChannelId(B), 1),
            (ChannelId(C), 1),
            (ChannelId(D), 1),
        ];
        let split = request::split(
            &channels,
            SECRET_ID,
            VERSION,
            b"weighted tally secret",
            THRESHOLD,
        )
        .expect("weighted split");
        let shares = InMemShareStore::default();
        for (channel_id, committed) in &split.shares {
            shares.data.lock().unwrap().insert(
                (SECRET_ID, channel_id.0, VERSION),
                Share {
                    secret_id: SECRET_ID,
                    version: VERSION,
                    bytes: committed.encode_to_vec(),
                    subshares: None,
                    threshold: None,
                },
            );
        }

        let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(InMemChannelStore::default())
            .with_share_store(shares.clone())
            .with_secret_store(InMemSecretStore::default())
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_transport(NoopTransport)
            .with_state_store(InMemPersistedStateStore::default())
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(builder_threshold)
            .build()
            .expect("test protocol builds");
        protocol
            .state_store
            .save(
                SECRET_ID,
                StateItem::SharingRound(Box::new(SharingRoundState {
                    version: VERSION,
                    pending: channels.iter().map(|&(c, _)| c).collect(),
                    confirmed: HashSet::new(),
                    failed: HashSet::new(),
                    pending_replicas: HashSet::new(),
                    synced_replicas: HashSet::new(),
                    behind_replicas: HashSet::new(),
                    started_at: now_secs(),
                    keep_version: None,
                    threshold: round_threshold,
                })),
            )
            .await
            .expect("seed round");
        (protocol, shares)
    }

    fn answers(confirmed: &[u64], rejected: &[u64]) -> Vec<DeRecEvent> {
        let mut events: Vec<DeRecEvent> = confirmed
            .iter()
            .map(|&c| DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(c),
                version: VERSION,
            })
            .collect();
        events.extend(rejected.iter().map(|&c| DeRecEvent::ShareRejected {
            channel_id: ChannelId(c),
            version: VERSION,
            status: StatusEnum::Fail as i32,
            memo: "rejected".to_owned(),
        }));
        events
    }

    fn threshold_met(events: &[DeRecEvent]) -> bool {
        events
            .iter()
            .find_map(|e| match e {
                DeRecEvent::SharingComplete {
                    version: VERSION,
                    threshold_met,
                    ..
                } => Some(*threshold_met),
                _ => None,
            })
            .expect("the round completes once every helper has answered")
    }

    #[test]
    fn threshold_met_counts_confirmed_weight() {
        run_async(async {
            // A (2 subshares) plus B (1 subshare) reach t = 3 with two helpers.
            let (mut protocol, _) = rig().await;
            let mut events = answers(&[A, B], &[C, D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(
                threshold_met(&events),
                "A + B hold 3 subshares; got {events:?}"
            );

            // Three weight-1 helpers reach t = 3 without A.
            let (mut protocol, _) = rig().await;
            let mut events = answers(&[B, C, D], &[A]);
            protocol.update_sharing_round(&mut events).await;
            assert!(
                threshold_met(&events),
                "B + C + D hold 3 subshares; got {events:?}"
            );

            // Two weight-1 helpers hold 2 subshares, below t = 3.
            let (mut protocol, _) = rig().await;
            let mut events = answers(&[B, C], &[A, D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(
                !threshold_met(&events),
                "B + C hold 2 subshares; got {events:?}"
            );
        });
    }

    /// The round is judged against the threshold it split at, whatever the
    /// builder says now.
    #[test]
    fn threshold_met_follows_the_rounds_own_threshold() {
        run_async(async {
            // B + C hold 2 subshares: enough for a builder at 2, not for the
            // round's 3.
            let (mut protocol, _) = rig_with(2, Some(3)).await;
            let mut events = answers(&[B, C], &[A, D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(!threshold_met(&events), "got {events:?}");

            // A + B hold 3 subshares: short of a builder at 4, enough for the
            // round's 3.
            let (mut protocol, _) = rig_with(4, Some(3)).await;
            let mut events = answers(&[A, B], &[C, D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(threshold_met(&events), "got {events:?}");

            // A round with no recorded threshold falls back to the builder's.
            let (mut protocol, _) = rig_with(2, None).await;
            let mut events = answers(&[B, C], &[A, D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(threshold_met(&events), "got {events:?}");
        });
    }

    #[test]
    fn threshold_met_counts_a_missing_tracking_share_as_one() {
        run_async(async {
            let (mut protocol, shares) = rig().await;
            shares.data.lock().unwrap().remove(&(SECRET_ID, A, VERSION));

            let mut events = answers(&[A, B, C], &[D]);
            protocol.update_sharing_round(&mut events).await;
            assert!(
                threshold_met(&events),
                "A's weight is unknown without its tracking share and counts as 1, so A + B + C hold 3 subshares; got {events:?}"
            );
        });
    }
}

/// A Helper prunes every version other than the `keepVersion` when it accepts the
/// version that carries it, so the owner's proofs for those versions follow
/// the Helper's confirmation and never its refusal.
#[cfg(test)]
mod keep_version_proof_tests {
    use super::*;
    use crate::derec_message::{DeRecMessageBuilder, current_timestamp};
    use crate::primitives::sharing::request::extract;
    use crate::protocol::DeRecFlow;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::events::VerifyFailureReason;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, RecordingTransport, run_async,
    };
    use crate::protocol::types::{
        ChannelRecord, ChannelStatus, HelperChannel, SecretValue, Share, SharingRoundState, Target,
        UserSecret,
    };
    use derec_proto::{
        DeRecResult, MessageBody, Protocol, SenderKind, StatusEnum, StoreShareRequestMessage,
        StoreShareResponseMessage, TransportProtocol,
    };
    use prost::Message as _;
    use std::collections::HashMap;

    const SECRET_ID: u64 = 0x4EE9;
    const A: u64 = 31;
    const B: u64 = 32;

    type TestProtocol = DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemPersistedStateStore,
        RecordingTransport,
    >;

    fn uri(channel: u64) -> String {
        format!("https://helper-{channel}.example")
    }

    fn key_of(channel: u64) -> [u8; 32] {
        [channel as u8; 32]
    }

    async fn owner(shares: InMemShareStore, transport: RecordingTransport) -> TestProtocol {
        let mut channels = InMemChannelStore::default();
        let mut secrets = InMemSecretStore::default();
        for channel in [A, B] {
            channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Helper(HelperChannel {
                        channel_id: ChannelId(channel),
                        transports: vec![TransportProtocol {
                            uri: uri(channel),
                            protocol: Protocol::Https as i32,
                        }],
                        communication_info: HashMap::new(),
                        peer_role: SenderKind::Helper,
                        status: ChannelStatus::Paired,
                        created_at: now_secs(),
                        weight: 1,
                    }),
                )
                .await
                .expect("seed helper");
            secrets
                .save(
                    SECRET_ID,
                    ChannelId(channel),
                    SecretValue::SharedKey(key_of(channel)),
                )
                .await
                .expect("seed key");
        }
        DeRecProtocolBuilder::new(SECRET_ID)
            .with_channel_store(channels)
            .with_share_store(shares)
            .with_secret_store(secrets)
            .with_user_secret_store(InMemUserSecretStore::default())
            .with_state_store(InMemPersistedStateStore::default())
            .with_transport(transport)
            .with_own_transports(["https://owner.example"])
            .with_threshold(2)
            .build()
            .expect("test protocol builds")
    }

    /// The channel each envelope sent so far went to, with the request it
    /// carried.
    fn sent_requests(transport: &RecordingTransport) -> Vec<(u64, StoreShareRequestMessage)> {
        transport
            .sent
            .lock()
            .unwrap()
            .iter()
            .map(|(endpoints, envelope)| {
                let channel = [A, B]
                    .into_iter()
                    .find(|c| endpoints[0].uri == uri(*c))
                    .expect("every send goes to a seeded helper");
                let request = extract(envelope, &key_of(channel))
                    .expect("a store-share request")
                    .request;
                (channel, request)
            })
            .collect()
    }

    fn answer(channel: u64, version: u32, status: StatusEnum) -> Vec<u8> {
        let timestamp = current_timestamp();
        DeRecMessageBuilder::channel()
            .channel_id(ChannelId(channel))
            .timestamp(timestamp)
            .message_body(MessageBody::StoreShareResponse(StoreShareResponseMessage {
                result: Some(DeRecResult {
                    status: status as i32,
                    memo: String::new(),
                }),
                version,
                timestamp: Some(timestamp),
                secret_id: SECRET_ID,
                replica_id: None,
            }))
            .encrypt(&key_of(channel))
            .expect("encrypt")
            .build()
            .expect("build")
            .encode_to_vec()
    }

    /// Publish once and have each Helper answer with the status `status_of`
    /// gives its channel. Returns the version published.
    async fn round(
        protocol: &mut TestProtocol,
        transport: &RecordingTransport,
        status_of: impl Fn(u64) -> StatusEnum,
    ) -> u32 {
        transport.sent.lock().unwrap().clear();
        protocol
            .start(DeRecFlow::ProtectSecret {
                secrets: vec![UserSecret {
                    id: b"id".to_vec(),
                    name: "name".to_owned(),
                    data: b"data".to_vec(),
                }],
                description: None,
                weights: HashMap::new(),
                threshold: None,
            })
            .await
            .expect("publish");
        let requests = sent_requests(transport);
        assert_eq!(requests.len(), 2, "one request per helper");
        let version = requests[0].1.version;
        for (channel, request) in requests {
            protocol
                .process(&answer(channel, request.version, status_of(channel)))
                .await
                .expect("the owner reads the answer");
        }
        version
    }

    fn versions_held(shares: &InMemShareStore, channel: u64) -> Vec<u32> {
        let mut versions: Vec<u32> = shares
            .data
            .lock()
            .unwrap()
            .keys()
            .filter(|(s, c, _)| *s == SECRET_ID && *c == channel)
            .map(|(_, _, v)| *v)
            .collect();
        versions.sort_unstable();
        versions
    }

    fn ok(_: u64) -> StatusEnum {
        StatusEnum::Ok
    }

    /// An application keeping no older version: once both Helpers confirm
    /// v3 they hold only v3, and so does the owner. Verifying v1 is then a
    /// local condition, not a question for the Helpers.
    #[test]
    fn confirmed_versions_other_than_the_keep_version_lose_their_proofs() {
        run_async(async {
            let shares = InMemShareStore::default();
            *shares.keep.lock().unwrap() = Some(0);
            let transport = RecordingTransport::default();
            let mut protocol = owner(shares.clone(), transport.clone()).await;

            for expected in 1..=3 {
                assert_eq!(round(&mut protocol, &transport, ok).await, expected);
            }

            assert_eq!(versions_held(&shares, A), vec![3]);
            assert_eq!(versions_held(&shares, B), vec![3]);

            transport.sent.lock().unwrap().clear();
            let events = protocol
                .start(DeRecFlow::VerifyShares {
                    secret_id: SECRET_ID,
                    version: 1,
                    target: Target::All,
                })
                .await
                .expect("verify starts");

            assert_eq!(events.len(), 2, "one verdict per helper; got {events:?}");
            assert!(
                events.iter().all(|e| matches!(
                    e,
                    DeRecEvent::VerifySharesFailed {
                        version: 1,
                        reason: VerifyFailureReason::NoProof,
                        ..
                    }
                )),
                "got {events:?}"
            );
            assert!(
                transport.sent_envelopes().is_empty(),
                "no challenge is sent for a version no helper holds"
            );
        });
    }

    /// A Helper that refuses v3 prunes nothing, so the owner keeps the
    /// proofs of the versions it still holds; the Helper that confirmed
    /// loses them.
    #[test]
    fn a_rejecting_helper_keeps_its_older_proofs() {
        run_async(async {
            let shares = InMemShareStore::default();
            let transport = RecordingTransport::default();
            let mut protocol = owner(shares.clone(), transport.clone()).await;

            round(&mut protocol, &transport, ok).await;
            round(&mut protocol, &transport, ok).await;
            assert_eq!(versions_held(&shares, B), vec![1, 2]);

            *shares.keep.lock().unwrap() = Some(0);
            let version = round(&mut protocol, &transport, |channel| {
                if channel == B {
                    StatusEnum::Fail
                } else {
                    StatusEnum::Ok
                }
            })
            .await;
            assert_eq!(version, 3);

            assert_eq!(versions_held(&shares, A), vec![3]);
            assert_eq!(
                versions_held(&shares, B),
                vec![1, 2],
                "B refused v3: it still holds v1 and v2, and v3's proof is dropped"
            );
        });
    }

    /// The `keepVersion` is still held by the Helper, so its proof stays.
    #[test]
    fn the_keep_version_keeps_its_proof() {
        run_async(async {
            let shares = InMemShareStore::default();
            let transport = RecordingTransport::default();
            let mut protocol = owner(shares.clone(), transport.clone()).await;

            round(&mut protocol, &transport, ok).await;
            *shares.keep.lock().unwrap() = Some(1);
            for _ in 2..=3 {
                round(&mut protocol, &transport, ok).await;
            }

            assert_eq!(versions_held(&shares, A), vec![1, 3]);
            assert_eq!(versions_held(&shares, B), vec![1, 3]);
        });
    }

    fn seed_proof(shares: &InMemShareStore, channel: u64, version: u32) {
        shares.data.lock().unwrap().insert(
            (SECRET_ID, channel, version),
            Share {
                secret_id: SECRET_ID,
                version,
                bytes: vec![0xAB],
                subshares: None,
                threshold: None,
            },
        );
    }

    async fn seed_open_round(protocol: &mut TestProtocol, version: u32, keep_version: Option<u32>) {
        protocol
            .state_store
            .save(
                SECRET_ID,
                StateItem::SharingRound(Box::new(SharingRoundState {
                    version,
                    pending: [ChannelId(A), ChannelId(B)].into_iter().collect(),
                    confirmed: Default::default(),
                    failed: Default::default(),
                    pending_replicas: Default::default(),
                    synced_replicas: Default::default(),
                    behind_replicas: Default::default(),
                    started_at: now_secs(),
                    keep_version,
                    threshold: None,
                })),
            )
            .await
            .expect("seed round");
    }

    /// A Helper ignores the `keepVersion` of a request older than a version it
    /// already holds. While the owner holds a newer proof for the channel,
    /// confirming the older round removes nothing.
    #[test]
    fn a_confirmation_older_than_a_held_proof_removes_nothing() {
        run_async(async {
            let shares = InMemShareStore::default();
            for version in [3, 4, 5] {
                seed_proof(&shares, A, version);
            }
            let mut protocol = owner(shares.clone(), RecordingTransport::default()).await;
            seed_open_round(&mut protocol, 4, Some(0)).await;

            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(A),
                version: 4,
            }];
            protocol.update_sharing_round(&mut events).await;

            assert_eq!(versions_held(&shares, A), vec![3, 4, 5]);
        });
    }

    /// A version whose round still waits on the Helper may reach it after
    /// the newer one and be stored without pruning, so its proof stays.
    #[test]
    fn a_version_still_awaiting_the_helper_keeps_its_proof() {
        run_async(async {
            let shares = InMemShareStore::default();
            for version in [3, 4, 5] {
                seed_proof(&shares, A, version);
            }
            let mut protocol = owner(shares.clone(), RecordingTransport::default()).await;
            seed_open_round(&mut protocol, 4, Some(0)).await;
            seed_open_round(&mut protocol, 5, Some(0)).await;

            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(A),
                version: 5,
            }];
            protocol.update_sharing_round(&mut events).await;

            assert_eq!(
                versions_held(&shares, A),
                vec![4, 5],
                "v3 is pruned; v4 still awaits this helper"
            );
        });
    }

    /// Keeping the version before each time leaves the owner the proofs of
    /// the last two versions, as the Helpers hold.
    #[test]
    fn keeping_the_previous_version_keeps_the_last_two_proofs() {
        run_async(async {
            let shares = InMemShareStore::default();
            let transport = RecordingTransport::default();
            let mut protocol = owner(shares.clone(), transport.clone()).await;

            for _ in 1..=3 {
                round(&mut protocol, &transport, ok).await;
            }

            assert_eq!(versions_held(&shares, A), vec![2, 3]);
            assert_eq!(versions_held(&shares, B), vec![2, 3]);
        });
    }

    /// A round with no recorded `keep_version`, such as one persisted before
    /// the field existed, removes no proof when its Helpers confirm.
    #[test]
    fn a_round_without_a_keep_version_removes_no_proof() {
        run_async(async {
            let shares = InMemShareStore::default();
            for version in [1, 2, 3] {
                seed_proof(&shares, A, version);
            }
            let mut protocol = owner(shares.clone(), RecordingTransport::default()).await;
            seed_open_round(&mut protocol, 3, None).await;

            let mut events = vec![DeRecEvent::ShareConfirmed {
                channel_id: ChannelId(A),
                version: 3,
            }];
            protocol.update_sharing_round(&mut events).await;

            assert_eq!(versions_held(&shares, A), vec![1, 2, 3]);
        });
    }
}