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
//! Type definitions, constants, and shared state for the protocol engine.
use crate;
use crate;
use crateError;
use ;
use ;
use TransportType;
use ;
use ;
use ;
use Instant;
use warn;
/// A carrier that speaks the gateway contract, and can therefore answer about
/// a third party's reachability.
///
/// Two of the five transports qualify, and the type exists so the other three
/// cannot be passed where a gateway answer is expected. That is not a
/// theoretical tidiness: every effect of a presence answer is carrier-scoped,
/// so a wrong carrier records a fact against a transport that never claimed
/// it and pins an un-park flush to a transport that never proved anything,
/// neither of which fails loudly.
///
/// - **BLE and Wi-Fi Direct** are zone carriers. A neighbour being in range
/// is a fact about this device's own link, not a claim about a third party,
/// and it arrives through discovery rather than through a verb.
/// - **Nostr** structurally cannot answer: a broadcast relay reports no
/// per-recipient delivery, so it is a carrier and never a gateway. See
/// [ADR 0017](../../../docs/adr/0017-nostr-is-a-carrier-not-a-gateway.md).
/// This is a permanent gap, recorded here in the type so it stops being
/// rediscovered as a bug.
/// Retry interval for persisting session confirmation after a transient storage error.
pub const CONFIRMATION_RETRY_INTERVAL_SECS: i64 = 5;
/// Probe interval for reconciling pending sessions after restart.
pub const CONFIRMATION_PROBE_INTERVAL_SECS: i64 = 5;
/// Minimum interval between 1:1 session re-keys for the same peer, triggered by
/// an epoch-desync decrypt failure. A re-key is a full teardown + key-package
/// re-exchange, so it is rate-limited well above the confirmation-probe cadence:
/// one legit desync heals in a single round-trip, and this bounds a peer
/// replaying stale-epoch ciphertext (or an injected wrong-epoch frame) to at
/// most one re-key per this window rather than a storm. The floor is enforced
/// unconditionally — a successful decrypt on the healed session does NOT reset
/// it — so an attacker cannot defeat it by interleaving replays with legit
/// traffic (see `schedule_session_rekey`).
pub const REKEY_INTERVAL_SECS: i64 = 30;
/// Minimum interval between two pushes of our key package to the same peer
/// while no session with that peer exists.
///
/// The first push is fire-once over a carrier that may lose it without saying
/// so (a superseded peer stream drops its late frames, `docs/spec/stream-framing.md`), so a
/// push that produced no session is re-armed. The floor is what keeps the
/// re-arm from becoming a key-package storm: discovery fires on every inbound
/// body, and a peer that never answers (an old SDK, encryption opted out) gets
/// one advertisement per window rather than one per frame. The window doubles
/// with each repeat up to [`KEY_PACKAGE_RESEND_CAP_SECS`], so that peer is not
/// sent a key package every 30 seconds for as long as it stays in range.
pub const KEY_PACKAGE_RESEND_INTERVAL_SECS: u64 = 30;
/// Ceiling on the doubling key-package resend window, matching
/// [`WELCOME_UNREACHABLE_RETRY_CAP_SECS`].
pub const KEY_PACKAGE_RESEND_CAP_SECS: u64 = 600;
// The wait doubles at most five times (`<< min(5)`, which also keeps the
// shift from wrapping the wait to zero); this keeps the cap reachable.
const _: = assert!;
const _: = assert!;
/// Seconds to wait before repeating a key-package push that has already been
/// repeated `repeats` times: the interval, doubled per repeat, capped.
pub
/// Number of welcome retry records processed per tick.
pub const WELCOME_RETRY_BATCH_SIZE: usize = 20;
/// Hard TTL for outbound welcome lifecycle records.
pub const WELCOME_LIFECYCLE_TTL_SECS: i64 = 300;
/// Jitter ratio applied to welcome retry backoff delays.
pub const WELCOME_RETRY_JITTER_RATIO: f64 = 0.2;
/// Timeout waiting for explicit internet send confirmation for welcome.
pub const WELCOME_INTERNET_CONFIRM_TIMEOUT_SECS: i64 = 10;
/// Timeout waiting for a mesh (BLE / WiFi-Direct) welcome to be confirmed by
/// the peer proving the session (probe / ack / welcome / decrypt). A mesh
/// `send()` returning Ok only means the local stack accepted the bytes, not
/// that the multi-fragment Welcome reassembled on the peer — so the lifecycle
/// stays non-terminal and the retry queue re-sends the whole Welcome after this
/// window, recovering from a lost fragment. Slightly longer than the internet
/// timeout to allow a slow multi-fragment Welcome to assemble plus the probe
/// round-trip before paying to re-fragment and re-send it.
pub const WELCOME_MESH_CONFIRM_TIMEOUT_SECS: i64 = 15;
/// Retry cadence for a Welcome that has no transport carrier at all (the peer is
/// simply unreachable right now). A send is guaranteed to fail with no carrier,
/// so we do NOT burn the speculative send/transition/event churn on it every
/// retry tick — we park it and re-check on this slow interval instead. The
/// primary recovery is event-driven (`on_neighbor_discovered` → re-arm fires the
/// instant a carrier surfaces the peer); this poll is only a safety net for a
/// carrier returning without a fresh discovery event, so it is deliberately far
/// slower than the data-plane retry interval to keep an offline device quiet.
/// Also the base interval for the plain-DM unreachable reachability probe
/// (`handle_recipient_unreachable_for_message`), which shares this
/// escalation.
pub const WELCOME_NO_CARRIER_RETRY_SECS: i64 = 15;
/// Cap for the escalating retry interval of a welcome repeatedly parked
/// `PeerUnreachable`, on every carrier (see
/// `apply_recipient_unreachable_failure`). Each consecutive unreachable park
/// doubles the interval from [`WELCOME_NO_CARRIER_RETRY_SECS`] up to this
/// cap: DORS may keep selecting the internet path for the timed retry, and
/// every such round trips another relay `DeliveryError` with the attempt
/// refunded — without escalation that is an unbounded 15s resend loop into
/// the relay for as long as the peer stays offline. At the cap the steady
/// state matches the presence-rescue cadence (one send per 10 min), which is
/// cheap and self-resolving. Shared by the plain-DM unreachable probe
/// (`handle_recipient_unreachable_for_message`, per-peer
/// `dm_unreachable_parks` counter) for the same reason — and there the
/// escalation carries the whole bound, since that probe runs on every carrier
/// (see `park_unreachable_dm`), including internet-only devices.
pub const WELCOME_UNREACHABLE_RETRY_CAP_SECS: i64 = 600;
/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in. How
/// many escalating timed probes a plain DM to an unreachable peer gets before
/// it goes edge-driven (stops being timed-probed and rests in the outbox until
/// the peer next proves reachable). One probe (plus the original send) gives a
/// brief blip tolerance; beyond that, recovery is the reachability edge — which
/// in an opted-in deployment is reliable (peers interact / advertise presence
/// on return), so more blind probes only lengthen the transient after a mass
/// disconnect. Default-off deployments never consult this (they probe forever
/// at the documented 15s->600s cap).
pub const DM_UNREACHABLE_PROBE_LIMIT: u32 = 1;
/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in. On the
/// startup/reconnect re-drive, a still-undelivered outbox message first sent
/// longer ago than this is left edge-driven rather than re-driven, so a restart
/// does not re-ramp a durably-failing backlog. Default-off deployments never
/// consult this.
pub const OUTBOX_DURABLE_UNREACHABLE_AGE_SECS: i64 = 300;
/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in.
/// Sustained rate (per second) and burst budget for the RETRY/PROBE resend path
/// (`process_retry_queue`). Set below the reference relay's per-connection limit
/// (10/s sustained, 30 burst) so resends to a fleet of unreachable peers can
/// never burst the connection into a rate-limit disconnect. Only resends are
/// bounded; first-attempt sends, ACKs, control frames and handshakes are never
/// throttled.
pub const RETRY_DRAIN_RATE_PER_SEC: f64 = 8.0;
pub const RETRY_DRAIN_BURST: f64 = 24.0;
/// Age limit for a welcome lifecycle to keep its peer on the presence
/// watchlist (`welcome_pending_peers`). Without it the watch set only ever
/// grows: every offline presence answer re-parks the record and pushes its
/// `expires_at`, so a permanently-dead peer (abandoned install) is watched —
/// and its parked lifecycle persisted — forever, and each such peer occupies
/// rotation slots that delay presence rescue for live peers. Once unwatched,
/// offline answers stop, `expires_at` stops being pushed, and the record
/// ages out through normal expiry; recovery degrades to peer-initiated
/// contact or mesh discovery, both of which rebuild the lifecycle.
pub const WELCOME_WATCHLIST_MAX_AGE_SECS: i64 = 14 * 24 * 60 * 60;
/// Backoff base for presence-driven welcome rescue. The first rescue for a
/// peer is immediate; each subsequent rescue that still fails to prove the
/// session doubles the wait (40s, 80s, 160s, ...) up to
/// [`WELCOME_PRESENCE_RESCUE_MAX_SECS`]. Bounds the resend loop when a peer
/// is provably online but can never confirm (stale key package after a
/// reinstall, incompatible peer version) — without it the platform's 20s
/// presence watch would re-send the multi-frame MLS welcome forever.
pub const WELCOME_PRESENCE_RESCUE_BASE_SECS: i64 = 40;
/// Cap for the presence-rescue backoff (10 minutes). Deliberately not a
/// terminal state: a peer that stays online but never confirms keeps getting
/// one rescue per cap interval, forever. That steady state is cheap (one
/// multi-frame welcome per 10 min per such peer) and self-resolving — the
/// lifecycle disappears the moment the session confirms — so a give-up
/// threshold would only add a way to strand a recoverable session.
pub const WELCOME_PRESENCE_RESCUE_MAX_SECS: i64 = 600;
/// Well-known prefix for transport send-failure reasons meaning "the carrier
/// is up but this recipient is unreachable on it" (e.g. the internet relay
/// answered `DeliveryError` for an offline peer). Classified in
/// `on_transport_send_failed` as authoritative proof the frame was dropped:
/// instead of burning a retry attempt, a welcome refunds it and parks on an
/// escalating reachability probe (`apply_recipient_unreachable_failure`), and
/// a plain DM parks the same way (`park_unreachable_dm`). The escalation, not
/// a carrier guard, is what keeps those probes from becoming a resend loop
/// into the relay.
///
/// Cross-layer contract: the React Native platform bridges
/// (`InternetManager.kt` / `InternetManager.swift`) hardcode this literal when
/// calling `internet_send_failed_with_reason` — keep them in sync.
pub const SEND_FAIL_REASON_RECIPIENT_UNREACHABLE: &str = "recipient_unreachable";
/// The relay accepted a frame for a recipient with no live socket and handed
/// it to a push notification (`MessageSent { pushed: true }`). Not a failure:
/// the push may deliver it. What it does establish is that the recipient is
/// not on the relay, and that the push is the only thing carrying this frame:
/// a relay whose mailbox also holds a copy says so with `stored: true`, which
/// the bridges report as [`SEND_FAIL_REASON_RELAY_PUSHED_STORED`] instead.
///
/// Deliberately its own token rather than a `recipient_unreachable` tail.
/// That prefix fast-fails connection requests and moves Welcomes to `Failed`,
/// both wrong for a frame that may have arrived. This token parks plain DMs
/// only (`park_relay_pushed_dm`), and connection requests and Welcomes stay
/// on their ordinary path.
///
/// Cross-layer contract: the React Native platform bridges
/// (`InternetManager.kt` / `InternetManager.swift`) and the Python relay
/// client (`internet_manager.py`) pass this exact literal to
/// `internet_send_failed_with_reason`; pinned on the React Native side by
/// `react_native_relay_parks_a_pushed_message_sent` and on the Python side by
/// `TestMessageSentPushed`. That call must not also score the report as a send
/// failure; see `OfflineProtocol::send_report_is_carrier_failure`.
pub const SEND_FAIL_REASON_RELAY_PUSHED: &str = "relay_pushed";
/// The relay's mailbox holds this frame for the recipient's next connection
/// (`DeliveryError { stored: true }`, on a relay advertising `mailbox_v1`).
///
/// The socket write still missed, so this is the `recipient_unreachable`
/// verdict in every respect but one: the frame is not lost, and the relay
/// re-sends it the moment the recipient connects. A plain DM is therefore
/// parked *edge-driven* — no escalating reachability probe — because a probe
/// would only rewrite the copy the relay already holds. That is what the
/// relay's own contract asks for ("do not retry faster on its account"), and
/// what keeps a fleet whose peers are merely asleep from paying relay traffic
/// for a redelivery the relay is already committed to. Recovery without the
/// probe is the reachability edge, and the relay's drain either way.
///
/// Everything that is not a parkable plain DM is deliberately unchanged: the
/// token is normalized back to [`SEND_FAIL_REASON_RECIPIENT_UNREACHABLE`] in
/// `on_transport_send_failed_via`, so connection requests still fast-fail and
/// Welcomes still park on their own lifecycle. Both carry their own proof of
/// arrival, and a held copy is not a reason to stop waiting for it.
///
/// Cross-layer contract: the React Native platform bridges
/// (`InternetManager.kt` / `InternetManager.swift`) and the Python relay
/// client (`internet_manager.py`) pass this exact literal, and only for the
/// one id the relay named — `stored` is a statement about a single message,
/// never about the recipient's other in-flight frames. Pinned on the React
/// Native side by `react_native_relay_parks_a_stored_delivery_error`.
pub const SEND_FAIL_REASON_RELAY_STORED: &str = "relay_stored";
/// [`SEND_FAIL_REASON_RELAY_PUSHED`] for a frame the mailbox also holds
/// (`MessageSent { pushed: true, stored: true }`).
///
/// Parks exactly as `relay_pushed` does — plain DMs only, no
/// `MessageUndeliverable`, kept out of the carrier's failure accounting —
/// except that the park schedules no reachability probe, for the reason
/// [`SEND_FAIL_REASON_RELAY_STORED`] gives.
///
/// Two tokens rather than one token and a flag because the two origins differ
/// for everything that is *not* a plain DM: a pushed frame must not fast-fail
/// a connection request, and a missed one must. Collapsing them would trade
/// that distinction for one fewer string.
pub const SEND_FAIL_REASON_RELAY_PUSHED_STORED: &str = "relay_pushed_stored";
/// Fallback token for a send failure that classifies as nothing more specific.
pub const SEND_FAIL_REASON_TRANSPORT: &str = "transport_send_failed";
/// A Welcome was written to a carrier that never confirmed it.
pub const SEND_FAIL_REASON_CONFIRM_TIMEOUT: &str = "send_confirmation_timed_out";
/// Every token [`classify_transport_send_error`] and
/// [`send_failure_token`] can produce.
///
/// Membership is what makes classification idempotent: a value already drawn
/// from this list re-classifies to itself, so a record written by one producer
/// and re-read by the other is not degraded to the fallback. Keep it in sync
/// with the two functions — the round-trip test
/// `every_send_failure_token_classifies_to_itself` fails otherwise.
pub const SEND_FAIL_REASON_TOKENS: & = &;
/// Maps a platform-supplied or previously-stored send-failure string onto a
/// fixed local vocabulary.
///
/// # Why the string cannot be passed through
///
/// The bridges build this string from the relay's `DeliveryError.reason`
/// (`"recipient_unreachable: <relay text>"` — the shape is a cross-layer
/// contract, see [`SEND_FAIL_REASON_RECIPIENT_UNREACHABLE`]), and the Nostr
/// bridge from a relay's `OK` rejection text. Both tails are remote-chosen,
/// unbounded, and not ours. They reach `MessageUndeliverable.reason`,
/// `ConnectionRequestUndeliverable.reason` and — through
/// `WelcomeLifecycleRecord::last_transport_error` —
/// `WelcomeSendFailed.transport_error`, every one of which the telemetry
/// scrubber ships verbatim beside a `recipient`/`peer_id` it *hashes*. An
/// identifier in the tail therefore undoes the hashing in the same record, and
/// even the honest relay writes one: its own wording renders the peer it
/// concerns.
///
/// # Why the prefix survives
///
/// The `recipient_unreachable` token is not decoration — core prefix-matches it
/// to fast-fail connection requests and to park plain DMs, and the bridges
/// hardcode it. So the classification *is* the bare token: everything the
/// protocol reads is kept, and only the prose tail is dropped.
///
/// Matching is prefix-based for that one token (the bridges append to it) and
/// exact otherwise, with a closed fallback — a bridge or relay rewording
/// degrades to [`SEND_FAIL_REASON_TRANSPORT`], never back to shipping its text.
/// The `&'static str` return is load-bearing the same way
/// [`GroupErrorPayload::classify_reason`] and `MlsError::privacy_safe_reason`
/// are: it makes interpolating the input unrepresentable rather than merely
/// discouraged.
///
/// Idempotent by construction, which matters twice: a record persisted before
/// this existed is classified when it is *read* (the stored string may be raw
/// relay prose), and a record written after it is classified again on the way
/// out without changing.
pub
/// The pending-ACK table was full, so the frame was held back instead of
/// transmitted. Not a transport fault: the retry queue sends it as soon as an
/// acknowledgement frees a slot. A link carrying less than the app offers
/// produces this steadily, and it is the signal to slow down.
pub const SEND_DEFER_REASON_ACK_CAPACITY: &str = "ack_capacity";
/// The peer already had [`PEER_SEND_WINDOW`] frames over a mesh link awaiting
/// its acknowledgement, so the frame waits in the outbox and goes out, oldest
/// first, as acknowledgements come back. Not a fault: it is what a link
/// carrying less than the app offers looks like.
pub const SEND_DEFER_REASON_PEER_WINDOW: &str = "peer_window";
/// How many frames this device keeps in flight to one peer over a mesh link
/// (Bluetooth LE, Wi-Fi Direct) before it holds the next one back.
///
/// Without a window the sender handed the carrier every new frame, every
/// resend and an acknowledgement per received frame, into one unbounded queue,
/// on a timer that starts at enqueue. In the 2026-10-19 volume test (run 4)
/// the Android side's indication path carried 12 to 16 frames a second against
/// 15 offered: the acknowledgement round trip passed the timeout, every resend
/// cost the receiver another acknowledgement on the saturated path, that
/// path's rate halved, and both phones retried 50,000 times and evicted 6,000
/// messages as "Outbox capacity exceeded". A window bounds the queue, and with
/// it the round trip, the resends and the receiver's ratchet gap, at any link
/// rate. It costs no throughput while it exceeds what the link carries in one
/// unloaded round trip: about six messages on that link, counting the
/// receiver's acknowledgement coalescing (`ACK_COALESCE_WINDOW`) and a
/// processing tick on each side. Sixteen leaves margin, and keeps the
/// round trip under about three seconds there, well inside the timeout.
///
/// Only the mesh carriers: a relay mailbox is store-and-forward, and holding
/// a message back from it would strand it on a device the user may close.
pub const PEER_SEND_WINDOW: usize = 16;
// Every in-window frame can be re-sealed on each of its attempts, and the
// re-seal budget must never trip under the window: past it resends go out
// verbatim, and a verbatim copy more than the out-of-order tolerance behind
// the receiver never decrypts (run 4: 3,308 such failures).
const _: = assert!;
/// The smallest forward window any receiver of a 1:1 session has: a phone's
/// OpenMLS group (configured) or a leaf's mls-rs one (fixed by mls-rs, and
/// smaller). The re-seal budget is a fraction of this, not of the phone's
/// window: derived from the phone's 8192, it let a sender burn 2,048
/// generations past a leaf that can fast-forward over 1,024.
pub const RECEIVER_FORWARD_WINDOW_FLOOR: u64 = ;
/// How many frames a sender may seal for one peer past the last one that peer
/// acknowledged before resends stop being re-sealed and go out verbatim.
///
/// A receiver cannot decrypt a frame more than its forward window past the
/// newest it has decrypted. A quarter of the smallest window any receiver has
/// ([`RECEIVER_FORWARD_WINDOW_FLOOR`]) leaves the rest to new messages, which
/// still seal. The per-peer window keeps unacknowledged seals growing only by
/// resends of at most [`PEER_SEND_WINDOW`] frames, so the budget trips only on
/// a link that has carried no acknowledgement for a whole retry ladder; the
/// compile-time assertion above keeps it above that ladder.
pub const RESEAL_GAP_BUDGET: u64 = RECEIVER_FORWARD_WINDOW_FLOOR / 4;
/// Past [`RESEAL_GAP_BUDGET`], a resend whose bytes the receiver can no
/// longer decrypt is still re-sealed, until the gap reaches this.
///
/// A verbatim copy sealed more than the out-of-order tolerance before the
/// newest frame this device sealed is refused by a receiver that has
/// decrypted anything since, and refused without an acknowledgement on a
/// mesh link, so it was resent until its ladder ran out: in run 4 of the
/// 2026-10-19 volume test, 525 such messages produced 3,308 decrypt
/// failures and were never delivered. Re-sealing one spends a generation,
/// which is what the budget rations, so the exception stops at half the
/// smallest forward window ([`RECEIVER_FORWARD_WINDOW_FLOOR`]): the receiver
/// going deaf is the failure the budget exists for, and a wasted resend is
/// not.
pub const RESEAL_HARD_LIMIT: u64 = RECEIVER_FORWARD_WINDOW_FLOOR / 2;
/// The longest an acknowledgement timeout is postponed for a frame that is
/// still waiting in a local transport queue, measured from the attempt.
///
/// Bounded so a queue that never drains (a link that died without telling
/// the transport) still reaches the retry ladder, and through it the other
/// carriers and the mesh, within a minute.
pub const QUEUED_ACK_GRACE_MAX: Duration = from_secs;
/// Classifies a locally raised send failure for an event field.
///
/// The sibling of [`classify_transport_send_error`] for errors this device
/// produced rather than received. It exists for the same reason: the transport
/// layer renders the counterparty into its own message —
/// `PeerNotReachable("no mesh transport holds a link to {peer_id}…")`, and the
/// same in the BLE and Wi-Fi Direct backends — so `format!("{}", err)` on a
/// routine send failure ships the peer's address to a telemetry sink. On
/// `MessageDeferred` that was the *only* identity in the record, since the
/// event carried no field for the scrubber to hash.
///
/// The match over [`crate::Error`] is exhaustive with no `_` arm: it lives in
/// the defining crate, so a new variant fails to compile here and forces the
/// privacy decision where the variant is written. The transport arm delegates
/// to `offline_protocol_transport::Error::code`, which is that crate's own
/// exhaustive, documented-stable classifier — its doc names telemetry
/// classification as the intended use. Matching its output needs a fallback
/// arm (a foreign `#[non_exhaustive]` enum can grow a variant), and that
/// fallback is closed: a new transport variant degrades to
/// [`SEND_FAIL_REASON_TRANSPORT`], never to its rendered text.
pub
/// Minimum interval between session reconciliation scans (list_sessions I/O).
/// Keeps the expensive Keychain/Keystore I/O out of the hot path so that
/// sendMessage() is not blocked by Mutex contention on every process tick.
pub const RECONCILIATION_THROTTLE_MS: u64 = 2_000;
/// Lamport clock ticks between storage persistence writes. Avoids a
/// Keychain/Keystore write on every sent and received message. On crash
/// recovery, at most this many ticks are lost, which is safe — the clock
/// is only used for causal ordering and the gap is absorbed on the next
/// merge with any peer.
pub const LAMPORT_PERSIST_INTERVAL: u64 = 64;
/// Most seen ids one `DedupSeenRecord` carries. Matches the default
/// `max_tracked_messages`; a larger configured tracker persists its newest
/// ids only, which are the ones a replay is most likely to repeat.
pub const MAX_PERSISTED_DEDUP_IDS: usize = 5000;
/// Seen-set changes that force a write before the time cadence elapses. A
/// burst of inbound traffic is exactly when the set is worth having on disk,
/// and 32 changes at ~60 bytes each is well under the cost of one write.
pub const DEDUP_PERSIST_DIRTY_THRESHOLD: u32 = 32;
/// How long a dirty seen set may wait for the next `process()` tick before it
/// is written. Bounds what a crash loses to a few seconds of receipts.
pub const DEDUP_PERSIST_INTERVAL: Duration = from_secs;
/// The deduplicator's seen set as persisted under
/// [`storage_keys::DEDUP_SEEN_IDS`].
///
/// The deduplicator was in-memory only, so after a restart the socket copy of
/// a message the app had already consumed from a push injection was not
/// recognised as a duplicate: it went to the ratchet, whose generation for
/// that message was already spent, and surfaced as a decryption failure — a
/// spurious signal the app counts toward its split-brain breaker, which then
/// tears down a healthy session. Persisting the ids makes the second copy
/// recognisable across the restart. Ids and timestamps only; nothing here is
/// content.
///
/// `version` is the forward-compatibility hinge: an unknown version is dropped
/// rather than guessed at, and the set simply starts empty.
pub
/// The only record version this build writes or reads.
pub const DEDUP_SEEN_RECORD_VERSION: u8 = 1;
/// Seconds the Nostr receive watermark must advance before it is written back
/// to protocol-state storage. Same debounce role as
/// [`LAMPORT_PERSIST_INTERVAL`]: every inbound relay event moves the mark, and
/// a storage write per message is exactly the I/O the Lamport debounce exists
/// to avoid.
///
/// What an un-flushed gap costs is bounded and one-directional: a launch that
/// loses up to this much advance re-fetches a slightly wider slice of relay
/// history, which dedup absorbs. It can never *skip* messages, because the
/// stale mark is always behind the live one.
pub const NOSTR_WATERMARK_PERSIST_INTERVAL_SECS: i64 = 300;
pub const MEDIA_TRANSFER_STALE_TIMEOUT_SECS: u64 = 300;
/// Maximum number of tracked known peers for service discovery.
pub const MAX_KNOWN_PEERS: usize = 1000;
/// How long a known peer stays tracked without being re-seen.
///
/// Peers on carriers with no disconnect signal (Internet, Reticulum, Nostr,
/// and WiFi Direct message-path senders) are only ever *added* to
/// `known_peers`; this TTL is their eviction path, swept from the periodic
/// `cleanup_expired_entries` tick. A second layer — least-recently-seen
/// eviction when an insert hits `MAX_KNOWN_PEERS` — guarantees a newly
/// discovered peer is always tracked even between sweeps.
///
/// Deliberately generous: a connected-but-quiet BLE peer refreshes only via
/// platform advertisement sightings (BLE inbound messages do not route
/// through the discovery hook), so a short TTL would evict it while still
/// connected. Eviction is self-healing (the peer is re-tracked on its next
/// advertisement or message), so erring long only delays hygiene.
pub const KNOWN_PEER_TTL_SECS: u64 = 1800;
/// Battery level below which a device stops carrying traffic for other
/// people even while charging.
///
/// Re-exported from the router crate rather than restated here: message
/// forwarding and the relay role apply the same floor, and a device must not
/// keep carrying traffic at a level that would have stripped it of the role.
/// Two copies of the number would eventually disagree, and nothing would
/// notice.
pub use CRITICAL_RELAY_BATTERY_LEVEL;
/// The metadata keys a signed control frame carries: the Ed25519 signature
/// over the canonical payload, and the public key it verifies against, both
/// base64.
///
/// Re-exported rather than restated because the payload they accompany is
/// built by `offline_protocol_sealed::control_signing_payload`, which a leaf
/// node calls too. `CTRL_SIGN_DOMAIN` lives there as well and is no longer
/// named in this crate outside its tests: nothing here builds the payload any
/// more. A key or a domain declared in two places is one that can differ in
/// one of them, and the only symptom is a signature that stops verifying.
pub use ;
/// Maximum number of peers retained in the encryption-capability set that gates
/// inbound plaintext.
///
/// Sized to hold every legitimate source at once — the durable capability
/// records plus the MLS session list — with room to spare, so a real deployment
/// never reaches it. The cap exists because the set is keyed by a wire-claimed
/// sender id and nothing else bounds it.
///
/// Note what does *not* bound it: requiring a signature. The control gate does
/// now reject unsigned control frames before dispatch, so every marking path
/// runs on a verified frame — and that changes nothing here. A signature proves
/// the signer owns the address it claims; it does not prove the address belongs
/// to anyone real, and minting one costs a keygen. An attacker spending keygens
/// produces unlimited distinct well-signed peers, so "written only after a
/// signature verifies" is not by itself a bound on anything.
///
/// It bounds the durable `encryption_capable_peers` storage category as well,
/// because `OfflineProtocol::record_encryption_capable` persists only for a
/// peer this cap admitted.
///
/// Unlike the other maps keyed by a wire-claimed id, this one **refuses** at
/// capacity instead of resetting or evicting: forgetting a peer here is the
/// fail-open direction. See `OfflineProtocol::mark_encryption_capable`.
pub const MAX_ENCRYPTION_CAPABLE_PEERS: usize = 8192;
/// Maximum number of blocked users to retain.
pub const MAX_BLOCKED_USERS: usize = 10_000;
/// Maximum number of peers tracked for once-per-peer
/// `PlaintextReceiveRejected` warning suppression.
///
/// The keys are wire-claimed (attacker-controllable) sender ids, so the set
/// resets at capacity instead of growing without bound: a flood of forged
/// senders degrades the throttle to once-per-peer-per-generation while
/// memory stays capped.
pub const MAX_PLAINTEXT_RECEIVE_WARNED_PEERS: usize = 1000;
/// Maximum number of peers tracked for once-per-peer-per-code control-gate
/// warning suppression.
///
/// Every rejection the control gate reports is reachable from an unauthenticated
/// frame carrying an attacker-chosen sender id — that is what a gate rejection
/// *is* — so without a throttle an off-path injector turns the app's event
/// stream into a flood and desensitizes operators to the one code that has no
/// benign reading (`SENDER_ADDRESS_MISMATCH`). Bounded and reset at capacity for
/// the same reason as [`MAX_PLAINTEXT_RECEIVE_WARNED_PEERS`]: the keys are
/// attacker-controlled, so a forged-sender flood degrades the throttle to
/// once-per-peer-per-generation rather than growing memory without bound.
pub const MAX_CONTROL_GATE_WARNED_PEERS: usize = 1000;
/// Maximum number of pending (received-but-unused) peer key packages retained
/// in memory and in durable `MlsStorage`.
///
/// Keyed by the wire-claimed `sender`, so — like [`MAX_KNOWN_PEERS`] — an
/// unpinned peer can flood distinct forged ids under the default config. Each
/// entry is also written to durable secure storage (`persist_peer_key_package`,
/// iOS Keychain / Android Keystore) and re-loaded on boot, so without this cap
/// a flood grows durable storage without bound and re-inflates memory on every
/// restart. At capacity a new peer evicts the soonest-to-expire entry and drops
/// its persisted copy; the restore-on-boot loop is capped the same way.
pub const MAX_PENDING_KEY_PACKAGES: usize = 1000;
/// Maximum outbound messages waiting for one peer's MLS session.
///
/// This queue is durable and accepts application-controlled content, so a peer
/// that never completes session establishment must not grow it without bound.
/// The limit matches the default inbound pending-decryption per-peer bound.
///
/// A count alone does not bound memory or durable storage — message content is
/// application-supplied — so this cap works together with
/// [`MAX_PENDING_MESSAGE_BYTES_PER_PEER`]; whichever binds first wins.
pub const MAX_PENDING_MESSAGES_PER_PEER: usize = 64;
/// Maximum outbound messages waiting for MLS sessions across all peers.
///
/// At capacity the globally oldest message is settled as failed before the new
/// message is admitted. The limit matches the default inbound pending queue.
/// Paired with [`MAX_PENDING_MESSAGE_BYTES_GLOBAL`], as above.
pub const MAX_PENDING_MESSAGES_GLOBAL: usize = 4096;
/// Maximum pending entries expired in one `process()` tick.
///
/// Each expiry is a settlement *and* a durable delete, and the two have to stay
/// paired — so what gets bounded is how many entries expire per pass, not how
/// many deletes it may issue. Messages queued in a burst share a `queued_at` and
/// so come due in a burst; without this, one tick of the 100 ms bindings loop
/// could issue up to [`MAX_PENDING_MESSAGES_GLOBAL`] synchronous deletes, each a
/// device barrier on every built-in provider.
///
/// The remainder is not deferred indefinitely: the entries left behind are still
/// past their deadline, so `recompute_next_pending_message_expiry` leaves
/// `next_pending_message_expiry` in the past and the very next tick drains
/// another pass.
pub const MAX_PENDING_EXPIRIES_PER_PASS: usize = 64;
/// Maximum per-message records one launch writes migrating legacy queues.
///
/// The migration's writes are the one part of the pending restore that is not
/// already bounded by a delete budget, and a `store` is the more expensive of
/// the two: every built-in provider flushes the record *and* its directory. A
/// pre-split install sitting near [`MAX_PENDING_MESSAGES_GLOBAL`] would
/// otherwise pay thousands of device barriers inside `initialize_mls`, on the
/// launch path, where a mobile watchdog is watching.
///
/// Sized to match [`crate::protocol::storage::MAX_RESTORE_PRUNE_DELETES`], so
/// the whole walk's barrier count stays the same order of magnitude whichever
/// half of it does the work. Checked per recipient and before its first write,
/// so a queue is either migrated whole or left entirely on disk for the next
/// launch — never split across the two layouts with nothing to reconcile it.
pub const MAX_MIGRATED_PENDING_WRITES_PER_LAUNCH: usize = 512;
/// Maximum terminal settlements parked by restore for `start()` to drain.
///
/// The restore caps already bound how many can be produced, but they bound it
/// as a sum across every category, and nothing drains this queue until
/// `start()` — which an application that only calls `initialize_mls`, or that
/// retries it against a store that keeps failing, may never reach. Sized above
/// the largest single-category restore ([`MAX_PENDING_MESSAGES_GLOBAL`], the
/// pending queue's own global cap) so no legitimate restore is ever truncated;
/// past that point the count is reported instead of the events.
pub const MAX_DEFERRED_RESTORE_SETTLEMENTS: usize = 2 * MAX_PENDING_MESSAGES_GLOBAL;
/// Maximum size of application-supplied message content accepted at the public
/// send boundary, in bytes.
///
/// Enforced at the boundary — not at transmit time — because a message queued
/// behind MLS session establishment never reaches the transport's
/// `DEFAULT_MAX_MESSAGE_SIZE` (1 MiB) check: it sits in the durable pending
/// queue first. Without a boundary cap a handful of very large sends could
/// exhaust mobile memory and protocol-state disk while still being formally
/// "within" the count caps above.
///
/// 256 KiB leaves ample headroom under the 1 MiB transport ceiling for MLS
/// ciphertext expansion, base64, and the JSON wire envelope, so anything this
/// path accepts can actually be delivered. Larger payloads belong on the media
/// path (`send_media`), which chunks.
pub const MAX_MESSAGE_CONTENT_BYTES: usize = 256 * 1024;
/// Maximum total serialized bytes of one peer's pending-session queue.
///
/// At capacity the peer's oldest entries are settled as failed until the
/// incoming message fits, exactly like the count cap. Deliberately larger than
/// [`MAX_MESSAGE_CONTENT_BYTES`] plus [`MAX_RICH_EXTRAS_BYTES`] so a single
/// boundary-legal message always fits in an empty queue and admission can never
/// livelock (pinned by `pending_queue_byte_budgets_admit_any_boundary_legal_message`).
///
/// # Durable cost
///
/// Pending messages are persisted one record per message
/// ([`storage_keys::PENDING_MESSAGE_ENTRIES`]), so an enqueue writes its own
/// entry and nothing else: filling one peer to this budget costs `budget` bytes
/// written, not `budget × entries / 2`. The per-recipient layout this replaced
/// re-serialized the peer's whole queue on every enqueue, which made the byte
/// cost quadratic in the entry count.
///
/// Bytes were never the expensive half, though, and sizing this budget off them
/// would be reading the wrong meter. Every built-in provider pays two device
/// barriers per `store` (the record's own flush plus its directory's) and one
/// per `delete`, *regardless of record size* — so a 500-byte write and a 2 MiB
/// write cost the same in the resource that actually dominates. What the
/// per-message layout buys is not primarily speed but that a record which will
/// not open still names the message it lost; see
/// [`storage_keys::PENDING_MESSAGE_ENTRIES`].
///
/// So this budget is still sized to bound a pathological queue rather than to
/// describe a normal one — real queues hold a handful of short messages waiting
/// on a handshake. Lowering it below `MAX_MESSAGE_CONTENT_BYTES +
/// MAX_RICH_EXTRAS_BYTES` breaks admission outright.
pub const MAX_PENDING_MESSAGE_BYTES_PER_PEER: usize = 2 * 1024 * 1024;
/// Maximum total serialized bytes of the pending-session queue across all
/// peers. Bounds the whole feature's footprint on a mobile device regardless of
/// how many peers are mid-establishment.
pub const MAX_PENDING_MESSAGE_BYTES_GLOBAL: usize = 16 * 1024 * 1024;
/// Maximum size of a single persisted protocol-state record, in bytes.
///
/// Enforced on both sides of [`crate::ProtocolStateStorage`]: the SDK refuses to
/// write a larger record, and refuses to *deserialize* a larger one on restore
/// (dropping it instead), so a corrupted or tampered state file cannot turn
/// into an unbounded allocation during initialization.
///
/// Sized above [`MAX_PENDING_MESSAGE_BYTES_PER_PEER`] with room for JSON and
/// seal overhead. That was once tight rather than generous: under the
/// per-recipient pending layout the largest legitimate record *was* one peer's
/// full queue, so the two constants were one bound apart. Now that pending
/// messages are keyed per id the largest legitimate record is a single message
/// ([`MAX_MESSAGE_CONTENT_BYTES`] plus [`MAX_RICH_EXTRAS_BYTES`]) or one outbox
/// entry, and the headroom is real. Keep the ordering anyway — a legacy
/// per-recipient record still has to be readable for long enough to migrate it.
pub const MAX_PROTOCOL_STATE_RECORD_BYTES: usize = 4 * 1024 * 1024;
/// Maximum number of peers remembered in `key_package_sent_to` (the peers we
/// have pushed our key package to, with when we last did).
///
/// Wire-claimed ids grow this set in lockstep with a key-package flood, so it
/// resets at capacity like [`MAX_PLAINTEXT_RECEIVE_WARNED_PEERS`]: the only cost
/// of forgetting a peer is a one-time idempotent re-send of our key package.
pub const MAX_KEY_PACKAGE_SENT_TO: usize = 1000;
/// Maximum number of peers tracked in `rekey_due_at` (the per-peer epoch-desync
/// re-key floor).
///
/// The desync classification that reaches `schedule_session_rekey` is produced
/// by OpenMLS *before* it authenticates anything, so the peer id keying this map
/// is wire-claimed. The envelope/sender binding in `SessionManager::decrypt_message`
/// already confines that id to peers we hold a session with, which bounds the map
/// on its own; this cap is the same defence-in-depth every other wire-keyed map
/// carries. Resets at capacity like [`MAX_KEY_PACKAGE_SENT_TO`] — forgetting a
/// peer only costs one extra re-key being allowed through early.
pub const MAX_REKEY_TRACKED_PEERS: usize = 1000;
/// Maximum lifetime (in milliseconds) honored for a *received* peer key
/// package's cached expiry.
///
/// `remaining_lifetime_ms` arrives on the wire unauthenticated and becomes the
/// eviction sort key for [`MAX_PENDING_KEY_PACKAGES`] (the soonest-to-expire
/// entry is evicted first). Without a ceiling, a flood of forged senders
/// claiming a maximal lifetime would pin their entries as latest-to-expire and
/// preferentially evict legitimate peers. Key packages are minted with a 30-day
/// lifetime (`DEFAULT_KEY_PACKAGE_LIFETIME_SECS` in `offline-protocol-mls`), so
/// a larger value is never legitimate. This bound is purely cache bookkeeping —
/// OpenMLS enforces real key-package validity at use time — so clamping only
/// affects when we drop the *cached* copy, never crypto correctness.
pub const MAX_KEY_PACKAGE_LIFETIME_MS: u64 = 30 * 24 * 60 * 60 * 1000;
/// Durable record that a peer has proved it runs MLS.
///
/// Written whenever a control message from that peer verifies — signature
/// valid, and the signing key derives to the address the frame claims — and
/// read back on `initialize_mls` to reseed
/// [`OfflineProtocol::encryption_capable_peers`](crate::OfflineProtocol).
///
/// The timestamp is diagnostic, not a policy input. Its predecessor
/// (`TofuEntry.last_seen_ms`) drove LRU eviction of a bounded pin store; there
/// is no eviction here, because there is no longer any per-peer *secret* whose
/// size needs bounding — only the fact, which the restore walk bounds on its
/// own terms. Keeping the field costs nothing and makes a stale store readable
/// by a human.
pub
/// Payload for key package exchange, and the compact envelope version it
/// advertises.
///
/// Both live in `offline-protocol-sealed`: a leaf node builds and reads this
/// payload with a different MLS implementation, and two ends that disagree
/// about its shape cannot negotiate anything. Re-exported here so every
/// existing use site is unchanged.
pub use ;
/// Sealed rich-payload version advertised in
/// [`KeyPackagePayload::rich_versions`]: the decrypted MLS plaintext may be
/// `__RICH_V1__` + JSON of [`RichPayloadV1`], carrying reply context, rich
/// media metadata, and forward attribution inside the AEAD boundary instead
/// of on the relay-visible outer message.
pub const RICH_PAYLOAD_V1: u8 = 1;
/// Upper bound on the serialized size of the rich extras accepted by the
/// rich send surface. Enforced at the API boundary (`send_message_with`),
/// deliberately NOT at seal time: a message queued behind session
/// establishment re-makes the seal decision at flush, and a seal-time
/// failure there would re-queue the message forever. Bounding at the
/// boundary means every queued extras blob is already known to seal.
pub const MAX_RICH_EXTRAS_BYTES: usize = 32 * 1024;
/// Replicated-document sync version advertised in
/// [`KeyPackagePayload::data_versions`]: the decrypted MLS plaintext may be
/// `__DATA_V1__` + JSON of a sync frame (version-vector exchange, delta
/// push, or snapshot offer).
///
/// One number covers both the frame schema and the document encoding the
/// frames carry. Splitting them would let a peer advertise a frame schema it
/// speaks around an encoding it cannot read, and the failure would surface
/// as an unreadable document rather than as a refused negotiation.
pub const DATA_SYNC_V1: u8 = 1;
/// Group-space replication, advertised in
/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
/// sender intercepts `__DATA_V1__` frames arriving inside a *group*
/// ciphertext, not only inside a 1:1 one.
///
/// A separate entry rather than a bump, and the reason is a compatibility
/// trap rather than tidiness. A build that speaks only [`DATA_SYNC_V1`]
/// advertises it, holds group sessions, and has no group interception at
/// all: every group path emits whatever decrypts as a chat message, so a
/// group sync frame sent to one would surface to its user as literal
/// `__DATA_V1__{...}` text. Gating group sends on this entry is what keeps
/// that frame from ever being sent, and appending rather than replacing is
/// what keeps 1:1 replication working with those same peers.
pub const DATA_GROUP_V1: u8 = 2;
/// Attachment and snapshot carriage over the media path, advertised in
/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
/// sender understands the `need_blob` and `blob_gone` frame kinds, and
/// routes a media transfer marked as data-purposed into the data layer
/// instead of surfacing it to its user as a received file.
///
/// A third entry rather than a bump, for the reason the second one exists.
/// A build speaking only [`DATA_SYNC_V1`] replicates documents correctly and
/// has no arm for either new frame kind; it consumes them (the parser reads
/// the version first and the body second, so an unknown kind is dropped
/// rather than surfaced) but answers nothing, so a fetch aimed at it waits
/// forever. Worse, such a build receiving a data-purposed media transfer
/// emits `FileReceived` and hands a person a CRDT snapshot as a downloaded
/// file. Gating on this entry is what stops both.
///
/// v1 carries blobs on 1:1 sessions only, so this entry has no attested
/// sibling: group members never exchange key packages with each other, and
/// there is nothing about group carriage for an inviter to attest.
pub const DATA_MEDIA_V1: u8 = 3;
/// Document removals, advertised in [`KeyPackagePayload::data_versions`]
/// alongside [`DATA_SYNC_V1`]: the sender reads the `gone` field of a
/// version offer, and removes what a floor covers instead of offering it
/// back.
///
/// A fourth entry rather than a bump, for the reason the second and third
/// exist, and here the compatibility story is unusually gentle. A build
/// without this entry ignores an unknown field on a frame kind it knows, so
/// it keeps its copy and re-offers it forever; this device refuses each
/// offer and each blob against its own floor, so the removal still holds
/// everywhere it is known. Nothing is surfaced wrongly and nothing loops:
/// the cost is one offer per exchange that is answered with nothing.
///
/// Gating the *field* on the entry is therefore a traffic decision rather
/// than a safety one, which is why a group carries it ungated: one
/// ciphertext reaches the whole roster, so there is no per-member choice to
/// make, and the roster-wide gate on [`DATA_GROUP_V1`] already decides
/// whether the frame may be sent at all.
pub const DATA_TOMBSTONE_V1: u8 = 4;
/// Interest-scoped replication, advertised in
/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
/// sender reads the `want` field of a version offer and answers only the
/// documents it names.
///
/// A fifth entry rather than a bump, and like the fourth it gates traffic
/// rather than correctness. A peer without it ignores the field and answers
/// with everything it holds, and the asking side refuses what it did not ask
/// for on arrival, so the narrowing holds regardless; what it does not do is
/// save the radio. Gating means a narrowed space says so only where saying so
/// changes what comes back.
///
/// The half that does not depend on this entry is the local refusal, and it
/// is the reason interest is safe to ship before any peer speaks it.
pub const DATA_INTEREST_V1: u8 = 5;
/// Attachment bytes inside a group, advertised in
/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
/// sender answers a `need_blob` that arrives inside a group ciphertext, and
/// carries the bytes back as `chunk` frames under the group key.
///
/// A sixth entry rather than a bump, and the first `data_versions` entry
/// since the second with an attested sibling. [`DATA_MEDIA_V1`] has none
/// because carriage was 1:1 and there was nothing about it for a group
/// inviter to attest; this one is about a group, so there is.
///
/// What it gates is a better answer to a question, not safety. A member
/// without it receives a `need_blob` it understands the shape of and
/// refuses, and receives `chunk` frames whose kind it does not know and
/// drops: the version is read before the body, so an unknown kind is
/// consumed rather than surfaced. Nothing is shown to anybody wrongly. What
/// the entry buys is refusing a fetch at the call instead of leaving an
/// application waiting out the silence timeout for an answer that was never
/// coming.
pub const DATA_GROUP_BLOB_V1: u8 = 6;
/// The custody receipt, advertised in [`KeyPackagePayload::data_versions`]
/// alongside [`DATA_SYNC_V1`]: the peer parses the `__CUSTODY_RECEIPT__`
/// control frame, so a custodian that accepted one of its replication frames
/// may answer with a receipt (`docs/spec/custody.md`).
///
/// It gates one frame in one direction and nothing else. A deposit request is
/// a metadata key an unaware receiver ignores, so a depositor writes it toward
/// any neighbour, and acceptance is decided by the custodian's quotas. The
/// gate exists because a peer without the entry does not know the prefix as a
/// control frame: with encryption on it refuses the receipt as inbound
/// plaintext and records a security refusal, and on a plaintext-only
/// deployment it shows the receipt to its user as a message.
///
/// In the replication family rather than a list of its own because custody
/// carries replication frames only. No attested sibling: the receipt is a 1:1
/// control frame between neighbours, and a group inviter has nothing to say
/// about one.
pub const DATA_CUSTODY_V1: u8 = 7;
/// Rich fields accepted by the `send_message_with` surface. Only ever
/// delivered inside the sealed [`RichPayloadV1`] body — toward a recipient
/// that did not advertise [`RICH_PAYLOAD_V1`] they are silently dropped,
/// never sent cleartext.
pub
/// Options for `OfflineProtocol::send_message_with`: priority and reply
/// threading (as on `send_message`), plus the rich fields introduced with
/// the sealed rich payload.
///
/// The rich fields (`reply_context`, `media_metadata`, `forward_info`) only
/// ever travel inside the MLS-sealed `__RICH_V1__` body, and only toward
/// recipients whose key package advertised `rich_versions` support. Toward
/// anyone else they are silently dropped — never sent cleartext — so the
/// message degrades to plain text with `reply_to_msg` threading intact.
/// Options for `OfflineProtocol::send_media_with`: the chunk-0 media
/// metadata (as on `send_media`), plus the rich fields introduced with the
/// sealed rich payload and an optional caller-supplied `file_id`.
///
/// The rich fields (`caption`, `reply_to_msg`, `reply_context`,
/// `forward_info`) only ever travel inside the MLS-sealed chunk-0 plaintext
/// (v2 media envelope), and only toward recipients whose key package
/// advertised `rich_versions` support. Toward anyone else — including every
/// plaintext (encryption opt-out) transfer — they are silently dropped,
/// never sent cleartext, so the transfer degrades to what plain
/// `send_media` sends.
/// The sealed rich body: what `__RICH_V1__` + JSON carries inside the MLS
/// plaintext. `text` is the user-visible content; the optional fields are
/// restored onto the inbound message by `apply_decrypted_content` *after*
/// its outer-field strip, making the sealed body the sole trusted carrier
/// for rich data on encrypted messages.
pub
/// An outbound connection request awaiting a transport outcome (see
/// `OfflineProtocol::pending_connection_requests`).
pub
/// How long an outbound connection request stays correlatable to a
/// transport failure. Past this window the entry is pruned: a DeliveryError
/// that stale belongs to a request the app has long stopped showing a
/// spinner for.
///
/// Deliberately wider than the bridges' 60s `RecipientInFlightTracker` TTL:
/// that window anchors at the socket write, while this one anchors at
/// `send_connection_request` — a request can dwell in the internet outbox
/// (device offline, relay reconnecting) before its wire attempt, and this
/// window must cover that dwell plus the bridge's correlation window.
///
/// Also deliberately wider than the worst-case default ACK retry schedule
/// (10 retries, 1s initial delay, x2 backoff capped at 5 min, plus a 10s
/// ACK timeout per attempt — up to ~910s end to end): retry exhaustion is
/// the last settlement point that can still emit a typed undeliverable
/// event, so the window must outlive it with headroom.
pub const PENDING_CONNECTION_REQUEST_TTL: Duration =
from_secs;
/// Cap on tracked outbound connection requests (oldest evicted first).
pub const MAX_PENDING_CONNECTION_REQUESTS: usize = 64;
/// Upper bound (UTF-8 bytes) for `initial_message` on a connection request.
/// The request is a plaintext High-priority control frame; an unbounded
/// first message would fragment heavily over BLE and can exceed relay frame
/// limits after the SDK already returned a message id, so oversized input
/// fails loudly at the API instead.
pub const MAX_INITIAL_MESSAGE_BYTES: usize = 4096;
/// Payload for a connection request message.
pub
/// Payload for a connection accepted message.
pub
// --- Presence, typing, and read receipt payloads ---
/// Maximum number of message IDs allowed in a single read receipt.
pub const MAX_READ_RECEIPT_IDS: usize = 256;
/// Payload for a presence update message.
pub
/// Payload for a typing indicator message.
pub
/// Payload for a read receipt message.
pub
// --- Group (relay) payloads ---
pub
pub
pub
pub
pub
pub
pub
pub
pub
/// A received key package awaiting use for session creation.
pub
/// Delivery ACKs held for one peer until they go out as one frame (see
/// `OfflineProtocol::coalesced_acks_out`).
pub
/// Durable record of the end-to-end capability versions a peer last
/// advertised in its key package (`env_versions` / `rich_versions`).
///
/// Persisted separately from [`ReceivedKeyPackage`] because the cached key
/// package is deleted once a session is established, while the capabilities
/// must survive restarts for exactly those peers: mobile apps restart
/// constantly and MLS sessions persist, so without this record a rich send
/// right after relaunch silently degrades to bare text (and the compact
/// envelope to JSON) until the next live key-package exchange.
///
/// Stores the raw advertised versions, not the config-gated subset: the kill
/// switches (`compact_envelope_enabled` / `rich_payload_enabled`) gate use —
/// live recording, restore, and send — not knowledge, so toggling one across
/// restarts behaves the same as toggling it live.
///
/// `wire_versions` is deliberately absent: it is hop-local (which frames a
/// directly-connected peer decodes), and connection setup re-exchanges key
/// packages on discovery anyway, so persisting it would buy nothing.
pub
/// Length of an x-only secp256k1 public key in lowercase hex.
pub const NOSTR_PUBKEY_HEX_LEN: usize = 64;
/// Validates a wire-supplied Nostr public key before it is persisted or used
/// as a sealing destination.
///
/// Shape only — the value is signature-bound to the sender, so this is not an
/// authenticity check. It exists so a malformed or oversized string cannot
/// enter a durable record, and it normalizes case so the same key never
/// persists under two spellings.
pub
/// Cap on how many advertised version entries persist per capability list
/// in a [`PeerCapabilities`] record. The lists are unauthenticated wire
/// input stored raw (raw so unknown future versions survive a local
/// upgrade), and a hostile advertiser could otherwise bloat each durable
/// record up to the transport message size. Truncation only hurts the
/// advertiser — real senders list a handful of versions.
pub const MAX_PERSISTED_CAPABILITY_VERSIONS: usize = 8;
/// Which canonical payload a control frame's signature verified against.
///
/// Both are legitimate: [`Self::V1`] is what every peer signed before the
/// freshness-bound payload existed, and refusing it outright would refuse
/// first contact with any peer that has not upgraded. What the distinction
/// buys is that the two can be treated differently once a peer has *proved* it
/// can produce the newer one.
pub
/// What verifying a control frame's signature established.
pub
/// Outcome of [`OfflineProtocol::security_gate_control_message`].
///
/// [`OfflineProtocol`]: crate::OfflineProtocol
/// [`OfflineProtocol::security_gate_control_message`]: crate::OfflineProtocol
pub
/// Result of processing an internal protocol message.
pub
/// Outcome of routing an inbound file-chunk message through
/// [`OfflineProtocol::handle_incoming_file_chunk`]. Distinguishes chunks that
/// were dealt with terminally (decrypted/assembled, or dropped for a permanent
/// reason) from chunks queued for delayed decryption — so the receive loop can
/// defer the ACK for the latter, exactly like the text `Deferred` path.
///
/// [`OfflineProtocol::handle_incoming_file_chunk`]: crate::OfflineProtocol
///
/// `#[must_use]`: the ACK/defer decision hinges on this outcome. Dropping it on
/// the floor silently reverts to the pre-deferred-ACK behavior (always ACK,
/// leave dedup-marked), reintroducing the queue-path silent-loss bug — so every
/// caller must branch on it.
pub
/// Pending message waiting for session establishment.
pub
/// One persisted pending-queue record: a single queued message plus the peer
/// it is queued for.
///
/// The recipient rides *inside* the record because the key is the message id,
/// and the in-memory queue is a map keyed by recipient that has to be rebuilt
/// from records read in whatever order the store enumerates them. Same shape as
/// [`OutboxEntry`], whose recipient likewise travels in the record (inside its
/// `Message`) rather than in the key.
///
/// Deliberately a wrapper rather than a `recipient` field on [`PendingMessage`]:
/// in memory the recipient is already the map key, and a second copy there
/// would be free to drift from it.
pub
/// One inbound encrypted frame parked in the pending-decryption queue, as
/// persisted under [`storage_keys::PENDING_DECRYPT_ENTRIES`].
///
/// The queue itself is in-memory only (`PendingDecryptionQueue`); this record
/// is what lets an entry survive an app restart. Without it a frame that
/// arrived before its session was ready was lost the moment the process died
/// — and with a relay that pushes ciphertext without store-and-forward there
/// is no second copy to ask for, so a restart during a slow handshake was a
/// silently lost message.
///
/// Keyed by message id, like [`PendingMessageRecord`], so a drain, a prune or
/// an overflow drop deletes exactly the record it settled. `peer_id` rides
/// inside the record because the in-memory queue is a per-peer map rebuilt
/// from records the store enumerates in no particular order.
///
/// `first_received_at_ms` is wall-clock, not the `Instant` the in-memory entry
/// carries: an `Instant` does not survive a restart, so on restore the entry is
/// re-stamped with a fresh `Instant::now()` (its in-memory TTL restarts) and
/// this field bounds the *total* time on disk instead —
/// `PENDING_DECRYPT_PERSISTED_MAX_AGE_MS`.
///
/// `version` is a forward-compatibility hinge: a reader that sees a version it
/// does not know treats the record as corrupt and drops it rather than
/// guessing at fields. Records written before the field existed default to 1.
pub
/// The only record version this build writes or reads.
pub const PENDING_DECRYPT_RECORD_VERSION: u8 = 1;
/// One frame in custody, persisted under [`storage_keys::CUSTODY`].
///
/// The frame as it arrived with the deposit request removed and the hop
/// fields as the forwarding path adjusted them; the depositor, which is both
/// the frame's sender and the peer it arrived from; the wall-clock acceptance
/// time in Unix milliseconds, never a monotonic instant; and the class token.
/// `version` is the same forward-compatibility hinge as
/// [`PendingDecryptRecord::version`].
pub
/// The only custody record version this build writes or reads.
pub const CUSTODY_RECORD_VERSION: u8 = 1;
/// Identity carried by an outbound message that is re-entering the
/// pending-session queue rather than being queued for the first time.
///
/// Both fields exist to keep a re-queue from looking like a fresh send: the id
/// so `MessageSent`/`MessageDelivered`/`MessageFailed` stay correlatable with
/// what `send_message*` returned, and the timestamp so the absolute pending
/// lifetime is measured from first entry.
pub
/// Durable state for a peer MLS session.
pub
/// Durable lifecycle states for outbound Welcome delivery.
pub
/// Per-peer throttle for presence-driven welcome rescue (see
/// `OfflineProtocol::on_peer_presence`). Deliberately in-memory only: a
/// restart resets the backoff, and the one free rescue that buys is useful
/// after a restart anyway.
pub
/// Durable metadata for outbound Welcome reliability handling.
pub
/// Storage key types for message persistence.
pub
/// Protocol state.
/// Shared state protected by mutex.
pub
/// Locks the shared state, recovering it if an earlier holder panicked.
///
/// Recovering rather than refusing is what keeps events flowing (#514). The
/// callers that emit `message_received` and `message_delivered` act first
/// (the ACK is sent, the outbox entry removed) and lock to emit afterwards, so
/// a refusal here does not undo anything: it silently drops the one event
/// that reports what was done, and then every later one too, since a std
/// mutex stays poisoned for good. Nothing under this lock is left
/// half-written by a panic that matters: handler and sink calls, the only
/// foreign code run under it, are panic-isolated in
/// [`SharedState::emit_event`], and the remaining writes are single pushes
/// and pops on a queue or a field store.
///
/// Still returns a `Result`, so the call sites' existing handling stays
/// valid, but never `Err`.
pub
/// Provenance kept on an outbox entry so an encrypted DM can be *re-sealed*
/// against the peer's current MLS session on each resend, instead of replaying
/// the ciphertext bytes sealed at first send (which become permanently
/// undecryptable once the peer re-keys to a new epoch). Mirrors the fields the
/// pre-send [`PendingMessage`] carries, so both re-seal through the same
/// `prepare_outbound_content` chokepoint. Only populated for main-outbox
/// (non-media) encrypted DMs; absent (`None`) means verbatim replay — the
/// fallback for plaintext sends and media chunks.
///
/// **Memory-only by design.** This holds the message *plaintext*, so it is never
/// persisted (see the `#[serde(skip)]` on [`OutboxEntry::reseal`]): persisting it
/// would broaden plaintext-at-rest to every sent-but-unACKed encrypted DM for the
/// full outbox lifetime, weakening forward secrecy in exchange for only a narrow
/// cross-restart reseal benefit. After a restart the restored entry replays
/// verbatim; if that resend hits a desync, Tier 1 (un-ACK + re-key) still keeps
/// delivery honest rather than silently losing the message.
pub
pub
pub
pub
/// Crash-scoped descriptor of an in-flight outbound media transfer.
///
/// Persisted (no chunk bytes — see commit 42d1b86's rationale: resurrected
/// chunks can never complete, and per-chunk secure-storage writes are
/// expensive) when a transfer starts and deleted whenever the in-memory
/// transfer is removed (completed, aborted, or stale-swept). A descriptor
/// found on restore therefore means the app died mid-transfer:
/// [`crate::events::Event::MediaResendRequired`] is emitted so the app can
/// re-supply the bytes via `send_media_with` under the same `file_id`,
/// validated against `file_checksum`.
pub
pub
/// Pins that every signing domain, live or reserved, is mutually non-prefixing.
///
/// # Why this test exists here, of all places
///
/// Four domains are in production and they live in three languages and two
/// repositories: `offline-ctrl-v1` (this crate), `offline-disc-v1` and
/// `offline-invite-v1` (the MLS crate), and `offline-relay-addr-v1` (the relay
/// server, plus hand-mirrored copies in the iOS and Android bridges). Nothing
/// can import all four, so this module is the one place they can be compared at
/// all: it is the highest crate that can see two of them, and the fourth is
/// pinned as a literal.
///
/// A fifth is reserved and covered here too, for the reason reservation exists:
/// non-prefixing is a property of the whole set, so a domain that is specified
/// but not yet emitted still has to be held against every other one. A guard
/// that watched only live domains would happily accept a new live domain that
/// prefixes a reserved one, and the collision would be discovered by the
/// implementation that finally emits it.
/// Holds the spec's conformance-vector index against the files on disk.
///
/// # Why this test exists here, of all places
///
/// `docs/spec/README.md` carries a table naming every vector file and the
/// chapter it pins, and that table is what a second implementer reads to find
/// out what they can test themselves against. It is maintained by hand and
/// nothing compared it to the tree, so it was correct only by attention.
///
/// The failure is quiet in both directions. A vector file added without a row
/// is a conformance surface nobody outside this repository knows exists. A row
/// left behind by a moved or renamed file sends an implementer looking for
/// something that is not there, and the reasonable conclusion is that the
/// protocol has no vectors for that chapter rather than that the index is
/// stale.
///
/// It lives beside the signing-domain guard for the same reason that one is
/// here: this is the cross-cutting registry module, and the check needs no
/// crate's code at all, only the repository tree.