offline-protocol-leaf 0.30.0

A constrained leaf node that speaks the Offline Protocol as a never-committing MLS member
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
//! A real phone talking to a real device.
//!
//! The phone here is `offline-protocol-mls`, built on OpenMLS, driven through
//! its ordinary public API. The device is this crate, built on mls-rs. So
//! every test below is a genuine two-implementation exchange rather than this
//! crate agreeing with itself, which is the only kind of test that can catch
//! the class of bug that matters here: a default in one library that the other
//! refuses.
//!
//! `tools/mls-interop` covers the same pair out of process and pins the
//! library versions. This file covers the choreography that sits above them:
//! the gates, the reset sequence, and the persist-before-emit rule.
//!
//! Absent on WebAssembly: the phone side does not build there, and the
//! crate's manifest leaves it out of the WASI configuration for that reason.
#![cfg(not(target_arch = "wasm32"))]

use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex, OnceLock,
};
use std::time::{SystemTime, UNIX_EPOCH};

use std::collections::BTreeMap;

use offline_protocol_core::{Message, MessagePriority, UserId};
use offline_protocol_leaf::{
    store::{
        KEY_TYPE_GROUP_EPOCH, KEY_TYPE_GROUP_STATE, KEY_TYPE_IDENTITY, KEY_TYPE_KEY_PACKAGE,
        KEY_TYPE_PEER,
    },
    Handled, LeafDevice, LeafError, LeafEvent, LeafStore, MemoryStore, StoreError,
};
use offline_protocol_mls::{storage::InMemoryStorage, MlsManager, MlsStorage};
use offline_protocol_sealed::{
    control_signing_payload_v2, derive_address, prefixes, EncryptedMessage, GroupId,
    KeyPackagePayload, WelcomeMessage, ACK_FOR_KEY, CTRL_FRESHNESS_FUTURE_MS,
    LEAF_CTRL_FRESHNESS_PAST_MS, MLS_ENVELOPE_COMPACT_V1,
};

use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};

const APP_ID: &str = "com.example.lock";

/// The instant every test in this file runs at: the wall clock, read once per
/// process.
///
/// It cannot be a fixed date, however much that would read better. The device
/// is told the time explicitly, but the phone is a production `MlsManager`,
/// and its MLS library checks a key package's lifetime against the system
/// clock with no seam to pin it. So a fixed instant expires together with the
/// device's key packages (`LEAF_KEY_PACKAGE_LIFETIME` after it). The first
/// value here, 2026-08-21, turned forty-eight of these tests red on
/// 2026-09-18, on every branch, for changes that had nothing to do with
/// pairing. Read once, it still gives every stamp and every `handle` call in a
/// run the same instant, which is the property [`phone_control_frame`] needs.
fn now() -> u64 {
    static NOW: OnceLock<u64> = OnceLock::new();
    *NOW.get_or_init(|| {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("the clock is past 1970")
            .as_secs()
    })
}

/// A phone, constructed the way production does it: the identity is minted
/// first and the manager is then built at the address it derives to.
///
/// The bootstrap pass exists because a manager's address is a function of a
/// key it mints on first construction, so there is nothing to name it with
/// until it exists. The second construction loads the same identity out of the
/// same storage.
struct Phone {
    manager: MlsManager,
    address: String,
}

fn new_phone() -> Phone {
    let storage: Arc<dyn MlsStorage> = Arc::new(InMemoryStorage::new());
    let bootstrap = MlsManager::new("bootstrap", Arc::clone(&storage)).expect("bootstrap manager");
    let public = bootstrap
        .get_identity_public_key()
        .expect("identity public key");
    let address = derive_address(&public).expect("derive").to_string();
    drop(bootstrap);

    let manager = MlsManager::new(address.clone(), storage).expect("addressed manager");
    Phone { manager, address }
}

fn device(store: Arc<dyn LeafStore>) -> LeafDevice {
    LeafDevice::open(store, APP_ID).expect("device opens")
}

/// Builds a control frame the way the phone's engine does, and signs it with
/// the phone's identity.
///
/// The canonical payload comes from the sealed layer, which is the one
/// construction both ends use, so this is the phone's own signature rather
/// than a second implementation of one.
///
/// The frame is stamped at [`now`], the same instant the device is told the
/// time is, rather than at a fresh reading of the clock. That is not tidiness:
/// the stamp is inside the signature and the device refuses a frame outside its
/// window, so a stamp taken separately from the instant handed to the device
/// could land on the wrong side of it on a slow runner.
fn phone_control_frame(phone: &Phone, to: &str, content: String) -> Message {
    phone_control_frame_at(phone, to, content, now())
}

/// [`phone_control_frame`] stamped at a chosen instant, for the tests whose
/// subject is the stamp.
fn phone_control_frame_at(phone: &Phone, to: &str, content: String, at_unix_secs: u64) -> Message {
    let mut message = Message::new(
        UserId::new(&phone.address).expect("phone address is a user id"),
        UserId::new(to).expect("device address is a user id"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        content,
    );
    message.priority = MessagePriority::High;
    // Before signing, always: the timestamp is one of the signed fields, so a
    // frame stamped afterwards carries a signature over a different frame than
    // the one handed over, and every such test passes or fails for the wrong
    // reason.
    message.timestamp = offline_protocol_core::Timestamp::from_millis((at_unix_secs as i64) * 1000);
    sign_as(phone, &mut message);
    message
}

fn sign_as(phone: &Phone, message: &mut Message) {
    // The freshness-bound payload, which is what the engine picks for a peer
    // whose key package advertises it — and a leaf advertises nothing else.
    let payload = control_signing_payload_v2(message).expect("canonical payload");
    let signature = phone.manager.sign_data(&payload).expect("phone signs");
    let public = phone
        .manager
        .get_identity_public_key()
        .expect("phone public key");
    message.metadata.insert(
        offline_protocol_sealed::CTRL_SIG_META_KEY.to_string(),
        BASE64.encode(&signature),
    );
    message.metadata.insert(
        offline_protocol_sealed::CTRL_PK_META_KEY.to_string(),
        BASE64.encode(&public),
    );
}

/// Reads a device's key package frame the way the phone's dispatch does.
fn import_device_key_package(phone: &Phone, frame: &Message) {
    let body = frame
        .content
        .strip_prefix(prefixes::KEY_PACKAGE)
        .expect("frame carries a key package");
    let payload: KeyPackagePayload = serde_json::from_str(body).expect("key package body parses");
    phone
        .manager
        .import_key_package(&payload.user_id, &payload.key_package_data)
        .expect("the phone accepts the device's key package");
}

/// The bare key package out of a device's advertisement frame.
fn raw_key_package(frame: &Message) -> Vec<u8> {
    let body = frame
        .content
        .strip_prefix(prefixes::KEY_PACKAGE)
        .expect("frame carries a key package");
    let payload: KeyPackagePayload = serde_json::from_str(body).expect("key package body parses");
    payload.key_package_data
}

/// Pairs a phone and a device, returning the device's address.
///
/// This is the whole choreography in one place: the device advertises, the
/// phone establishes and sends a Welcome, the device joins and confirms.
fn pair(phone: &Phone, device: &mut LeafDevice) -> String {
    let device_address = device.address().to_string();

    let advertisement = device
        .key_package_frame(&phone.address, now())
        .expect("device mints a key package");
    import_device_key_package(phone, &advertisement);

    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone creates the session");
    let welcome_frame = phone_control_frame(
        phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome serializes")
        ),
    );

    let handled = device.handle(&welcome_frame, now()).expect("device joins");
    assert!(
        handled.events.contains(&LeafEvent::SessionEstablished {
            peer: phone.address.clone(),
        }),
        "joining a welcome did not establish a session: {:?}",
        handled.events
    );

    // The confirmation is a group-aware decrypt, so the phone must be able to
    // open it. That is the whole reason it is sealed rather than sent as a
    // plaintext acknowledgement.
    let said = spoken(&handled);
    assert_eq!(said.len(), 1, "expected one confirmation frame");
    let confirm = envelope_of(said[0]);
    let opened = phone
        .manager
        .decrypt_from_user(&confirm, &device_address)
        .expect("phone opens the confirmation");
    assert_eq!(
        opened.as_deref(),
        Some(prefixes::SESSION_CONFIRM_ENCRYPTED.as_bytes()),
        "the confirmation did not carry the encrypted-confirm marker"
    );

    device_address
}

/// What a device said, with delivery acknowledgements taken out.
///
/// A leaf answers every frame it accepts from a peer it knows (issue 402), so
/// a test about what the device *said* has to separate the two or it is really
/// asserting on an acknowledgement it never meant to look at.
fn spoken(handled: &Handled) -> Vec<&Message> {
    handled
        .outbound
        .iter()
        .filter(|frame| !frame.metadata.contains_key(ACK_FOR_KEY))
        .collect()
}

/// The delivery acknowledgements a device emitted.
fn acknowledgements(handled: &Handled) -> Vec<&Message> {
    handled
        .outbound
        .iter()
        .filter(|frame| frame.metadata.contains_key(ACK_FOR_KEY))
        .collect()
}

/// Pulls the envelope out of a device's `__MLS_ENC__` frame.
fn envelope_of(message: &Message) -> EncryptedMessage {
    let body = message
        .content
        .strip_prefix(prefixes::ENCRYPTED)
        .expect("frame carries an envelope");
    if body.starts_with('{') {
        serde_json::from_str(body).expect("json envelope parses")
    } else {
        let bytes = BASE64.decode(body).expect("envelope is base64");
        EncryptedMessage::from_bytes(&bytes).expect("compact envelope parses")
    }
}

/// Wraps a device's sealed frame the way a transport would deliver it.
fn phone_sealed_frame(phone: &Phone, to: &str, envelope: &EncryptedMessage) -> Message {
    let body = BASE64.encode(envelope.to_bytes());
    Message::new(
        UserId::new(&phone.address).expect("phone address"),
        UserId::new(to).expect("device address"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        format!("{}{}", prefixes::ENCRYPTED, body),
    )
}

#[test]
fn a_phone_and_a_device_pair_and_talk_both_ways() {
    let phone = new_phone();
    let store = Arc::new(MemoryStore::new());
    let mut device = device(store);
    let device_address = pair(&phone, &mut device);

    // Phone to device.
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );

    // Device to phone.
    let answer = device
        .seal(&phone.address, "unlocked", now())
        .expect("device seals");
    let opened = phone
        .manager
        .decrypt_from_user(&envelope_of(&answer), &device_address)
        .expect("phone opens the answer");
    assert_eq!(opened.as_deref(), Some(&b"unlocked"[..]));
}

#[test]
fn a_driven_rekey_reaches_the_device_as_a_session_reset() {
    let phone = new_phone();
    let store = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    assert!(
        device.has_session(&phone.address).expect("session check"),
        "pairing left no session"
    );

    // A phone-driven rekey: the phone discards its own session first and then
    // sends a fresh key package with the reset flag, which is the shape
    // post-compromise security takes for a member that never commits.
    //
    // The teardown-first ordering is the engine's, and it is deliberate there:
    // it makes convergence symmetric whatever the two addresses sort like, so
    // the device always *joins* rather than racing a tiebreaker.
    phone
        .manager
        .delete_session(&device_address)
        .expect("phone discards its own session");

    let phone_package = phone
        .manager
        .take_push_key_package(&device_address)
        .expect("phone mints a package");
    let mut payload: KeyPackagePayload = serde_json::from_str(&format!(
        r#"{{"user_id":{},"key_package_data":[]}}"#,
        serde_json::to_string(&phone.address).expect("address")
    ))
    .expect("skeleton payload");
    payload.key_package_data = phone_package.bundle.key_package_data.clone();
    payload.session_reset = true;
    payload.env_versions = vec![MLS_ENVELOPE_COMPACT_V1];

    let reset_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload serializes")
        ),
    );

    let handled = device.handle(&reset_frame, now()).expect("device resets");
    assert!(
        handled.events.contains(&LeafEvent::SessionReset {
            peer: phone.address.clone(),
        }),
        "a reset flag did not reset the session: {:?}",
        handled.events
    );
    assert!(
        !device.has_session(&phone.address).expect("session check"),
        "the device kept a session the phone had already discarded"
    );

    // And it answers with a fresh package, so the exchange can begin again.
    let said = spoken(&handled);
    assert_eq!(said.len(), 1, "a reset did not produce a fresh key package");
    let fresh = said[0];
    assert!(fresh.content.starts_with(prefixes::KEY_PACKAGE));

    // The phone can complete a second pairing from it, which is what makes the
    // rekey a heal rather than a permanent break.
    import_device_key_package(&phone, fresh);
    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone re-establishes");
    let welcome_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome serializes")
        ),
    );
    let rejoined = device
        .handle(&welcome_frame, now())
        .expect("device rejoins");
    assert!(rejoined.events.contains(&LeafEvent::SessionEstablished {
        peer: phone.address.clone(),
    }));
}

#[test]
fn an_unsigned_control_frame_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    let mut frame = phone_control_frame(
        &phone,
        &device.address().to_string(),
        format!("{}{{}}", prefixes::KEY_PACKAGE),
    );
    frame.metadata.clear();

    let err = device
        .handle(&frame, now())
        .expect_err("unsigned was accepted");
    assert!(
        matches!(err, LeafError::ControlFrameRefused(_)),
        "unsigned control frame produced {err:?}"
    );
}

#[test]
fn half_a_signature_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    let mut frame = phone_control_frame(
        &phone,
        &device.address().to_string(),
        format!("{}{{}}", prefixes::KEY_PACKAGE),
    );
    frame
        .metadata
        .remove(offline_protocol_sealed::CTRL_SIG_META_KEY);

    let err = device
        .handle(&frame, now())
        .expect_err("a key without a signature was accepted");
    assert!(
        matches!(err, LeafError::ControlFrameRefused(_)),
        "half a signature produced {err:?}"
    );
}

#[test]
fn a_signing_key_that_does_not_derive_to_the_sender_is_refused() {
    let phone = new_phone();
    let impostor = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    // A frame that claims to be from the phone, signed correctly, but by
    // somebody else's key. The signature verifies; the derivation does not.
    let mut frame = phone_control_frame(
        &phone,
        &device.address().to_string(),
        format!("{}{{}}", prefixes::KEY_PACKAGE),
    );
    sign_as(&impostor, &mut frame);

    let err = device
        .handle(&frame, now())
        .expect_err("an impostor's key was accepted");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "impersonation produced {err:?}"
    );
}

#[test]
fn a_sender_that_is_not_an_address_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    // The bypass this gate exists to close: claim a nickname, and a check that
    // skipped unparseable identifiers would never run at all.
    let mut frame = phone_control_frame(
        &phone,
        &device.address().to_string(),
        format!("{}{{}}", prefixes::KEY_PACKAGE),
    );
    frame.sender = UserId::new("alice").expect("nickname is a valid user id");
    sign_as(&phone, &mut frame);

    let err = device
        .handle(&frame, now())
        .expect_err("a nickname sender was accepted");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a non-address sender produced {err:?}"
    );
}

#[test]
fn a_key_package_that_claims_another_owner_is_refused() {
    let phone = new_phone();
    let other = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    let package = phone
        .manager
        .take_push_key_package(&device.address().to_string())
        .expect("package");
    let payload = KeyPackagePayload {
        // The body says one peer; the frame is signed by another.
        user_id: other.address.clone(),
        key_package_data: package.bundle.key_package_data,
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: false,
        wire_versions: vec![],
        env_versions: vec![],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };

    let frame = phone_control_frame(
        &phone,
        &device.address().to_string(),
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("a borrowed-name package was accepted");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a mismatched package owner produced {err:?}"
    );
}

#[test]
fn a_welcome_for_another_pairs_group_is_refused() {
    let phone = new_phone();
    let stranger = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    // A Welcome the stranger built for a group of their own, relayed by the
    // phone. Without the group check the device would join a room whose
    // membership it never chose.
    let advertisement = device
        .key_package_frame(&stranger.address, now())
        .expect("device advertises");
    import_device_key_package(&stranger, &advertisement);
    let welcome = stranger
        .manager
        .create_session(&device_address)
        .expect("stranger creates a session");

    let frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("a relayed welcome was accepted");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a foreign welcome produced {err:?}"
    );
}

#[test]
fn state_survives_a_power_cycle() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let device_address = {
        let mut device = device(Arc::clone(&store));
        pair(&phone, &mut device)
    };

    // The device value is gone; only the store remains. This is what a reboot
    // looks like from the outside, and it is the whole reason no MLS state is
    // cached in the device value.
    let mut revived = LeafDevice::resume(Arc::clone(&store), APP_ID).expect("device resumes");
    assert_eq!(
        revived.address().to_string(),
        device_address,
        "the device came back as a different device"
    );

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"still there?")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = revived.handle(&frame, now()).expect("revived device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "still there?".to_string(),
        }],
        "a session did not survive the power cycle"
    );
}

/// The shape of the answer, field by field.
///
/// A delivery acknowledgement is not a control frame: no prefix, no signature,
/// empty content. Its whole meaning is one metadata entry, and the engine that
/// reads it takes the key from the same declaration this asserts against, so a
/// rename moves both ends at once rather than leaving a device talking to
/// itself.
#[test]
fn an_accepted_frame_is_answered_with_a_delivery_acknowledgement() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    assert!(
        frame.requires_ack,
        "the frame under test did not ask for an answer, so it proves nothing"
    );

    let handled = device
        .handle(&frame, now())
        .expect("device opens the frame");
    let answers = acknowledgements(&handled);
    assert_eq!(answers.len(), 1, "an accepted frame was not answered");
    let ack = answers[0];

    assert_eq!(
        ack.metadata.get(ACK_FOR_KEY),
        Some(&frame.id.to_string()),
        "the answer did not name the frame it answers"
    );
    assert_eq!(
        ack.sender.as_str(),
        device_address,
        "an answer from anyone but the recipient is discarded by the peer"
    );
    assert_eq!(
        ack.recipient.as_str(),
        phone.address,
        "the answer went somewhere other than the sender"
    );
    assert!(ack.content.is_empty(), "an answer carries no content");
    assert!(
        !ack.requires_ack,
        "an answer that asks to be answered does not terminate"
    );
    assert!(
        !ack.metadata
            .contains_key(offline_protocol_sealed::CTRL_SIG_META_KEY),
        "an answer is not a control frame and must not be signed as one"
    );
}

/// A stranger gets the silence it got before.
///
/// A record exists only for a peer that cleared the key package gate, so this
/// is the line between a paired phone and anyone else within radio range.
/// Answering the second would hand out two things a device should not give
/// away: a way to make it transmit on demand, and a reply to "is there a node
/// at this address", which against a lock is the first question worth asking.
#[test]
fn a_frame_from_a_peer_this_device_does_not_know_is_not_answered() {
    let phone = new_phone();
    let stranger = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let mut frame = phone_control_frame(
        &stranger,
        &device_address,
        String::from("nothing this device parses"),
    );
    sign_as(&stranger, &mut frame);
    assert!(frame.requires_ack, "the frame did not ask for an answer");

    let handled = device.handle(&frame, now()).expect("a stranger is ignored");
    assert!(
        handled.outbound.is_empty(),
        "a device answered a peer it has never paired with: {:?}",
        handled.outbound
    );
}

/// A frame that names a paired peer and proves nothing is not answered.
///
/// The known-peer gate asks whether an address has ever paired, and a frame's
/// sender is a plaintext field, so anyone who overheard the pair once can
/// write that address on a frame of their own. What closes it is that a frame
/// carrying no prefix this device acts on verifies nothing, so it never earns
/// an answer: without that, a stranger in radio range has a way to make a lock
/// transmit on demand and a reply to "is there a node at this address", which
/// is the whole thing the gate was put there to withhold.
#[test]
fn a_frame_that_names_a_known_peer_but_proves_nothing_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    // No signature at all: whoever built this holds none of the phone's keys
    // and has only copied its address off a frame it overheard.
    let forged = Message::new(
        UserId::new(&phone.address).expect("phone address is a user id"),
        UserId::new(&device_address).expect("device address is a user id"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        String::from("nothing this device parses"),
    );
    assert!(
        forged.requires_ack,
        "the frame under test did not ask for an answer, so it proves nothing"
    );

    let handled = device
        .handle(&forged, now())
        .expect("an unsigned frame is ignored");
    assert!(
        handled.outbound.is_empty(),
        "a device answered a frame that proved nothing about its sender: {:?}",
        handled.outbound
    );
}

/// And such a frame cannot push out what the device really did answer.
///
/// The memory is four deep and evicts oldest-first, so a frame that got into
/// it for free would be a way to empty it: five of them and the device has
/// nothing left to answer a genuine retransmission from, which puts back the
/// full retry ladder this mechanism exists to end. Nothing may be written
/// there on the strength of a plaintext sender field.
#[test]
fn frames_that_prove_nothing_cannot_evict_what_a_device_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let genuine = phone_sealed_frame(&phone, &device_address, &sealed);
    device
        .handle(&genuine, now())
        .expect("first delivery opens");

    // Exactly the depth, which is the fewest that would push the genuine id
    // off the end if junk were remembered. The same four that
    // `a_replay_the_device_no_longer_remembers_is_refused` uses to do it with
    // real frames, so the two move together if the depth ever changes.
    for n in 0..4 {
        let forged = Message::new(
            UserId::new(&phone.address).expect("phone address is a user id"),
            UserId::new(&device_address).expect("device address is a user id"),
            offline_protocol_core::AppId::new(APP_ID).expect("app id"),
            format!("junk {n}"),
        );
        let handled = device.handle(&forged, now()).expect("junk is ignored");
        assert!(
            handled.outbound.is_empty(),
            "a device answered junk: {:?}",
            handled.outbound
        );
    }

    let repeat = device
        .handle(&genuine, now())
        .expect("a retransmission is answered");
    assert_eq!(
        acknowledgements(&repeat).len(),
        1,
        "junk pushed a real answer out of the memory, restoring the retry ladder"
    );
}

/// An unsolicited probe acknowledgement is not answered either.
///
/// It is the other arm that verifies nothing, and it is the more tempting of
/// the two, because it carries a prefix this device recognises. Recognising a
/// prefix is not checking a signature.
#[test]
fn an_unsolicited_probe_acknowledgement_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let forged = Message::new(
        UserId::new(&phone.address).expect("phone address is a user id"),
        UserId::new(&device_address).expect("device address is a user id"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        String::from(prefixes::SESSION_CONFIRM_ACK),
    );

    let handled = device
        .handle(&forged, now())
        .expect("an unsolicited ack is ignored");
    assert!(
        handled.outbound.is_empty(),
        "a device answered an unsolicited probe acknowledgement: {:?}",
        handled.outbound
    );
}

/// A refusal is not a receipt.
///
/// Handing an acknowledgement to whoever just failed the signature gate tells
/// them their frames are being processed, which is the phone's reason for
/// withholding one on a security rejection and is this device's too.
#[test]
fn a_frame_that_is_refused_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    // Signed by the peer, then altered, so it fails on the signature rather
    // than on anything about its shape.
    let mut frame = phone_control_frame(
        &phone,
        &device_address,
        format!("{}not a key package", prefixes::KEY_PACKAGE),
    );
    sign_as(&phone, &mut frame);
    frame.content.push_str(" tampered");

    let err = device
        .handle(&frame, now())
        .expect_err("a tampered frame was accepted");
    assert!(
        matches!(
            err,
            LeafError::ControlFrameRefused(_) | LeafError::MalformedFrame(_)
        ),
        "the frame was refused for an unexpected reason: {err:?}"
    );
}

/// The memory of an answer survives losing power.
///
/// A device that answered and then forgot would meet the retransmission with
/// silence, which is the state this whole mechanism exists to leave, so the
/// record is written before the answer is handed to the caller.
#[test]
fn what_a_device_answered_survives_a_power_cycle() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    device.handle(&frame, now()).expect("first delivery opens");

    // The same flash, a fresh device.
    let mut rebooted = LeafDevice::resume(Arc::clone(&store), APP_ID).expect("device resumes");
    let handled = rebooted
        .handle(&frame, now())
        .expect("a replay after a reboot is answered");
    assert_eq!(
        acknowledgements(&handled).len(),
        1,
        "a device that rebooted met a retransmission with silence"
    );
}

/// A frame that asks for no answer gets none.
#[test]
fn a_frame_that_does_not_ask_for_an_answer_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let mut frame = phone_sealed_frame(&phone, &device_address, &sealed);
    frame.requires_ack = false;

    let handled = device
        .handle(&frame, now())
        .expect("device opens the frame");
    assert!(
        acknowledgements(&handled).is_empty(),
        "a device answered a frame that asked for no answer"
    );
}

/// A frame that arrives twice is answered twice and opened once.
///
/// The second copy is overwhelmingly a retransmission: the peer waits ten
/// seconds for an answer and sends the same frozen bytes again when none comes,
/// and the answer is the frame most likely to have been the one that went
/// missing. Opening it again is impossible, because the ratchet spent that
/// generation on the first copy, so what a device can do is say again what it
/// said before. It is the phone's own rule for a duplicate, for the reason the
/// phone gives: a second copy and a lost answer are not distinguishable here,
/// and staying quiet for the second turns a delivered frame into a failed one.
///
/// The property the older version of this test pinned still holds and is
/// asserted below: the frame is not opened a second time, and nothing reaches
/// firmware suggesting it was.
#[test]
fn a_replayed_sealed_frame_is_answered_again_and_never_opened_twice() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);

    let first = device.handle(&frame, now()).expect("first delivery opens");
    assert!(
        first.events.contains(&LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: String::from("unlock"),
        }),
        "the first delivery did not reach firmware: {:?}",
        first.events
    );
    assert_eq!(
        acknowledgements(&first).len(),
        1,
        "an accepted frame was not answered"
    );

    let second = device.handle(&frame, now()).expect("a replay is answered");
    assert_eq!(
        acknowledgements(&second).len(),
        1,
        "a retransmission went unanswered, which is what makes the peer keep asking"
    );
    assert_eq!(
        acknowledgements(&second)[0].metadata.get(ACK_FOR_KEY),
        Some(&frame.id.to_string()),
        "the repeated answer named a different frame"
    );
    assert!(
        spoken(&second).is_empty(),
        "a replay produced a frame beyond the answer: {:?}",
        spoken(&second)
    );
    assert!(
        !second
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::MessageReceived { .. })),
        "a replayed frame was delivered to firmware a second time: {:?}",
        second.events
    );
}

/// A replay the device no longer remembers answering is still refused.
///
/// The memory is four frames deep, which bounds flash rather than correctness,
/// and this is the edge it puts there: past it a device has nothing to answer
/// from and the ratchet does what it always did. It matters because the whole
/// point of quietening the retransmissions was to leave a real replay
/// visible, and a device that absorbed every one of them would have traded one
/// invisible attack for another.
#[test]
fn a_replay_the_device_no_longer_remembers_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let capture = phone_sealed_frame(&phone, &device_address, &sealed);
    device
        .handle(&capture, now())
        .expect("first delivery opens");

    // Four more, which is exactly the depth, so the captured frame's id falls
    // off the end.
    for n in 0..4 {
        let sealed = phone
            .manager
            .encrypt_for_user(&device_address, format!("later {n}").as_bytes())
            .expect("phone seals");
        let frame = phone_sealed_frame(&phone, &device_address, &sealed);
        device.handle(&frame, now()).expect("later delivery opens");
    }

    let err = device
        .handle(&capture, now())
        .expect_err("a forgotten replay was answered anyway");
    assert!(
        matches!(err, LeafError::Mls(_)),
        "a forgotten replay produced {err:?}"
    );
}

#[test]
fn the_device_answers_a_probe_with_an_ack() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    pair(&phone, &mut device);

    let probe = phone_control_frame(
        &phone,
        &device.address().to_string(),
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    let handled = device.handle(&probe, now()).expect("device answers");

    let said = spoken(&handled);
    assert_eq!(said.len(), 1);
    assert_eq!(
        said[0].content,
        prefixes::SESSION_CONFIRM_ACK,
        "a probe was not answered with an acknowledgement"
    );
    assert!(
        said[0]
            .metadata
            .contains_key(offline_protocol_sealed::CTRL_SIG_META_KEY),
        "the acknowledgement went out unsigned"
    );
}

#[test]
fn a_probe_without_a_session_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    // No pairing: this is a device that was wiped, or one this peer never
    // paired with. The phone confirms its session on the acknowledgement and
    // then flushes everything it had queued into it, so answering here would
    // leave it holding a session confirmed against a device that cannot
    // decrypt a single frame of it, with nothing afterwards to tell it so.
    let probe = phone_control_frame(
        &phone,
        &device.address().to_string(),
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    let handled = device.handle(&probe, now()).expect("probe is handled");

    assert!(
        handled.outbound.is_empty(),
        "a device with no session confirmed one anyway"
    );
    assert!(
        matches!(handled.events.as_slice(), [LeafEvent::Ignored { .. }]),
        "a session-less probe produced {:?}",
        handled.events
    );
}

#[test]
fn an_unsolicited_acknowledgement_does_not_establish_a_session() {
    let stranger = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));

    // A leaf emits acknowledgements and never probes, so it never has one
    // outstanding and every inbound acknowledgement is unsolicited. Acting on
    // one would hand a session to anyone holding a keypair: the frame is
    // signed, and a signature that derives to its own address costs nothing to
    // produce. The phone gates the same frame on holding a session of its own,
    // and the leaf profile lists this prefix under what a device emits rather
    // than under what it accepts.
    let frame = phone_control_frame(
        &stranger,
        &device.address().to_string(),
        prefixes::SESSION_CONFIRM_ACK.to_string(),
    );

    let handled = device
        .handle(&frame, now())
        .expect("the acknowledgement is handled");
    assert!(
        !handled
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::SessionEstablished { .. })),
        "an unsolicited acknowledgement established a session: {:?}",
        handled.events
    );
    assert!(
        handled.outbound.is_empty(),
        "an unsolicited acknowledgement produced a frame"
    );
    assert!(
        !device
            .has_session(&stranger.address)
            .expect("session check"),
        "an unsolicited acknowledgement left a session on flash"
    );

    // And what firmware would have acted on is refused where it counts: there
    // is no session to seal into, whatever the event said.
    let err = device
        .seal(&stranger.address, "unlock", now())
        .expect_err("sealed to a peer that only sent an acknowledgement");
    assert!(matches!(err, LeafError::NoSession(_)), "produced {err:?}");
}

#[test]
fn a_peer_that_already_has_a_key_package_is_not_sent_another() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    // The device advertises first, which is how pairing starts.
    let _ = device
        .key_package_frame(&phone.address, now())
        .expect("device advertises");

    // The phone answers with its own package, as the engine does. If the
    // device answered that in turn, the two would trade packages forever, and
    // each exchange spends an init key.
    let package = phone
        .manager
        .take_push_key_package(&device_address)
        .expect("package");
    let payload = KeyPackagePayload {
        user_id: phone.address.clone(),
        key_package_data: package.bundle.key_package_data,
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: false,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    let frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload")
        ),
    );

    let handled = device
        .handle(&frame, now())
        .expect("device records the peer");
    assert!(
        spoken(&handled).is_empty(),
        "the device answered a key package with another one, which loops"
    );
    assert!(handled.events.contains(&LeafEvent::PeerAdvertised {
        peer: phone.address.clone(),
    }));
}

#[test]
fn the_envelope_encoding_follows_what_the_peer_advertised() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    // Pairing recorded nothing about the phone's capabilities, because the
    // phone never sent a key package in this flow. Absent means the floor.
    assert!(device
        .peer_env_versions(&phone.address)
        .expect("record")
        .is_empty());
    let floor = device
        .seal(&phone.address, "floor", now())
        .expect("device seals");
    let body = floor
        .content
        .strip_prefix(prefixes::ENCRYPTED)
        .expect("envelope");
    assert!(
        body.starts_with('{'),
        "a peer that advertised nothing was sent a compact envelope"
    );

    // And the phone opens it, because the JSON envelope is the permanent floor
    // rather than a legacy path anything may stop parsing.
    let opened = phone
        .manager
        .decrypt_from_user(&envelope_of(&floor), &device_address)
        .expect("phone opens the floor envelope");
    assert_eq!(opened.as_deref(), Some(&b"floor"[..]));
}

/// A store that fails every write after it is armed.
///
/// Used as a negative control for the rule this crate is built around: if a
/// persist fails, no frame may exist. A device that emitted first and
/// persisted second would come back from a power cut and reuse an AEAD nonce.
#[derive(Default)]
struct FailingStore {
    inner: MemoryStore,
    failing: AtomicBool,
    writes_after_arming: Mutex<usize>,
}

impl FailingStore {
    fn arm(&self) {
        self.failing.store(true, Ordering::SeqCst);
    }
}

impl LeafStore for FailingStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        if self.failing.load(Ordering::SeqCst) {
            if let Ok(mut count) = self.writes_after_arming.lock() {
                *count += 1;
            }
            return Err(StoreError::Store("flash is on fire".to_string()));
        }
        self.inner.store(key_type, key_id, data)
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        self.inner.load(key_type, key_id)
    }

    fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError> {
        self.inner.delete(key_type, key_id)
    }
}

#[test]
fn a_failing_store_produces_no_frame() {
    let phone = new_phone();
    let store = Arc::new(FailingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    pair(&phone, &mut device);

    store.arm();

    let err = device
        .seal(&phone.address, "unlock", now())
        .expect_err("a frame was produced despite the store failing");
    assert!(
        matches!(err, LeafError::Storage(_)),
        "a failing store produced {err:?}"
    );

    // The control: the write really was attempted, so this test is failing at
    // the persist rather than short-circuiting somewhere earlier and passing
    // for the wrong reason.
    assert!(
        *store.writes_after_arming.lock().expect("count") > 0,
        "no write was even attempted, so this proves nothing about ordering"
    );
}

/// A store that fails to write peer records once armed, and nothing else.
///
/// Narrow on purpose. A store that failed everything would fail the frame's
/// own persist and never reach the question this is asked to answer, which is
/// what a device does when the frame is already open and only the bookkeeping
/// behind the answer fails.
#[derive(Default)]
struct PeerWriteFailingStore {
    inner: MemoryStore,
    failing: AtomicBool,
}

impl PeerWriteFailingStore {
    fn arm(&self) {
        self.failing.store(true, Ordering::SeqCst);
    }
}

impl LeafStore for PeerWriteFailingStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        if key_type == KEY_TYPE_PEER && self.failing.load(Ordering::SeqCst) {
            return Err(StoreError::Store("flash is on fire".to_string()));
        }
        self.inner.store(key_type, key_id, data)
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        self.inner.load(key_type, key_id)
    }

    fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError> {
        self.inner.delete(key_type, key_id)
    }
}

/// A store that fails while recording the answer does not eat the message.
///
/// By the time the answer is minted the frame is open and the ratchet has
/// spent that generation, so what it produced is already owed to firmware: an
/// unlock this device really did receive cannot be thrown away because the
/// receipt for it would not write. The retransmission that follows will be
/// refused as a replay with nothing remembered to answer it from, which is the
/// ordinary retry ladder and is recoverable. A lost command is not.
#[test]
fn a_store_that_fails_while_recording_the_answer_still_reports_the_message() {
    let phone = new_phone();
    let store = Arc::new(PeerWriteFailingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);

    store.arm();

    let handled = device
        .handle(&frame, now())
        .expect("a frame this device opened was reported as a failure");
    assert!(
        handled.events.contains(&LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: String::from("unlock"),
        }),
        "the command was discarded because its receipt would not store: {:?}",
        handled.events
    );

    // No answer, because the record behind it is not durable and this crate
    // emits nothing it has not persisted first.
    assert!(
        acknowledgements(&handled).is_empty(),
        "an answer went out with nothing on flash behind it"
    );

    // And firmware is told, rather than left to infer it from a silence that
    // looks exactly like a healthy device on a quiet link.
    assert!(
        handled
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::Ignored { reason } if reason.contains("could not be stored"))),
        "a store failure was swallowed: {:?}",
        handled.events
    );
}

#[test]
fn a_device_refuses_to_replace_its_own_identity() {
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let first = LeafDevice::provision(Arc::clone(&store), APP_ID).expect("first provisioning");

    let err = LeafDevice::provision(Arc::clone(&store), APP_ID)
        .expect_err("a second provisioning replaced the identity");
    assert!(matches!(err, LeafError::AlreadyProvisioned));

    // And `open` is the safe door: it resumes rather than replacing.
    let reopened = LeafDevice::open(store, APP_ID).expect("open resumes");
    assert_eq!(reopened.address().to_string(), first.address().to_string());
}

#[test]
fn a_device_address_derives_from_its_own_key() {
    // The property every trust gate in this protocol rests on, checked from
    // the outside: what the device calls itself is a function of the key it
    // signs with, so a peer can refute a claim without a directory.
    let mut device = device(Arc::new(MemoryStore::new()));
    let probe_target = device.address().to_string();

    let phone = new_phone();
    // Paired first, because a probe is only answered by a device that holds a
    // session; the acknowledgement is just the most convenient signed frame to
    // read the key out of.
    pair(&phone, &mut device);
    let mut frame = phone_control_frame(
        &phone,
        &probe_target,
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    sign_as(&phone, &mut frame);

    let handled = device.handle(&frame, now()).expect("probe answered");
    let ack = spoken(&handled)[0];
    let key = BASE64
        .decode(
            ack.metadata
                .get(offline_protocol_sealed::CTRL_PK_META_KEY)
                .expect("ack carries a key"),
        )
        .expect("key is base64");

    assert_eq!(
        derive_address(&key).expect("derive").to_string(),
        device.address().to_string(),
        "the device signed with a key that does not derive to its own address"
    );
}

/// A store that can be asked what is in it.
///
/// `LeafStore` deliberately offers no enumeration, which is right for the
/// seam and useless for a test that has to prove something was *removed*.
#[derive(Debug, Default)]
struct CountingStore {
    entries: Mutex<BTreeMap<(String, String), Vec<u8>>>,
}

impl CountingStore {
    /// The key ids held under one key type.
    fn keys_of(&self, key_type: &str) -> Vec<String> {
        self.entries
            .lock()
            .expect("lock")
            .keys()
            .filter(|(held, _)| held == key_type)
            .map(|(_, id)| id.clone())
            .collect()
    }

    /// Prior-epoch records, which are the `:max` marker's siblings.
    fn epoch_records(&self) -> Vec<String> {
        self.keys_of(KEY_TYPE_GROUP_EPOCH)
            .into_iter()
            .filter(|id| !id.ends_with(":max"))
            .collect()
    }
}

impl LeafStore for CountingStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        self.entries
            .lock()
            .expect("lock")
            .insert((key_type.to_string(), key_id.to_string()), data.to_vec());
        Ok(())
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        Ok(self
            .entries
            .lock()
            .expect("lock")
            .get(&(key_type.to_string(), key_id.to_string()))
            .cloned())
    }

    fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError> {
        self.entries
            .lock()
            .expect("lock")
            .remove(&(key_type.to_string(), key_id.to_string()));
        Ok(())
    }
}

/// Drives one phone-side commit and delivers it to the device.
fn commit_to(phone: &Phone, device: &mut LeafDevice, device_address: &str) {
    let group_id = GroupId::for_session(&phone.address, device_address).expect("pair group id");
    let commit = phone.manager.update_keys(&group_id).expect("phone commits");
    let frame = phone_sealed_frame(phone, device_address, &commit);
    let handled = device
        .handle(&frame, now())
        .expect("device applies the commit");
    assert!(
        handled
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::CommitApplied { .. })),
        "a commit did not apply: {:?}",
        handled.events
    );
}

#[test]
fn a_commit_trims_the_prior_epochs_it_leaves_behind() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    // Post-compromise security arrives on the phone's cadence, so on a device
    // that lives for years this is the loop that runs forever. Every commit
    // leaves the epoch it departed behind as a record, and mls-rs leaves it to
    // the storage provider to decide how many of those to keep: a provider
    // that keeps all of them fills a part with a few hundred kilobytes of
    // flash, and keeps every one of those epochs' secrets while it does, so a
    // device taken apart later reads back everything it ever received.
    for _ in 0..12 {
        commit_to(&phone, &mut device, &device_address);
    }

    let records = store.epoch_records();
    assert!(
        records.len() <= 3,
        "twelve commits left {} prior-epoch records: {records:?}",
        records.len()
    );

    // And the window that is kept is still a working one: the session did not
    // survive by being trimmed into uselessness.
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"still talking")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "still talking".to_string(),
        }]
    );
}

#[test]
fn unpairing_erases_the_prior_epoch_records_too() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    commit_to(&phone, &mut device, &device_address);
    commit_to(&phone, &mut device, &device_address);
    assert!(
        !store.epoch_records().is_empty(),
        "the setup wrote no epoch records, so this test would pass vacuously"
    );

    device.unpair(&phone.address).expect("device unpairs");

    // Each of those records holds an epoch's secrets. Leaving them behind is
    // key material outliving the erasure the owner asked for, under a name the
    // next session with the same peer answers to, because a pair's group id is
    // derived from the two addresses and does not change on a re-pair.
    assert!(
        store.epoch_records().is_empty(),
        "unpairing left epoch records behind: {:?}",
        store.epoch_records()
    );
    assert!(
        store.keys_of(KEY_TYPE_PEER).is_empty(),
        "unpairing left the peer record behind"
    );
    assert!(
        !device.has_session(&phone.address).expect("session check"),
        "unpairing left a session"
    );
}

#[test]
fn a_corrupt_group_state_is_not_reported_as_a_missing_session() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    pair(&phone, &mut device);

    // A store handing back bytes this device did not write. Reported as a
    // missing session it sends a bench chasing a re-pair, which is the one
    // repair that cannot work: the pairing is fine and the flash is not.
    let key = store
        .keys_of(KEY_TYPE_GROUP_STATE)
        .into_iter()
        .next()
        .expect("pairing wrote group state");
    store
        .store(KEY_TYPE_GROUP_STATE, &key, b"not a group")
        .expect("store");

    let err = device
        .seal(&phone.address, "unlock", now())
        .expect_err("a corrupt group state still produced a frame");
    assert!(
        matches!(err, LeafError::Storage(_)),
        "a corrupt group state produced {err:?}"
    );

    // The control: an absent session is still the other error, so this test is
    // not simply asserting that everything is a storage failure.
    let stranger = new_phone();
    let err = device
        .seal(&stranger.address, "unlock", now())
        .expect_err("sealed to a peer with no session");
    assert!(
        matches!(err, LeafError::NoSession(_)),
        "an absent session produced {err:?}"
    );
}

#[test]
fn unpairing_sweeps_epochs_a_corrupt_marker_cannot_bound() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    commit_to(&phone, &mut device, &device_address);
    commit_to(&phone, &mut device, &device_address);
    assert!(
        !store.epoch_records().is_empty(),
        "the setup wrote no epoch records, so this test would pass vacuously"
    );

    // The marker is what bounds the sweep, and it is one more record on a part
    // whose flash can hand back something else. Anchoring at zero when it does
    // deletes one record, returns `Ok`, and leaves the rest of the epochs'
    // secrets on flash under a name the next session with this peer answers to.
    let marker = store
        .keys_of(KEY_TYPE_GROUP_EPOCH)
        .into_iter()
        .find(|id| id.ends_with(":max"))
        .expect("a marker was written");
    store
        .store(KEY_TYPE_GROUP_EPOCH, &marker, b"not eight bytes")
        .expect("store");

    device.unpair(&phone.address).expect("device unpairs");

    assert!(
        store.epoch_records().is_empty(),
        "a corrupt marker left epoch records behind: {:?}",
        store.epoch_records()
    );
}

/// A store that refuses to write one key, to cut power at a chosen moment.
struct CutStore {
    inner: MemoryStore,
    refuse: Mutex<Option<String>>,
}

impl CutStore {
    fn cutting(key_id: &str) -> Self {
        Self {
            inner: MemoryStore::new(),
            refuse: Mutex::new(Some(key_id.to_string())),
        }
    }

    fn restore_power(&self) {
        *self.refuse.lock().expect("lock") = None;
    }
}

impl LeafStore for CutStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        if self.refuse.lock().expect("lock").as_deref() == Some(key_id) {
            return Err(StoreError::Store("power cut".to_string()));
        }
        self.inner.store(key_type, key_id, data)
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        self.inner.load(key_type, key_id)
    }

    fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError> {
        self.inner.delete(key_type, key_id)
    }
}

#[test]
fn a_provisioning_cut_between_the_two_identity_writes_is_recoverable() {
    // An identity is two entries and the store is atomic per entry, not across
    // a pair, so a cut lands between them. The secret is written last and is
    // the marker `provision` refuses on, which is what makes the torn state one
    // the next boot overwrites. Written the other way round the two checks
    // disagree, `open` has no third door, and a device that lost power once on
    // its very first boot answers every call with an error forever.
    let store = Arc::new(CutStore::cutting("signature_secret"));

    let err = LeafDevice::provision(Arc::clone(&store) as Arc<dyn LeafStore>, APP_ID)
        .expect_err("the cut write reported success");
    assert!(matches!(err, LeafError::Storage(_)), "cut produced {err:?}");

    // The control: the first write really did land, so this is the torn state
    // and not simply an empty store.
    assert!(
        store
            .load(KEY_TYPE_IDENTITY, "signature_public")
            .expect("load")
            .is_some(),
        "nothing was written at all, so this proves nothing about ordering"
    );

    store.restore_power();
    let device = LeafDevice::open(Arc::clone(&store) as Arc<dyn LeafStore>, APP_ID)
        .expect("a device that was cut mid-provisioning could not be opened");

    // And it is a working identity, not a half of one.
    let resumed = LeafDevice::resume(store as Arc<dyn LeafStore>, APP_ID).expect("device resumes");
    assert_eq!(resumed.address().to_string(), device.address().to_string());
}

#[test]
fn a_replayed_session_reset_does_not_tear_down_the_new_session() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    // A reset frame, captured off the air the first time it was sent.
    phone
        .manager
        .delete_session(&device_address)
        .expect("phone discards its own session");
    let package = phone
        .manager
        .take_push_key_package(&device_address)
        .expect("phone mints a package");
    let payload = KeyPackagePayload {
        user_id: phone.address.clone(),
        key_package_data: package.bundle.key_package_data,
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: true,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    let reset_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload")
        ),
    );

    let handled = device.handle(&reset_frame, now()).expect("device resets");
    assert!(handled.events.contains(&LeafEvent::SessionReset {
        peer: phone.address.clone(),
    }));

    // The pair rebuilds, as a driven rekey is meant to.
    import_device_key_package(&phone, spoken(&handled)[0]);
    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone re-establishes");
    let welcome_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome")
        ),
    );
    device
        .handle(&welcome_frame, now())
        .expect("device rejoins");
    assert!(device.has_session(&phone.address).expect("session check"));

    // Now the captured frame is sent again. Its signature verifies exactly as
    // well as it did the first time, and it is inside the freshness window, so
    // neither of those is what stops it: the device refuses it because its
    // stamp is not newer than the last reset it acted on. Without that mark, a
    // frame captured once is a session teardown replayable for as long as the
    // window lasts.
    let replayed = device
        .handle(&reset_frame, now())
        .expect("the replay is handled");
    assert!(
        !replayed.events.contains(&LeafEvent::SessionReset {
            peer: phone.address.clone(),
        }),
        "a replayed reset tore down the session again: {:?}",
        replayed.events
    );
    assert!(
        device.has_session(&phone.address).expect("session check"),
        "a replayed reset discarded a session the peer still holds"
    );

    // And the session it kept is the working one.
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );
}

#[test]
fn a_flood_of_strangers_cannot_displace_an_established_peer() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    // The phone advertises, so it holds a record like any other peer and is a
    // candidate for eviction on the same terms.
    let package = phone
        .manager
        .take_push_key_package(&device_address)
        .expect("package");
    let payload = KeyPackagePayload {
        user_id: phone.address.clone(),
        key_package_data: package.bundle.key_package_data,
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: false,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    let frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload")
        ),
    );
    device
        .handle(&frame, now())
        .expect("device records the phone");

    // Producing a signature that derives to its own address is as hard as
    // generating a key, so a stranger's frame costs nothing to make. Each one
    // that lands writes a peer record and mints a package, both to flash.
    for index in 0..24 {
        let stranger = new_phone();
        let payload = KeyPackagePayload {
            user_id: stranger.address.clone(),
            key_package_data: vec![index],
            remaining_lifetime_ms: 0,
            timestamp_ms: 0,
            session_reset: false,
            wire_versions: vec![],
            env_versions: vec![],
            rich_versions: vec![],
            data_versions: vec![],
            ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
            svc_versions: Vec::new(),
            ack_versions: Vec::new(),
            nostr_pubkey: None,
        };
        let frame = phone_control_frame(
            &stranger,
            &device_address,
            format!(
                "{}{}",
                prefixes::KEY_PACKAGE,
                serde_json::to_string(&payload).expect("payload")
            ),
        );
        // Admitted or refused, both are fine. What is not fine is unbounded.
        let _ = device.handle(&frame, now());
    }

    assert!(
        store.keys_of(KEY_TYPE_PEER).len() <= 16,
        "a flood grew the peer table to {}",
        store.keys_of(KEY_TYPE_PEER).len()
    );

    // The property that matters: whoever the flood displaced, it was not the
    // peer the owner actually paired with.
    assert!(
        device.has_session(&phone.address).expect("session check"),
        "a flood of strangers evicted the established peer"
    );
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );
}

#[test]
fn a_welcome_whose_body_lies_about_its_group_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    // The phone builds a group that is not this pair's, and does it with the
    // package the device minted for the phone, so the reference check passes
    // on material that really was handed to this peer. That is what keeps this
    // test pointed at the gate it names rather than at an earlier one.
    let advertisement = device
        .key_package_frame(&phone.address, now())
        .expect("device advertises");
    let decoy = phone
        .manager
        .create_group("decoy")
        .expect("phone creates a group that is not this pair's");
    let (foreign, _commit) = phone
        .manager
        .add_group_member(
            &decoy.group_id,
            &device_address,
            &raw_key_package(&advertisement),
        )
        .expect("phone adds the device to the decoy group");

    // The body then lies: it names the phone as inviter and this pair's own
    // group id, so both of the checks that read the body pass. Only the
    // Welcome inside disagrees, and it is the one that decides which group is
    // actually joined.
    let forged = WelcomeMessage {
        group_id: GroupId::for_session(&phone.address, &device_address).expect("pair group id"),
        welcome_data: foreign.welcome_data.clone(),
        inviter_id: phone.address.clone(),
        group_name: None,
        timestamp_ms: 0,
    };
    let frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&forged).expect("welcome")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("a welcome whose body lied was accepted");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a mismatched welcome produced {err:?}"
    );
    assert!(
        !device.has_session(&phone.address).expect("session check"),
        "the refused welcome still left a session on flash"
    );
}

/// A store that refuses writes of one key type while armed.
///
/// A power cut lands between two entries rather than inside one, and this is
/// how that looks to a caller: everything before the cut is durable, the entry
/// at the cut is not, and the device is asked to carry on afterwards.
struct TornStore {
    inner: MemoryStore,
    refuse_type: Mutex<Option<String>>,
    refusals: Mutex<usize>,
    keys: Mutex<Vec<(String, String)>>,
}

impl TornStore {
    fn new() -> Self {
        Self {
            inner: MemoryStore::new(),
            refuse_type: Mutex::new(None),
            refusals: Mutex::new(0),
            keys: Mutex::new(Vec::new()),
        }
    }

    /// Prior-epoch records held, which `LeafStore` itself cannot enumerate.
    fn epoch_records(&self) -> Vec<String> {
        self.keys
            .lock()
            .expect("lock")
            .iter()
            .filter(|(held, id)| held == KEY_TYPE_GROUP_EPOCH && !id.ends_with(":max"))
            .map(|(_, id)| id.clone())
            .collect()
    }

    fn cut(&self, key_type: &str) {
        *self.refuse_type.lock().expect("lock") = Some(key_type.to_string());
    }

    fn restore_power(&self) {
        *self.refuse_type.lock().expect("lock") = None;
    }

    fn refusals(&self) -> usize {
        *self.refusals.lock().expect("lock")
    }
}

impl LeafStore for TornStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        if self.refuse_type.lock().expect("lock").as_deref() == Some(key_type) {
            *self.refusals.lock().expect("lock") += 1;
            return Err(StoreError::Store("power cut".to_string()));
        }
        self.inner.store(key_type, key_id, data)?;
        let mut keys = self.keys.lock().expect("lock");
        if !keys.iter().any(|(t, i)| t == key_type && i == key_id) {
            keys.push((key_type.to_string(), key_id.to_string()));
        }
        Ok(())
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        self.inner.load(key_type, key_id)
    }

    fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError> {
        self.inner.delete(key_type, key_id)?;
        self.keys
            .lock()
            .expect("lock")
            .retain(|(t, i)| !(t == key_type && i == key_id));
        Ok(())
    }
}

#[test]
fn a_cut_between_the_epoch_records_and_the_state_does_not_wedge_the_session() {
    let phone = new_phone();
    let store = Arc::new(TornStore::new());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    // A healthy commit first, so the group has a marker to get ahead of. The
    // wedge this guards needs a marker that already exists.
    commit_to(&phone, &mut device, &device_address);

    // The cut: the commit's epoch records reach flash, the state does not.
    // mls-rs sequences every later insert against the marker, so a marker that
    // landed here without its state refuses every commit that follows, for
    // good: the retry offers the epoch id the marker has already counted.
    store.cut(KEY_TYPE_GROUP_STATE);
    let group_id = GroupId::for_session(&phone.address, &device_address).expect("pair group id");
    let commit = phone.manager.update_keys(&group_id).expect("phone commits");
    let frame = phone_sealed_frame(&phone, &device_address, &commit);
    let err = device
        .handle(&frame, now())
        .expect_err("a state write that failed still reported success");
    assert!(
        matches!(err, LeafError::Storage(_)),
        "a cut state write produced {err:?}"
    );

    // The control: the write really was refused, so this test is exercising
    // the torn window rather than passing because nothing was attempted.
    assert!(
        store.refusals() > 0,
        "no state write was attempted, so this proves nothing about the window"
    );

    // Power comes back and the phone retries the frame it never saw answered,
    // which is what a radio does with anything unacknowledged.
    store.restore_power();
    let retried = device
        .handle(&frame, now())
        .expect("the retried commit was refused, so the session is wedged");
    assert!(
        retried
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::CommitApplied { .. })),
        "the retried commit did not apply: {:?}",
        retried.events
    );

    // And the session is a working one rather than one that merely stopped
    // reporting errors.
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let app_frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&app_frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );

    // The device answers too, so its own ratchet advanced rather than merely
    // its reader.
    let answer = device
        .seal(&phone.address, "unlocked", now())
        .expect("device seals");
    let opened = phone
        .manager
        .decrypt_from_user(&envelope_of(&answer), &device_address)
        .expect("phone opens the answer");
    assert_eq!(opened.as_deref(), Some(&b"unlocked"[..]));
}

#[test]
fn a_peer_that_paired_through_a_welcome_is_in_the_audit_list() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    pair(&phone, &mut device);

    // Authorization is the obligation this crate cannot discharge, and
    // `peers` is what it offers firmware instead: the list of who a device
    // ended up holding. A session missing from it is one nobody can audit and
    // nobody can point `unpair` at, and advertise-then-Welcome is the ordinary
    // way a session comes to exist, not an unusual one.
    assert!(
        device.has_session(&phone.address).expect("session check"),
        "the pairing left no session, so this test would pass vacuously"
    );
    let peers = device.peers().expect("peers");
    assert!(
        peers.contains(&phone.address),
        "a peer this device holds a session with is missing from the audit list: {peers:?}"
    );

    // And the list is actionable: what it names can be removed.
    device.unpair(&phone.address).expect("device unpairs");
    assert!(
        !device.has_session(&phone.address).expect("session check"),
        "unpairing a peer from the audit list left its session"
    );
    assert!(
        device.peers().expect("peers").is_empty(),
        "unpairing left the peer in the audit list"
    );
}

#[test]
fn a_probe_against_a_group_state_that_will_not_load_is_not_answered() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    pair(&phone, &mut device);

    // Bytes on flash are not a session. A peer confirms its session on the
    // acknowledgement and then flushes everything it queued into it, so a
    // device that answered on the strength of a state it cannot load would
    // confirm a session it cannot open one frame of, and its silence
    // afterwards is indistinguishable from a quiet link.
    let key = store
        .keys_of(KEY_TYPE_GROUP_STATE)
        .into_iter()
        .next()
        .expect("pairing wrote group state");
    store
        .store(KEY_TYPE_GROUP_STATE, &key, b"not a group")
        .expect("store");

    let probe = phone_control_frame(
        &phone,
        &device.address().to_string(),
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    let err = device
        .handle(&probe, now())
        .expect_err("a device with an unloadable session confirmed one anyway");

    // And it is reported as what it is. A store handing back bytes this device
    // did not write is not a missing session, and sending a bench to re-pair
    // is sending it after the one repair that cannot work.
    assert!(
        matches!(err, LeafError::Storage(_)),
        "an unloadable state produced {err:?}"
    );
}

#[test]
fn a_resumed_device_refuses_a_public_key_its_secret_did_not_make() {
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let original = LeafDevice::provision(Arc::clone(&store), APP_ID).expect("provisioning");
    let address = original.address().to_string();
    let own = store
        .load(KEY_TYPE_IDENTITY, "signature_public")
        .expect("load")
        .expect("provisioning wrote a public key");

    // The identity is two entries, and the reason this crate has a durability
    // contract at all is that a part can hand back something other than what
    // was written. Somebody else's public key is the shape that does the most
    // damage quietly: the device comes back at an address no peer knows it by
    // and signs frames that verify nowhere, and every gate in the protocol
    // refuses it while naming a different failure than the one that happened.
    let other_store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    LeafDevice::provision(Arc::clone(&other_store), APP_ID).expect("second device");
    let foreign = other_store
        .load(KEY_TYPE_IDENTITY, "signature_public")
        .expect("load")
        .expect("the second device wrote a public key");
    assert_ne!(
        foreign, own,
        "the two devices minted the same key, so this test would prove nothing"
    );

    store
        .store(KEY_TYPE_IDENTITY, "signature_public", &foreign)
        .expect("store");
    let err = LeafDevice::resume(Arc::clone(&store), APP_ID)
        .expect_err("a device resumed on a key its secret does not derive to");
    assert!(
        matches!(err, LeafError::Storage(_)),
        "a mismatched identity pair produced {err:?}"
    );

    // The control: with its own key back, the same device resumes as itself.
    // This refuses a mismatch rather than refusing everything.
    store
        .store(KEY_TYPE_IDENTITY, "signature_public", &own)
        .expect("store");
    let resumed = LeafDevice::resume(store, APP_ID).expect("the intact pair still resumes");
    assert_eq!(resumed.address().to_string(), address);
}

#[test]
fn unpairing_sweeps_epochs_when_the_state_entry_cannot_be_read() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    commit_to(&phone, &mut device, &device_address);
    commit_to(&phone, &mut device, &device_address);
    assert!(
        !store.epoch_records().is_empty(),
        "the setup wrote no epoch records, so this test would pass vacuously"
    );

    // The sweep's first anchor is the marker inside the state entry, and this
    // is the case that anchor cannot cover: the entry itself is unreadable, so
    // neither the marker nor the group's own epoch can bound anything. The
    // separate high-water record exists for exactly this, and without it the
    // sweep would anchor at zero, delete one record, return `Ok`, and leave
    // the rest of the epochs' secrets on flash under a name the next session
    // with this peer answers to.
    let key = store
        .keys_of(KEY_TYPE_GROUP_STATE)
        .into_iter()
        .next()
        .expect("pairing wrote group state");
    store
        .store(KEY_TYPE_GROUP_STATE, &key, b"nope")
        .expect("store");

    device.unpair(&phone.address).expect("device unpairs");

    assert!(
        store.epoch_records().is_empty(),
        "an unreadable state entry left epoch records behind: {:?}",
        store.epoch_records()
    );
}

/// Builds a key package advertisement body, with the package data left as
/// junk because a device records what a peer advertises and never parses the
/// package itself: the phone builds the group, not the device.
fn advertisement_body(user_id: &str) -> String {
    let payload = KeyPackagePayload {
        user_id: user_id.to_string(),
        key_package_data: vec![7],
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: false,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    format!(
        "{}{}",
        prefixes::KEY_PACKAGE,
        serde_json::to_string(&payload).expect("payload")
    )
}

#[test]
fn a_frame_addressed_to_another_node_is_ignored() {
    let phone = new_phone();
    let bystander = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = device.address().to_string();

    // One body, sent twice, to two different recipients. That is the whole
    // test: the frames are otherwise identical, so whatever the device does
    // differently it did because of the addressing and nothing else.
    let body = advertisement_body(&phone.address);

    // A radio hears what it is not the recipient of. This frame is honestly
    // signed and its signature covers the recipient, so every gate below the
    // dispatch verifies it happily; only the addressing says it is not ours.
    let overheard = phone_control_frame(&phone, &bystander.address, body.clone());
    let handled = device
        .handle(&overheard, now())
        .expect("overhearing a neighbour is not a failure");

    assert!(
        handled.outbound.is_empty(),
        "the device answered a frame addressed to somebody else: {:?}",
        handled.outbound.len()
    );
    assert!(
        matches!(handled.events.as_slice(), [LeafEvent::Ignored { .. }]),
        "an overheard frame produced {:?}",
        handled.events
    );

    // And it spent nothing. Each of these is a write to a part with a finite
    // number of them, and the key package is a private init key minted for a
    // pairing nobody asked this device for.
    assert!(
        store.keys_of(KEY_TYPE_PEER).is_empty(),
        "an overheard frame wrote a peer record: {:?}",
        store.keys_of(KEY_TYPE_PEER)
    );
    assert!(
        store.keys_of(KEY_TYPE_KEY_PACKAGE).is_empty(),
        "an overheard frame minted a key package: {:?}",
        store.keys_of(KEY_TYPE_KEY_PACKAGE)
    );
    assert!(
        device.peers().expect("peers").is_empty(),
        "an overheard frame put a peer in the audit list"
    );

    // The control: the same body addressed to this device is acted on. Without
    // this the test above would pass on a device that answers nothing at all.
    let addressed = phone_control_frame(&phone, &device_address, body);
    let handled = device
        .handle(&addressed, now())
        .expect("device handles a frame addressed to it");
    assert_eq!(
        spoken(&handled).len(),
        1,
        "a frame addressed to this device was not answered: {:?}",
        handled.events
    );
    assert!(
        device.peers().expect("peers").contains(&phone.address),
        "a frame addressed to this device did not record its sender"
    );
}

#[test]
fn a_sealed_frame_addressed_elsewhere_is_not_opened() {
    let phone = new_phone();
    let bystander = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    // A frame this device really can open, addressed to somebody else. The
    // data plane carries no signature, by design: MLS authenticates its own
    // sender, so the AEAD covers the ciphertext and nothing covers the
    // addressing beside it. Anyone who captured this frame can therefore
    // rewrite its recipient and hand it back.
    //
    // Openable is not the same question as addressed here, and without the
    // dispatch gate the device never asks the second one: it opens the
    // ciphertext and reports an ordinary message. Firmware that also carries
    // frames for its neighbours would then act on the same frame it forwards.
    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let elsewhere = phone_sealed_frame(&phone, &bystander.address, &sealed);

    let handled = device
        .handle(&elsewhere, now())
        .expect("a frame addressed elsewhere is not a failure");
    assert!(
        matches!(handled.events.as_slice(), [LeafEvent::Ignored { .. }]),
        "a sealed frame addressed elsewhere produced {:?}",
        handled.events
    );

    // The control: the same ciphertext addressed here opens. What the device
    // refused was the addressing rather than the frame.
    let addressed = phone_sealed_frame(&phone, &device_address, &sealed);
    let handled = device.handle(&addressed, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );
}

#[test]
fn traffic_between_two_neighbours_is_ignored_rather_than_reported_as_a_failure() {
    let phone = new_phone();
    let bystander = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    pair(&phone, &mut device);

    // Two other nodes talking, overheard. This device is in neither end of it
    // and cannot open a byte, so nothing here is a confidentiality question.
    // What it is is a reporting one: every gate downstream refuses this as an
    // identity binding failure, and on a device whose only account of itself
    // is its error stream that makes ordinary neighbour traffic arrive wearing
    // the shape of an attack on it.
    let stranger = new_phone();
    let envelope = EncryptedMessage {
        group_id: GroupId::for_session(&stranger.address, &bystander.address)
            .expect("their pair's group id"),
        message_type: offline_protocol_sealed::MlsMessageType::Application,
        epoch: 1,
        ciphertext: vec![9, 9, 9],
        sender_id: stranger.address.clone(),
        timestamp_ms: 0,
    };
    let overheard = phone_sealed_frame(&stranger, &bystander.address, &envelope);

    let handled = device
        .handle(&overheard, now())
        .expect("two neighbours talking is not this device's failure");
    assert!(
        matches!(handled.events.as_slice(), [LeafEvent::Ignored { .. }]),
        "overheard neighbour traffic produced {:?}",
        handled.events
    );

    // The control: the device still has its own working session, so this is a
    // device that ignores what is not its business rather than one that has
    // stopped listening.
    let sealed = phone
        .manager
        .encrypt_for_user(&device.address().to_string(), b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device.address().to_string(), &sealed);
    let handled = device.handle(&frame, now()).expect("device opens");
    assert_eq!(
        handled.events,
        vec![LeafEvent::MessageReceived {
            peer: phone.address.clone(),
            text: "unlock".to_string(),
        }]
    );
}

/// A store that writes and reads normally and refuses every delete.
///
/// The shape a flash part takes when erasing a sector fails: the write path is
/// fine and the reclaim path is not.
#[derive(Default)]
struct UndeletableStore {
    inner: MemoryStore,
    keys: Mutex<Vec<(String, String)>>,
}

impl UndeletableStore {
    /// The key ids held under one key type, in insertion order.
    fn keys_of(&self, key_type: &str) -> Vec<String> {
        self.keys
            .lock()
            .expect("lock")
            .iter()
            .filter(|(held, _)| held == key_type)
            .map(|(_, id)| id.clone())
            .collect()
    }
}

impl LeafStore for UndeletableStore {
    fn store(&self, key_type: &str, key_id: &str, data: &[u8]) -> Result<(), StoreError> {
        self.inner.store(key_type, key_id, data)?;
        let mut keys = self.keys.lock().expect("lock");
        if !keys.iter().any(|(t, i)| t == key_type && i == key_id) {
            keys.push((key_type.to_string(), key_id.to_string()));
        }
        Ok(())
    }

    fn load(&self, key_type: &str, key_id: &str) -> Result<Option<Vec<u8>>, StoreError> {
        self.inner.load(key_type, key_id)
    }

    fn delete(&self, _key_type: &str, _key_id: &str) -> Result<(), StoreError> {
        Err(StoreError::Delete("the sector will not erase".to_string()))
    }
}

#[test]
fn a_failed_eviction_leaves_no_key_package_the_index_has_forgotten() {
    // Where the list of unspent packages lives. Mirrored from the adapter,
    // which keeps it private; it cannot collide with a package id because
    // every one of those is hex and `_` is not a hex digit.
    const KEY_PACKAGE_INDEX: &str = "__index__";
    /// What the adapter keeps, past which a mint evicts the oldest.
    const MAX_UNSPENT: usize = 4;

    let store = Arc::new(UndeletableStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);

    // Fill the window. Nothing is evicted yet, so no delete is attempted and
    // the failing erase is not in play.
    let peers: Vec<String> = (0..MAX_UNSPENT).map(|_| new_phone().address).collect();
    for peer in &peers {
        device
            .key_package_frame(peer, now())
            .expect("device mints a key package");
    }
    let held: Vec<String> = store
        .keys_of(KEY_TYPE_KEY_PACKAGE)
        .into_iter()
        .filter(|id| id != KEY_PACKAGE_INDEX)
        .collect();
    assert_eq!(
        held.len(),
        MAX_UNSPENT,
        "the window did not fill, so the eviction below would never run: {held:?}"
    );

    // One more. This one evicts, the erase fails, and the mint fails with it.
    let err = device
        .key_package_frame(&new_phone().address, now())
        .expect_err("a package was minted although its eviction could not be erased");

    // The invariant: nothing is on flash that the index has stopped naming.
    // A package the index still names but which is gone costs one slot and is
    // evicted in its turn; the reverse is private key material nothing
    // reclaims, because no sweep covers this key type and an eviction the
    // index has forgotten is never attempted again.
    let raw = store
        .load(KEY_TYPE_KEY_PACKAGE, KEY_PACKAGE_INDEX)
        .expect("load")
        .expect("minting wrote an index");
    let index: Vec<String> = serde_json::from_slice(&raw).expect("the index parses");
    let orphaned: Vec<String> = store
        .keys_of(KEY_TYPE_KEY_PACKAGE)
        .into_iter()
        .filter(|id| id != KEY_PACKAGE_INDEX)
        .filter(|id| !index.contains(id))
        .collect();
    assert!(
        orphaned.is_empty(),
        "a failed eviction left key package private material no index names: \
         {orphaned:?} (error was {err:?})"
    );
}

/// A key package is a bearer token, and a shared radio delivers it to everyone.
///
/// The frame carrying it is signed and addressed, and neither of those keeps a
/// copy out of a listener's hands. Every other gate on the Welcome that
/// listener builds passes honestly: it holds the key its own address derives
/// from, and the group it built really is the one its pair with this device
/// would build. Only the reference of the package it spends gives it away.
#[test]
fn an_overheard_key_package_cannot_be_spent_by_the_node_that_overheard_it() {
    let phone = new_phone();
    let eavesdropper = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    let advertisement = device
        .key_package_frame(&phone.address, now())
        .expect("device advertises to the phone");

    // Copied off the air and spent under the eavesdropper's own name.
    import_device_key_package(&eavesdropper, &advertisement);
    let hijack = eavesdropper
        .manager
        .create_session(&device_address)
        .expect("the eavesdropper builds a group on the copied package");
    let frame = phone_control_frame(
        &eavesdropper,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&hijack).expect("welcome")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("an overheard key package was spent by whoever copied it");
    assert!(
        matches!(err, LeafError::UnsolicitedWelcome(_)),
        "spending an overheard key package produced {err:?}"
    );
    assert!(
        !device
            .has_session(&eavesdropper.address)
            .expect("session check"),
        "the refused welcome still left a session on flash"
    );
    // The bound is applied on the way in, and a Welcome skips it. That is only
    // safe while a Welcome cannot be reached without a package of one's own.
    assert!(
        !device
            .peers()
            .expect("peer list")
            .contains(&eavesdropper.address),
        "a refused welcome still spent a slot in the peer table"
    );

    // The whole point of refusing before the join: the init key was never
    // spent, so the peer it was minted for can still use that very package. A
    // device that noticed after joining would have burned it, and the pairing
    // it was for would need a driven reset to recover.
    import_device_key_package(&phone, &advertisement);
    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone creates the session on the package it was given");
    let welcome_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome serializes")
        ),
    );
    let handled = device
        .handle(&welcome_frame, now())
        .expect("the intended peer can still join");
    assert!(
        handled.events.contains(&LeafEvent::SessionEstablished {
            peer: phone.address.clone(),
        }),
        "the overheard attempt burned the package it was refused for: {:?}",
        handled.events
    );
}

/// Having a package of one's own is not permission to spend somebody else's.
///
/// This is the case a "has this peer ever been given a package" flag would
/// wave through, and it is the one that costs the most: the neighbour is a
/// peer this device really did mint for, and the package it spends is the one
/// the phone is waiting to use.
#[test]
fn a_welcome_cannot_spend_a_key_package_minted_for_a_different_peer() {
    let phone = new_phone();
    let neighbour = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    let for_phone = device
        .key_package_frame(&phone.address, now())
        .expect("device advertises to the phone");
    // The neighbour is paired with too, so it holds a record and a package of
    // its own on this device.
    device
        .key_package_frame(&neighbour.address, now())
        .expect("device advertises to the neighbour");

    // But it builds its Welcome on the phone's package rather than its own.
    import_device_key_package(&neighbour, &for_phone);
    let hijack = neighbour
        .manager
        .create_session(&device_address)
        .expect("the neighbour builds a group on the phone's package");
    let frame = phone_control_frame(
        &neighbour,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&hijack).expect("welcome")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("a peer spent a package minted for somebody else");
    assert!(
        matches!(err, LeafError::UnsolicitedWelcome(_)),
        "spending another peer's key package produced {err:?}"
    );
    assert!(
        !device
            .has_session(&neighbour.address)
            .expect("session check"),
        "the refused welcome still left a session on flash"
    );

    // And the phone's package survived it.
    import_device_key_package(&phone, &for_phone);
    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone creates the session");
    let welcome_frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome serializes")
        ),
    );
    let handled = device
        .handle(&welcome_frame, now())
        .expect("the intended peer can still join");
    assert!(
        handled.events.contains(&LeafEvent::SessionEstablished {
            peer: phone.address.clone(),
        }),
        "the neighbour's attempt burned the phone's package: {:?}",
        handled.events
    );
}

/// A pair that stops being a pair is a room this device never chose.
///
/// The Welcome gate refuses a group that is not this pair's, and it runs once.
/// A commit changes the roster without changing the group id, and in the
/// never-committing profile every commit is the peer's to make, so the only
/// thing standing between a device and a room full of strangers is re-reading
/// the roster on the way through.
#[test]
fn a_commit_that_adds_a_third_member_is_refused() {
    let phone = new_phone();
    let outsider = new_phone();
    let store = Arc::new(MemoryStore::new());
    let mut device = device(store);
    let device_address = pair(&phone, &mut device);
    let group_id = GroupId::for_session(&phone.address, &device_address).expect("pair group id");

    let bundle = outsider
        .manager
        .get_or_create_key_package()
        .expect("the outsider has a key package");
    let (_welcome, commit) = phone
        .manager
        .add_group_member(&group_id, &outsider.address, &bundle.key_package_data)
        .expect("the peer adds a third member to the pair's own group");

    let frame = phone_sealed_frame(&phone, &device_address, &commit);
    let err = device
        .handle(&frame, now())
        .expect_err("the device followed its peer into a room it never chose");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a commit that grew the pair produced {err:?}"
    );
}

/// Drives the peer into adding a third member to the pair's own group.
///
/// The device refuses the commit and has applied it regardless, which is the
/// state the tests below are about: a member cannot skip one commit and keep
/// decrypting the next, so the refusal is a returned value and the roster it
/// objected to is what is on flash.
fn widen_the_pair(phone: &Phone, device: &mut LeafDevice, device_address: &str) {
    let outsider = new_phone();
    let group_id = GroupId::for_session(&phone.address, device_address).expect("pair group id");
    let bundle = outsider
        .manager
        .get_or_create_key_package()
        .expect("the outsider has a key package");
    let (_welcome, commit) = phone
        .manager
        .add_group_member(&group_id, &outsider.address, &bundle.key_package_data)
        .expect("the peer adds a third member to the pair's own group");

    let frame = phone_sealed_frame(phone, device_address, &commit);
    let err = device
        .handle(&frame, now())
        .expect_err("the device followed its peer into a room it never chose");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a commit that grew the pair produced {err:?}"
    );
}

/// A refusal is a value, and a device that is power cycled has only flash.
///
/// Refusing the widening commit and then sealing into the group anyway hands
/// the added member every message that follows. The commit is the only moment
/// the roster can change and the worst possible moment to be the only one that
/// checks it, because by then the answer cannot be kept anywhere.
#[test]
fn a_group_that_stopped_being_a_pair_is_not_sealed_into() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = pair(&phone, &mut device);

    device
        .seal(&phone.address, "while it was a pair", now())
        .expect("a pair seals");

    widen_the_pair(&phone, &mut device, &device_address);

    let err = device
        .seal(&phone.address, "after", now())
        .expect_err("the device sealed into a group holding a third member");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "sealing into a widened group produced {err:?}"
    );

    // The one that matters: the returned refusal is gone, and the roster on
    // flash is the device's whole account of what happened.
    drop(device);
    let mut revived = LeafDevice::resume(Arc::clone(&store), APP_ID).expect("device resumes");
    let err = revived
        .seal(&phone.address, "after a reboot", now())
        .expect_err("a rebooted device sealed into a group holding a third member");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "sealing into a widened group after a reboot produced {err:?}"
    );
}

/// The same group, in the other direction.
///
/// The message really is the peer's, so it binds honestly and arrives as
/// ordinary traffic. A device that opened it would go on actuating for its
/// owner while a member the owner never chose reads the room, which is the
/// state firmware most needs told rather than hidden.
#[test]
fn a_message_into_a_group_that_stopped_being_a_pair_is_not_opened() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    widen_the_pair(&phone, &mut device, &device_address);

    let sealed = phone
        .manager
        .encrypt_for_user(&device_address, b"unlock")
        .expect("phone seals");
    let frame = phone_sealed_frame(&phone, &device_address, &sealed);
    let err = device
        .handle(&frame, now())
        .expect_err("the device opened a message from a group holding a third member");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "opening a message from a widened group produced {err:?}"
    );
}

/// An acknowledgement is a promise to use the session.
///
/// The peer confirms on it and flushes everything it had queued. A device that
/// answered for a group it will refuse to seal into makes a promise it has
/// already decided to break, and the peer's own silence afterwards is
/// indistinguishable from a quiet link.
#[test]
fn a_probe_against_a_group_that_stopped_being_a_pair_is_not_answered() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    widen_the_pair(&phone, &mut device, &device_address);

    let probe = phone_control_frame(
        &phone,
        &device_address,
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    let err = device
        .handle(&probe, now())
        .expect_err("the device promised a session it will not seal into");
    assert!(
        matches!(err, LeafError::IdentityBinding(_)),
        "a probe against a widened group produced {err:?}"
    );
}

/// A record can sit *above* every anchor the sweep has to work from.
///
/// The adapter writes epoch records before the state entry that sequences
/// them, so a cut between the two leaves an epoch on flash that the marker,
/// the high-water record and the group's own epoch all agree is not there. A
/// sweep that only ran downward would delete every record but that one and
/// report success, which is an erasure the owner asked for that did not
/// happen, holding the secrets of the one epoch nothing else will ever name.
#[test]
fn unpairing_sweeps_an_epoch_record_a_torn_write_left_above_every_anchor() {
    let phone = new_phone();
    let store = Arc::new(TornStore::new());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);
    let device_address = pair(&phone, &mut device);

    // Two ordinary commits, so the group has left epochs behind and the
    // records below the anchor are the ones a healthy sweep already covers.
    commit_to(&phone, &mut device, &device_address);
    commit_to(&phone, &mut device, &device_address);

    // The cut: the record for the epoch being left goes down, and the state
    // entry that would have named it does not.
    store.cut(KEY_TYPE_GROUP_STATE);
    let group_id = GroupId::for_session(&phone.address, &device_address).expect("pair group id");
    let commit = phone.manager.update_keys(&group_id).expect("phone commits");
    let frame = phone_sealed_frame(&phone, &device_address, &commit);
    let err = device
        .handle(&frame, now())
        .expect_err("the state write was cut and the frame was handled anyway");
    assert!(
        matches!(err, LeafError::Storage(_)),
        "a cut state write produced {err:?}"
    );
    store.restore_power();

    let before = store.epoch_records();
    assert!(
        !before.is_empty(),
        "nothing was left on flash to sweep, so this test proves nothing"
    );

    device.unpair(&phone.address).expect("the owner unpairs");

    let after = store.epoch_records();
    assert!(
        after.is_empty(),
        "an epoch record survived the erasure its owner asked for: {after:?} \
         (before unpairing: {before:?})"
    );
}

/// An init key outliving the peer it was minted for.
///
/// The reference in the peer record is the only pointer to it, so deleting
/// that record without erasing the package first leaves private key material
/// nothing names and nothing reclaims: a package nobody spends is never
/// consumed by a join, no sweep covers this key type, and the ring only
/// evicts it once four later mints have happened. On a device that pairs
/// twice a year that is years, for a peer the owner asked it to forget.
#[test]
fn unpairing_erases_the_key_package_minted_for_the_peer() {
    // Mirrored from the adapter, which keeps it private; it cannot collide
    // with a package id because every one of those is hex and `_` is not a
    // hex digit.
    const KEY_PACKAGE_INDEX: &str = "__index__";

    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);

    // Minted and never spent, which is the state that accumulates: an
    // abandoned pairing, or one a stranger provoked.
    device
        .key_package_frame(&phone.address, now())
        .expect("device mints a key package");

    let held: Vec<String> = store
        .keys_of(KEY_TYPE_KEY_PACKAGE)
        .into_iter()
        .filter(|id| id != KEY_PACKAGE_INDEX)
        .collect();
    assert_eq!(
        held.len(),
        1,
        "no package was minted, so this test proves nothing: {held:?}"
    );

    device.unpair(&phone.address).expect("the owner unpairs");

    let after: Vec<String> = store
        .keys_of(KEY_TYPE_KEY_PACKAGE)
        .into_iter()
        .filter(|id| id != KEY_PACKAGE_INDEX)
        .collect();
    assert!(
        after.is_empty(),
        "an init key survived the peer it was minted for: {after:?}"
    );
}

/// The owner's escape hatch cannot be closed by the corruption it recovers
/// from.
///
/// Erasing the key package means reading the record that names it, and a
/// record that will not decode has no reference to give. Refusing the whole
/// call for that would leave a device unable to forget a peer at all, which
/// is a worse residue than an unreclaimed package by every measure.
#[test]
fn unpairing_survives_a_peer_record_that_will_not_decode() {
    let phone = new_phone();
    let store = Arc::new(CountingStore::default());
    let mut device = device(Arc::clone(&store) as Arc<dyn LeafStore>);

    device
        .key_package_frame(&phone.address, now())
        .expect("device mints a key package");

    // The record holding the reference is now unreadable.
    store
        .store(KEY_TYPE_PEER, &phone.address, b"not json at all")
        .expect("the store accepts the corrupt record");

    device
        .unpair(&phone.address)
        .expect("a corrupt record left the owner unable to forget a peer");

    assert!(
        !store.keys_of(KEY_TYPE_PEER).contains(&phone.address),
        "the peer record survived unpairing"
    );
    assert!(
        !device.peers().expect("peer list").contains(&phone.address),
        "the peer survived unpairing in the index"
    );
}

/// The peer is exactly who it claims and is spending exactly what it was
/// given, and the package is gone anyway.
///
/// Not an attack: the ring that bounds unspent packages evicted it when later
/// mints filled the window. Left to the join, this arrives from inside MLS as
/// a Welcome that will not decode, which reads as a broken peer and sends a
/// bench to the wire when the repair is a fresh package.
#[test]
fn a_welcome_that_spends_a_package_the_device_no_longer_holds_names_the_real_failure() {
    /// What the adapter keeps, past which a mint evicts the oldest.
    const MAX_UNSPENT: usize = 4;

    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = device.address().to_string();

    let advertisement = device
        .key_package_frame(&phone.address, now())
        .expect("device advertises to the phone");
    import_device_key_package(&phone, &advertisement);

    // Four later mints, which is exactly what it takes to push the phone's
    // package out of the ring. The phone's record still names it.
    for peer in (0..MAX_UNSPENT).map(|_| new_phone().address) {
        device
            .key_package_frame(&peer, now())
            .expect("device mints for another peer");
    }

    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone creates the session on the package it was given");
    let frame = phone_control_frame(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::WELCOME,
            serde_json::to_string(&welcome).expect("welcome serializes")
        ),
    );

    let err = device
        .handle(&frame, now())
        .expect_err("the package this welcome spends is no longer held");
    assert!(
        matches!(err, LeafError::StaleKeyPackage(_)),
        "a welcome spending an evicted package produced {err:?}"
    );
}

// ============================================================================
// FRESHNESS (issue 403)
// ============================================================================

/// A frame the phone signed days ago is refused, whatever its signature says.
#[test]
fn a_frame_older_than_the_window_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let stale_at = now() - (LEAF_CTRL_FRESHNESS_PAST_MS / 1000) - 60;
    let frame = phone_control_frame_at(
        &phone,
        &device_address,
        format!("{}{{}}", prefixes::SESSION_CONFIRM_PROBE),
        stale_at,
    );

    let refused = device.handle(&frame, now());
    assert!(
        matches!(refused, Err(LeafError::StaleControlFrame(_))),
        "a frame older than the window must be refused as stale, got {refused:?}"
    );

    // The same frame, minted now, is answered — so the refusal is about the
    // age and not about the fixture.
    let fresh = phone_control_frame_at(
        &phone,
        &device_address,
        format!("{}{{}}", prefixes::SESSION_CONFIRM_PROBE),
        now(),
    );
    assert!(device.handle(&fresh, now()).is_ok());
}

/// And one stamped well ahead of the device's clock, which is what a *local*
/// time-source fault looks like from the inside.
#[test]
fn a_frame_from_the_future_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let ahead = now() + (CTRL_FRESHNESS_FUTURE_MS / 1000) + 60;
    let frame = phone_control_frame_at(
        &phone,
        &device_address,
        format!("{}{{}}", prefixes::SESSION_CONFIRM_PROBE),
        ahead,
    );

    assert!(matches!(
        device.handle(&frame, now()),
        Err(LeafError::StaleControlFrame(_))
    ));

    // Modest skew is tolerated, or two honest devices refuse each other over a
    // few seconds of clock disagreement.
    let slight = phone_control_frame_at(
        &phone,
        &device_address,
        format!("{}{{}}", prefixes::SESSION_CONFIRM_PROBE),
        now() + 30,
    );
    assert!(device.handle(&slight, now()).is_ok());
}

/// A leaf verifies the freshness-bound payload and nothing else.
///
/// The older payload leaves the timestamp outside the signature, so accepting
/// it would mean accepting a stamp an attacker rewrites — the window and the
/// replay mark would both be reading attacker-chosen numbers. A phone accepts
/// it because it must talk to installs that predate it; a leaf has no such
/// peer, so here it is simply a refusal.
#[test]
fn a_frame_under_the_older_payload_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let mut frame = Message::new(
        UserId::new(&phone.address).expect("phone address"),
        UserId::new(&device_address).expect("device address"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        format!("{}{{}}", prefixes::SESSION_CONFIRM_PROBE),
    );
    frame.timestamp = offline_protocol_core::Timestamp::from_millis((now() as i64) * 1000);
    // The v1 payload: every field but the stamp.
    let payload = offline_protocol_sealed::control_signing_payload(&frame).expect("v1 payload");
    let signature = phone.manager.sign_data(&payload).expect("phone signs");
    let public = phone
        .manager
        .get_identity_public_key()
        .expect("phone public key");
    frame.metadata.insert(
        offline_protocol_sealed::CTRL_SIG_META_KEY.to_string(),
        BASE64.encode(&signature),
    );
    frame.metadata.insert(
        offline_protocol_sealed::CTRL_PK_META_KEY.to_string(),
        BASE64.encode(&public),
    );

    let refused = device.handle(&frame, now());
    assert!(
        matches!(refused, Err(LeafError::ControlFrameRefused(_))),
        "a frame under the older payload must not verify here, got {refused:?}"
    );
}

/// The property a ring of remembered ids could never have: a reset *older*
/// than the last one acted on is refused, even though this device has no
/// memory of ever seeing it.
///
/// That is the difference between denying a repeat and denying a replay. An
/// attacker holding several captures cannot pick the one that predates the
/// device's memory and spend it.
#[test]
fn a_reset_older_than_the_last_one_acted_on_is_refused() {
    let phone = new_phone();
    let mut device = device(Arc::new(MemoryStore::new()));
    let device_address = pair(&phone, &mut device);

    let reset_frame_at = |at: u64| {
        let package = phone
            .manager
            .take_push_key_package(&device_address)
            .expect("phone mints a package");
        let payload = KeyPackagePayload {
            user_id: phone.address.clone(),
            key_package_data: package.bundle.key_package_data,
            remaining_lifetime_ms: 0,
            timestamp_ms: 0,
            session_reset: true,
            wire_versions: vec![],
            env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
            rich_versions: vec![],
            data_versions: vec![],
            ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
            svc_versions: Vec::new(),
            ack_versions: Vec::new(),
            nostr_pubkey: None,
        };
        phone_control_frame_at(
            &phone,
            &device_address,
            format!(
                "{}{}",
                prefixes::KEY_PACKAGE,
                serde_json::to_string(&payload).expect("payload")
            ),
            at,
        )
    };

    // An older capture the device never saw, and the current reset. Both are
    // inside the window, so freshness alone admits either.
    let older = reset_frame_at(now() - 3600);
    let current = reset_frame_at(now());

    let acted = device.handle(&current, now()).expect("device resets");
    assert!(acted.events.contains(&LeafEvent::SessionReset {
        peer: phone.address.clone(),
    }));

    let replayed = device
        .handle(&older, now())
        .expect("the older one is handled");
    assert!(
        !replayed.events.contains(&LeafEvent::SessionReset {
            peer: phone.address.clone(),
        }),
        "a reset predating the last one acted on must not be spendable: {:?}",
        replayed.events
    );
}

/// The mark is on flash, not in RAM, or a power cut hands the attacker the
/// replay back.
#[test]
fn a_spent_reset_stays_spent_across_a_power_cycle() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(store.clone());
    let device_address = pair(&phone, &mut device);

    let package = phone
        .manager
        .take_push_key_package(&device_address)
        .expect("phone mints a package");
    let payload = KeyPackagePayload {
        user_id: phone.address.clone(),
        key_package_data: package.bundle.key_package_data,
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: true,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    let reset_frame = phone_control_frame_at(
        &phone,
        &device_address,
        format!(
            "{}{}",
            prefixes::KEY_PACKAGE,
            serde_json::to_string(&payload).expect("payload")
        ),
        now(),
    );

    let acted = device.handle(&reset_frame, now()).expect("device resets");
    assert!(acted.events.contains(&LeafEvent::SessionReset {
        peer: phone.address.clone(),
    }));

    // The power cut: everything in RAM is gone, the store is what is left.
    drop(device);
    let mut rebooted = crate::device(store);

    let replayed = rebooted
        .handle(&reset_frame, now())
        .expect("the replay is handled");
    assert!(
        !replayed.events.contains(&LeafEvent::SessionReset {
            peer: phone.address.clone(),
        }),
        "a reboot must not make a spent reset spendable again: {:?}",
        replayed.events
    );
}

/// A phone signs a control frame under the older payload, which leaves the
/// frame's timestamp outside the signature.
///
/// This is what an engine produces for a peer whose `ctrl_versions` it has
/// never seen, which is every peer before that peer's key package has reached
/// it.
fn sign_as_undated(phone: &Phone, message: &mut Message) {
    let payload =
        offline_protocol_sealed::control_signing_payload(message).expect("canonical payload");
    let signature = phone.manager.sign_data(&payload).expect("phone signs");
    let public = phone
        .manager
        .get_identity_public_key()
        .expect("phone public key");
    message.metadata.insert(
        offline_protocol_sealed::CTRL_SIG_META_KEY.to_string(),
        BASE64.encode(&signature),
    );
    message.metadata.insert(
        offline_protocol_sealed::CTRL_PK_META_KEY.to_string(),
        BASE64.encode(&public),
    );
}

/// [`phone_control_frame`], signed under the older payload.
fn phone_undated_frame(phone: &Phone, to: &str, content: String) -> Message {
    let mut message = Message::new(
        UserId::new(&phone.address).expect("phone address is a user id"),
        UserId::new(to).expect("device address is a user id"),
        offline_protocol_core::AppId::new(APP_ID).expect("app id"),
        content,
    );
    message.priority = MessagePriority::High;
    message.timestamp = offline_protocol_core::Timestamp::from_millis((now() as i64) * 1000);
    sign_as_undated(phone, &mut message);
    message
}

/// The frame that begins a phone-initiated pairing is accepted.
///
/// A sender builds the freshness-bound payload for a recipient that has
/// advertised it and the older one for a recipient that has not, and
/// capabilities travel **in a key package**. So the first key package to a peer
/// never met is signed under the older payload however new the sender is: it is
/// inherent to the negotiation, not a legacy peer.
///
/// A device that refused it would be a device no phone could ever start a
/// pairing with. It would never learn the phone exists, and the phone's retry
/// ladder would deliver the same refusal ten times over, reaching firmware as a
/// run of signature failures indistinguishable from an attack.
#[test]
fn a_key_package_that_states_no_time_is_admitted_because_first_contact_has_none() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = device.address().to_string();

    let frame = phone_undated_frame(&phone, &device_address, advertisement_body(&phone.address));
    let handled = device
        .handle(&frame, now())
        .expect("a device that refuses this can never be paired with by a phone");

    assert!(
        handled.events.iter().any(
            |event| matches!(event, LeafEvent::PeerAdvertised { peer } if *peer == phone.address)
        ),
        "the device did not record the phone that just introduced itself: {:?}",
        handled.events
    );
    assert_eq!(
        spoken(&handled).len(),
        1,
        "the device must answer first contact with a key package of its own"
    );
    assert!(
        spoken(&handled)[0]
            .content
            .starts_with(prefixes::KEY_PACKAGE),
        "the answer to a key package is a key package"
    );
}

/// A reset carried on a frame that states no time is refused its teardown.
///
/// This is the whole cost of admitting the older payload, and it is the reason
/// admitting it is safe. The high-water mark that makes one captured reset
/// worth one teardown compares a timestamp; under this payload that timestamp
/// sits outside the signature, so anyone in radio range could rewrite it. Set
/// once to the far future, it would deny the pair every later reset, which is a
/// durable denial of healing rather than a bounded replay.
///
/// The rest of the frame is still acted on, because capability advertisement is
/// unauthenticated hint data everywhere in this protocol.
#[test]
fn a_session_reset_that_states_no_time_is_refused_its_teardown() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = pair(&phone, &mut device);

    assert!(
        device.has_session(&phone.address).expect("session"),
        "the pair has to be up for a teardown to be worth refusing"
    );

    let payload = KeyPackagePayload {
        user_id: phone.address.clone(),
        key_package_data: vec![7],
        remaining_lifetime_ms: 0,
        timestamp_ms: 0,
        session_reset: true,
        wire_versions: vec![],
        env_versions: vec![MLS_ENVELOPE_COMPACT_V1],
        rich_versions: vec![],
        data_versions: vec![],
        ctrl_versions: vec![offline_protocol_sealed::CTRL_SIGN_V2],
        svc_versions: Vec::new(),
        ack_versions: Vec::new(),
        nostr_pubkey: None,
    };
    let content = format!(
        "{}{}",
        prefixes::KEY_PACKAGE,
        serde_json::to_string(&payload).expect("payload")
    );
    let frame = phone_undated_frame(&phone, &device_address, content);

    let handled = device.handle(&frame, now()).expect("the frame is admitted");

    assert!(
        !handled
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::SessionReset { .. })),
        "a reset on a frame whose age cannot be judged tore the session down: {:?}",
        handled.events
    );
    assert!(
        device.has_session(&phone.address).expect("session"),
        "the session is gone, so the teardown happened after all"
    );
    assert!(
        handled
            .events
            .iter()
            .any(|event| matches!(event, LeafEvent::PeerAdvertised { .. })),
        "the frame's capability half must still be acted on: {:?}",
        handled.events
    );
}

/// A Welcome under the older payload is refused.
///
/// The exception is for key packages alone, and nothing else needs it: a
/// Welcome can only follow this device's own key package reaching the peer, and
/// that is the frame which teaches the peer to sign the freshness-bound
/// payload. Admitting one here would put a frame whose age cannot be judged in
/// front of a join.
#[test]
fn a_welcome_that_states_no_time_is_refused() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = device.address().to_string();

    // The device advertises first, so the phone holds a real key package and
    // the Welcome below is refused for its payload rather than for its body.
    let advertisement = device
        .key_package_frame(&phone.address, now())
        .expect("device mints");
    import_device_key_package(&phone, &advertisement);
    let welcome = phone
        .manager
        .create_session(&device_address)
        .expect("phone creates the session");
    let content = format!(
        "{}{}",
        prefixes::WELCOME,
        serde_json::to_string(&welcome).expect("welcome body")
    );

    let frame = phone_undated_frame(&phone, &device_address, content);
    let refusal = device.handle(&frame, now());

    assert!(
        matches!(refusal, Err(LeafError::ControlFrameRefused(_))),
        "a welcome that states no time was admitted: {refusal:?}"
    );
    assert!(
        !device.has_session(&phone.address).expect("session"),
        "the device joined from a welcome it should have refused"
    );
}

/// A probe under the older payload is refused, for the same reason.
#[test]
fn a_probe_that_states_no_time_is_refused() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = pair(&phone, &mut device);

    let frame = phone_undated_frame(
        &phone,
        &device_address,
        prefixes::SESSION_CONFIRM_PROBE.to_string(),
    );
    let refusal = device.handle(&frame, now());

    assert!(
        matches!(refusal, Err(LeafError::ControlFrameRefused(_))),
        "a probe that states no time was admitted: {refusal:?}"
    );
}

/// The freshness-bound payload is still preferred, and still judged for age.
///
/// The fallback must not become a way around the window: a frame that carries
/// a valid freshness-bound signature is judged under it, and an old one is
/// refused rather than quietly retried under the payload that does not care.
#[test]
fn a_stale_key_package_is_still_refused_rather_than_retried_undated() {
    let phone = new_phone();
    let store: Arc<dyn LeafStore> = Arc::new(MemoryStore::new());
    let mut device = device(Arc::clone(&store));
    let device_address = device.address().to_string();

    let stale_at = now() - (LEAF_CTRL_FRESHNESS_PAST_MS / 1000) - 60;
    let frame = phone_control_frame_at(
        &phone,
        &device_address,
        advertisement_body(&phone.address),
        stale_at,
    );

    let refusal = device.handle(&frame, now());

    assert!(
        matches!(refusal, Err(LeafError::StaleControlFrame(_))),
        "a stale frame under the freshness-bound payload must stay refused for \
         its age, not fall through to the payload that states none: {refusal:?}"
    );
}