bsv-sdk 0.2.89

Pure Rust implementation of the BSV Blockchain SDK
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
//! Peer orchestrator for BRC-31 mutual authentication.
//!
//! The Peer manages handshakes, sessions via SessionManager, and message dispatch
//! over a Transport. It is the central protocol engine for BRC-31 Authrite.
//!
//! Translated from TS SDK Peer.ts (991 lines) and Go SDK peer.go (1163 lines).

use std::collections::HashMap;
use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock};

use tokio::sync::{mpsc, Mutex as AsyncMutex, RwLock};

use super::certificates::master::MasterCertificate;
use super::error::AuthError;
use super::session_manager::{MarkSeen, SessionManager};
use super::transports::Transport;
use super::types::{
    AuthMessage, MessageType, PeerSession, RequestedCertificateSet, AUTH_PROTOCOL_ID, AUTH_VERSION,
};
use super::utils::certificates::get_verifiable_certificates;
use super::utils::nonce::{create_nonce, verify_nonce};
use crate::wallet::interfaces::{
    Certificate, CreateSignatureArgs, GetPublicKeyArgs, VerifySignatureArgs, WalletInterface,
};
use crate::wallet::types::{Counterparty, CounterpartyType, Protocol};

// ---------------------------------------------------------------------------
// Listener callback type
// ---------------------------------------------------------------------------

/// Callback invoked when an incoming `certificateRequest` (or an initial
/// message carrying `requestedCertificates`) is received. Registered via
/// [`Peer::listen_for_certificates_requested`].
///
/// Mirrors TS SDK `Peer.listenForCertificatesRequested`. Fire-and-forget:
/// Peer does not await any async work the callback spawns. If the callback
/// needs to perform async work (e.g. reading the wallet + sending a cert
/// response) it should spawn its own task.
pub type OnCertificateRequestReceived =
    dyn Fn(String, RequestedCertificateSet) + Send + Sync + 'static;

// ---------------------------------------------------------------------------
// Interior-mutability state for the handshake / transport-drain path
// ---------------------------------------------------------------------------

/// All the mutable handshake/transport state that must be serialized so the
/// rest of `Peer` can be `&self`-shareable as `Arc<Peer<W>>`.
///
/// This holds only the single-consumer transport receiver. It lives behind a
/// `tokio::sync::Mutex` on `Peer` so that the handshake path (`initiate_handshake`,
/// `process_pending`, `process_next`) can drain/await on it while the lock-free
/// general-message hot path (`verify_general_message`, `create_general_message`)
/// never touches it.
///
/// The lock IS held across `rx.recv().await` inside `initiate_handshake` (a peer
/// can only meaningfully run one handshake-drain at a time — the transport
/// receiver is single-consumer), but it is NOT held across the wallet crypto
/// awaits in the message handlers: handlers take `&self` and are invoked after
/// a message has been pulled out of the receiver, so concurrent crypto work
/// (and the general-message hot path) proceeds without contention on this mutex.
struct HandshakeState {
    /// Transport incoming message receiver (single-consumer).
    transport_rx: Option<mpsc::Receiver<AuthMessage>>,
}

// ---------------------------------------------------------------------------
// Base64 helpers (self-contained, matching nonce module pattern)
// ---------------------------------------------------------------------------

fn base64_encode(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut result = String::new();
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let triple = (b0 << 16) | (b1 << 8) | b2;
        result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
        result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
        if chunk.len() > 1 {
            result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
        if chunk.len() > 2 {
            result.push(CHARS[(triple & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
    }
    result
}

fn base64_decode(s: &str) -> Result<Vec<u8>, AuthError> {
    fn char_to_val(c: u8) -> Result<u8, AuthError> {
        match c {
            b'A'..=b'Z' => Ok(c - b'A'),
            b'a'..=b'z' => Ok(c - b'a' + 26),
            b'0'..=b'9' => Ok(c - b'0' + 52),
            b'+' => Ok(62),
            b'/' => Ok(63),
            _ => Err(AuthError::SerializationError(format!(
                "invalid base64 char: {}",
                c as char
            ))),
        }
    }
    let bytes = s.as_bytes();
    let mut result = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'=' {
            break;
        }
        let a = char_to_val(bytes[i])?;
        let b = if i + 1 < bytes.len() && bytes[i + 1] != b'=' {
            char_to_val(bytes[i + 1])?
        } else {
            0
        };
        let c = if i + 2 < bytes.len() && bytes[i + 2] != b'=' {
            char_to_val(bytes[i + 2])?
        } else {
            0
        };
        let d = if i + 3 < bytes.len() && bytes[i + 3] != b'=' {
            char_to_val(bytes[i + 3])?
        } else {
            0
        };
        let triple = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
        result.push(((triple >> 16) & 0xFF) as u8);
        if i + 2 < bytes.len() && bytes[i + 2] != b'=' {
            result.push(((triple >> 8) & 0xFF) as u8);
        }
        if i + 3 < bytes.len() && bytes[i + 3] != b'=' {
            result.push((triple & 0xFF) as u8);
        }
        i += 4;
    }
    Ok(result)
}

fn parse_public_key(hex: &str) -> Result<crate::primitives::public_key::PublicKey, AuthError> {
    crate::primitives::public_key::PublicKey::from_string(hex).map_err(AuthError::from)
}

/// Current wall-clock time in milliseconds since the Unix epoch.
///
/// The clock lives here (in the `network`-gated `Peer`) rather than inside the
/// pure `SessionManager`, so the session module stays wasm/no_std-friendly (the
/// timestamp is injected). `Peer` is only compiled with the `network` feature,
/// which already pulls `std` + tokio, so `SystemTime` is always available here —
/// matching the existing `iso_now()` pattern in `clients::auth_fetch`.
fn now_ms() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// ---------------------------------------------------------------------------
// Peer
// ---------------------------------------------------------------------------

/// A peer capable of performing BRC-31 mutual authentication.
///
/// Manages sessions, handles authentication handshakes, certificate requests
/// and responses, and sends/receives general messages over a Transport.
///
/// Generic over `W: WalletInterface` for cryptographic operations.
/// Feature-gated behind `network` since it depends on tokio and Transport.
pub struct Peer<W: WalletInterface> {
    wallet: W,
    transport: Arc<dyn Transport>,
    /// Session store wrapped in an `Arc<RwLock>` so that the lock-free,
    /// `&self` general-message hot path (`verify_general_message`,
    /// `create_general_message`) can take concurrent read locks while the
    /// handshake path (which adds/updates sessions) takes a brief write lock.
    /// Read guards are never held across a wallet `await` — sessions are
    /// `.cloned()` out of the guard at every call site before any crypto.
    session_manager: Arc<RwLock<SessionManager>>,
    /// Certificates to include in handshake responses. `StdRwLock` so the
    /// `&self` setter and the `&self` handshake handlers can both touch it; it
    /// is only ever read under a brief synchronous lock (cloned out before any
    /// await), never held across `.await`.
    #[allow(dead_code)]
    certificates_to_include: StdRwLock<Vec<MasterCertificate>>,
    /// Certificate types to request from peers during handshake. Same locking
    /// discipline as `certificates_to_include`.
    certificates_to_request: StdRwLock<Option<RequestedCertificateSet>>,

    // Event channels (sender side -- Peer pushes events here). `mpsc::Sender`
    // is itself `&self`-cloneable/usable, so these need no extra wrapping.
    general_message_tx: mpsc::Sender<(String, Vec<u8>)>,
    certificate_tx: mpsc::Sender<(String, Vec<Certificate>)>,
    certificate_request_tx: mpsc::Sender<(String, RequestedCertificateSet)>,

    // Receiver side -- taken once by consumer. `StdMutex<Option<..>>` so the
    // `on_*` accessors can `.take()` under `&self` (they are called once,
    // before the Peer is shared, but must not require `&mut self`).
    general_message_rx: StdMutex<Option<mpsc::Receiver<(String, Vec<u8>)>>>,
    certificate_rx: StdMutex<Option<mpsc::Receiver<(String, Vec<Certificate>)>>>,
    certificate_request_rx: StdMutex<Option<mpsc::Receiver<(String, RequestedCertificateSet)>>>,

    /// Mutable handshake/transport-drain surface behind a single async mutex.
    /// Locked only by the handshake path (`process_pending`, `process_next`,
    /// `initiate_handshake`); the general-message hot path never touches it.
    handshake: AsyncMutex<HandshakeState>,

    // Listener callbacks for incoming certificateRequest messages.
    // Mirrors TS SDK `onCertificateRequestReceivedCallbacks`.
    //
    // `StdMutex` so registration (`listen_for_certificates_requested`) and the
    // synchronous fire path (`fire_certificate_request_listeners`) can both run
    // under `&self`. Callbacks are cloned out of the guard before invocation so
    // the lock is never held across the callback body.
    on_certificate_request_received_callbacks:
        StdMutex<HashMap<u64, Arc<OnCertificateRequestReceived>>>,
    callback_id_counter: StdMutex<u64>,
}

impl<W: WalletInterface> Peer<W> {
    /// Create a new Peer with the given wallet and transport.
    pub fn new(wallet: W, transport: Arc<dyn Transport>) -> Self {
        // General-message channel is bounded at 1024 (vs 32 for the
        // lower-traffic cert channels) so that N concurrent in-flight general
        // messages on a single session never trip `try_send` drops under
        // the client dispatcher.
        let (general_tx, general_rx) = mpsc::channel(1024);
        let (cert_tx, cert_rx) = mpsc::channel(32);
        let (cert_req_tx, cert_req_rx) = mpsc::channel(32);

        let transport_rx = transport.subscribe();

        Peer {
            wallet,
            transport,
            session_manager: Arc::new(RwLock::new(SessionManager::new())),
            certificates_to_include: StdRwLock::new(Vec::new()),
            certificates_to_request: StdRwLock::new(None),
            general_message_tx: general_tx,
            certificate_tx: cert_tx,
            certificate_request_tx: cert_req_tx,
            general_message_rx: StdMutex::new(Some(general_rx)),
            certificate_rx: StdMutex::new(Some(cert_rx)),
            certificate_request_rx: StdMutex::new(Some(cert_req_rx)),
            handshake: AsyncMutex::new(HandshakeState {
                transport_rx: Some(transport_rx),
            }),
            on_certificate_request_received_callbacks: StdMutex::new(HashMap::new()),
            callback_id_counter: StdMutex::new(0),
        }
    }

    /// Set certificates to include in handshake responses.
    ///
    /// `&self` (interior mutability) so it can be called on a shared
    /// `Arc<Peer>` before or after the peer is wrapped in an `Arc`.
    pub fn set_certificates_to_include(&self, certs: Vec<MasterCertificate>) {
        *self
            .certificates_to_include
            .write()
            .expect("certificates_to_include lock poisoned") = certs;
    }

    /// Set certificate types to request from peers during handshake.
    pub fn set_certificates_to_request(&self, requested: RequestedCertificateSet) {
        *self
            .certificates_to_request
            .write()
            .expect("certificates_to_request lock poisoned") = Some(requested);
    }

    /// Take the general message receiver. Returns None if already taken.
    pub fn on_general_message(&self) -> Option<mpsc::Receiver<(String, Vec<u8>)>> {
        self.general_message_rx
            .lock()
            .expect("general_message_rx lock poisoned")
            .take()
    }

    /// Take the certificates receiver. Returns None if already taken.
    pub fn on_certificates(&self) -> Option<mpsc::Receiver<(String, Vec<Certificate>)>> {
        self.certificate_rx
            .lock()
            .expect("certificate_rx lock poisoned")
            .take()
    }

    /// Take the certificate request receiver. Returns None if already taken.
    ///
    /// Exposes a pure observer channel: the receiver is notified for every
    /// incoming cert-request (and embedded cert-requests from the handshake).
    /// Taking the receiver does NOT disable the default auto-response — use
    /// [`Peer::listen_for_certificates_requested`] to override the response
    /// behaviour with an explicit handler.
    pub fn on_certificate_request(
        &self,
    ) -> Option<mpsc::Receiver<(String, RequestedCertificateSet)>> {
        self.certificate_request_rx
            .lock()
            .expect("certificate_request_rx lock poisoned")
            .take()
    }

    /// Register a handler that overrides the default certificate-request
    /// auto-response.
    ///
    /// Mirrors TS SDK `Peer.listenForCertificatesRequested`. When one or
    /// more callbacks are registered, an incoming `certificateRequest`
    /// (or a handshake message carrying `requestedCertificates`) fires each
    /// registered callback and the Peer does NOT auto-respond — the handler
    /// is expected to call [`Peer::send_certificate_response`] itself once
    /// it has resolved the verifiable certificates for the verifier.
    ///
    /// Returns a `callback_id` that can be passed to
    /// [`Peer::stop_listening_for_certificates_requested`] to remove the
    /// handler. The observer channel exposed via `on_certificate_request`
    /// continues to fire regardless of listener registration.
    pub fn listen_for_certificates_requested(
        &self,
        callback: Arc<OnCertificateRequestReceived>,
    ) -> u64 {
        let mut counter = self
            .callback_id_counter
            .lock()
            .expect("callback_id_counter lock poisoned");
        let id = *counter;
        *counter = counter.wrapping_add(1);
        drop(counter);
        self.on_certificate_request_received_callbacks
            .lock()
            .expect("cert-request callbacks lock poisoned")
            .insert(id, callback);
        id
    }

    /// Remove a previously registered certificate-request handler.
    ///
    /// Mirrors TS SDK `Peer.stopListeningForCertificatesRequested`.
    pub fn stop_listening_for_certificates_requested(&self, callback_id: u64) {
        self.on_certificate_request_received_callbacks
            .lock()
            .expect("cert-request callbacks lock poisoned")
            .remove(&callback_id);
    }

    /// Whether any cert-request listener is currently registered.
    fn has_certificate_request_listeners(&self) -> bool {
        !self
            .on_certificate_request_received_callbacks
            .lock()
            .expect("cert-request callbacks lock poisoned")
            .is_empty()
    }

    /// Fire all registered cert-request listeners with the given payload.
    ///
    /// Clones the callback `Arc`s out of the guard before invoking them so the
    /// registry lock is never held across the (synchronous) callback body —
    /// callbacks may themselves register/remove listeners without deadlocking.
    fn fire_certificate_request_listeners(
        &self,
        identity_key: &str,
        requested: &RequestedCertificateSet,
    ) {
        let callbacks: Vec<Arc<OnCertificateRequestReceived>> = self
            .on_certificate_request_received_callbacks
            .lock()
            .expect("cert-request callbacks lock poisoned")
            .values()
            .cloned()
            .collect();
        for cb in callbacks {
            (cb)(identity_key.to_string(), requested.clone());
        }
    }

    /// Clone the "best" session for an identifier (peer identity key or
    /// session nonce), if one exists. Takes a brief read lock and clones the
    /// session out before returning — never holds the lock across an await.
    pub async fn session_by_identifier(&self, identifier: &str) -> Option<PeerSession> {
        self.session_manager
            .read()
            .await
            .get_session_by_identifier(identifier)
            .cloned()
    }

    /// Clone all sessions tracked for a given peer identity key. Takes a brief
    /// read lock and clones the sessions out before returning.
    pub async fn sessions_for_identity(&self, identity_key: &str) -> Vec<PeerSession> {
        self.session_manager
            .read()
            .await
            .get_sessions_for_identity(identity_key)
            .into_iter()
            .cloned()
            .collect()
    }

    /// Process one incoming message from the transport.
    ///
    /// Returns `Ok(true)` if a message was processed, `Ok(false)` if no message
    /// was available (channel empty/closed).
    pub async fn process_next(&self) -> Result<bool, AuthError> {
        // Pull one message out under the handshake lock, then RELEASE the lock
        // before dispatching — dispatch performs wallet crypto awaits and must
        // not hold the transport mutex across them.
        let msg = {
            let mut hs = self.handshake.lock().await;
            let rx = match hs.transport_rx.as_mut() {
                Some(rx) => rx,
                None => return Ok(false),
            };
            match rx.try_recv() {
                Ok(msg) => msg,
                Err(mpsc::error::TryRecvError::Empty) => return Ok(false),
                Err(mpsc::error::TryRecvError::Disconnected) => return Ok(false),
            }
        };

        self.dispatch_message(msg).await?;
        Ok(true)
    }

    /// Process all pending incoming messages from the transport.
    ///
    /// Drains the transport receive buffer and dispatches each message.
    pub async fn process_pending(&self) -> Result<usize, AuthError> {
        let mut count = 0;
        while self.process_next().await? {
            count += 1;
        }
        Ok(count)
    }

    async fn create_general_message_from_session(
        &self,
        session: &PeerSession,
        payload: Vec<u8>,
    ) -> Result<AuthMessage, AuthError> {
        let request_nonce = base64_encode(&crate::primitives::random::random_bytes(32));
        let key_id = format!("{} {}", request_nonce, session.peer_nonce);

        let signature_result = self
            .wallet
            .create_signature(
                CreateSignatureArgs {
                    data: Some(payload.clone()),
                    hash_to_directly_sign: None,
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(parse_public_key(&session.peer_identity_key)?),
                    },
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        let identity_key_str = self.get_identity_public_key().await?;

        Ok(AuthMessage {
            version: AUTH_VERSION.to_string(),
            message_type: MessageType::General,
            identity_key: identity_key_str,
            nonce: Some(request_nonce),
            your_nonce: Some(session.peer_nonce.clone()),
            initial_nonce: Some(session.session_nonce.clone()),
            certificates: None,
            requested_certificates: None,
            payload: Some(payload),
            signature: Some(signature_result.signature),
        })
    }

    /// Build a signed general message for an existing authenticated session
    /// without sending it over the transport.
    ///
    /// `session_identifier` may be either the peer identity key or the local
    /// session nonce. The latter is useful for servers that need to bind the
    /// signature to the exact session that authenticated an incoming request.
    pub async fn create_general_message(
        &self,
        session_identifier: &str,
        payload: Vec<u8>,
    ) -> Result<AuthMessage, AuthError> {
        // Brief read lock: clone the session out before any wallet crypto.
        let session = self
            .session_manager
            .read()
            .await
            .get_session_by_identifier(session_identifier)
            .cloned()
            .ok_or_else(|| {
                AuthError::SessionNotFound(format!(
                    "session not found for identifier: {}",
                    session_identifier
                ))
            })?;

        if !session.is_authenticated {
            return Err(AuthError::NotAuthenticated(format!(
                "session not authenticated for identifier: {}",
                session_identifier
            )));
        }

        self.create_general_message_from_session(&session, payload)
            .await
    }

    /// Send a general message to a peer identified by their identity key.
    ///
    /// If no authenticated session exists, initiates a handshake first.
    pub async fn send_message(
        &self,
        identity_key: &str,
        payload: Vec<u8>,
    ) -> Result<(), AuthError> {
        // Find or create an authenticated session
        let session = self.get_authenticated_session(identity_key).await?;
        let general_msg = self
            .create_general_message_from_session(&session, payload)
            .await?;

        self.transport.send(general_msg).await
    }

    /// Send a certificate response to a peer.
    ///
    /// Sends a signed CertificateResponse message containing the given
    /// certificates. Initiates a handshake if no authenticated session
    /// exists with the peer.
    ///
    /// Translated from TS SDK `Peer.sendCertificateResponse` (signs the
    /// JSON-serialized certificate array with `keyID = "{requestNonce} {peerNonce}"`).
    pub async fn send_certificate_response(
        &self,
        identity_key: &str,
        certificates: Vec<Certificate>,
    ) -> Result<(), AuthError> {
        let session = self.get_authenticated_session(identity_key).await?;
        self.send_certificate_response_for_session(&session, certificates)
            .await
    }

    /// Inner helper: build + sign + send a CertificateResponse for an
    /// already-resolved session. Used by both the public API (which performs
    /// handshake first) and the dispatch-message auto-response paths (which
    /// already hold an authenticated session and must avoid re-entering
    /// `get_authenticated_session` to break async recursion).
    async fn send_certificate_response_for_session(
        &self,
        session: &PeerSession,
        certificates: Vec<Certificate>,
    ) -> Result<(), AuthError> {
        let identity_key_str = self.get_identity_public_key().await?;

        // Fresh request nonce for this outgoing message (32 random bytes,
        // base64-encoded), matching TS `Utils.toBase64(Random(32))`.
        let request_nonce = base64_encode(&crate::primitives::random::random_bytes(32));

        // Sign over the JSON-serialized certificates array, matching TS.
        let sign_data = serde_json::to_vec(&certificates).map_err(|e| {
            AuthError::SerializationError(format!(
                "failed to serialize certificates for signing: {}",
                e
            ))
        })?;
        let key_id = format!("{} {}", request_nonce, session.peer_nonce);
        let peer_pubkey = parse_public_key(&session.peer_identity_key)?;

        let sig_result = self
            .wallet
            .create_signature(
                CreateSignatureArgs {
                    data: Some(sign_data),
                    hash_to_directly_sign: None,
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(peer_pubkey),
                    },
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        let cert_response = AuthMessage {
            version: AUTH_VERSION.to_string(),
            message_type: MessageType::CertificateResponse,
            identity_key: identity_key_str,
            nonce: Some(request_nonce),
            your_nonce: Some(session.peer_nonce.clone()),
            initial_nonce: Some(session.session_nonce.clone()),
            certificates: Some(certificates),
            requested_certificates: None,
            payload: None,
            signature: Some(sig_result.signature),
        };

        self.transport.send(cert_response).await
    }

    /// Get an authenticated session for the given identity key, initiating
    /// a handshake if necessary.
    ///
    /// Public to allow AuthFetch to trigger handshake before sending
    /// general messages (needed for certificate exchange ordering).
    pub async fn get_authenticated_session(
        &self,
        identity_key: &str,
    ) -> Result<PeerSession, AuthError> {
        // Check if we already have an authenticated session.
        // Brief read lock: clone out before returning / before handshake await.
        {
            let mgr = self.session_manager.read().await;
            if let Some(session) = mgr.get_session_by_identifier(identity_key) {
                if session.is_authenticated {
                    return Ok(session.clone());
                }
            }
        }

        // Initiate handshake
        self.initiate_handshake(identity_key).await
    }

    /// Initiate a BRC-31 handshake with the given peer.
    ///
    /// Creates a nonce, sends an initialRequest, waits for the
    /// initialResponse (polling the transport), and completes the handshake.
    async fn initiate_handshake(&self, identity_key: &str) -> Result<PeerSession, AuthError> {
        let session_nonce = create_nonce(&self.wallet).await?;

        // Create initial session (not yet authenticated). Write lock. Touch it
        // so idle reaping has a baseline, and opportunistically reap on this
        // low-frequency handshake path (keeps the hot verify path reap-free).
        {
            let mut mgr = self.session_manager.write().await;
            mgr.add_session(PeerSession {
                session_nonce: session_nonce.clone(),
                peer_identity_key: identity_key.to_string(),
                peer_nonce: String::new(),
                is_authenticated: false,
            });
            let now = now_ms();
            mgr.touch(&session_nonce, now);
            mgr.reap_idle(now);
        }

        let identity_key_str = self.get_identity_public_key().await?;

        let initial_request = AuthMessage {
            version: AUTH_VERSION.to_string(),
            message_type: MessageType::InitialRequest,
            identity_key: identity_key_str,
            nonce: None,
            your_nonce: None,
            initial_nonce: Some(session_nonce.clone()),
            certificates: None,
            requested_certificates: self
                .certificates_to_request
                .read()
                .expect("certificates_to_request lock poisoned")
                .clone(),
            payload: None,
            signature: None,
        };

        // Send the request
        self.transport.send(initial_request).await?;

        // Wait for the response by polling the transport
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
        loop {
            if tokio::time::Instant::now() > deadline {
                return Err(AuthError::Timeout("handshake timeout".to_string()));
            }

            // Lock the handshake mutex only to pull the next message off the
            // single-consumer transport receiver, then RELEASE it before any
            // dispatch / complete-handshake crypto await below. Holding the
            // lock across `rx.recv().await` is fine (only one drainer at a
            // time), but holding it across wallet crypto would serialize the
            // whole handshake path unnecessarily.
            let msg = {
                let mut hs = self.handshake.lock().await;
                let rx = hs.transport_rx.as_mut().ok_or_else(|| {
                    AuthError::TransportNotConnected("no transport rx".to_string())
                })?;
                match tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv()).await {
                    Ok(Some(msg)) => msg,
                    Ok(None) => {
                        return Err(AuthError::TransportNotConnected(
                            "transport closed".to_string(),
                        ))
                    }
                    Err(_) => continue, // timeout, retry (lock released here)
                }
            };

            // If this is the initialResponse we're waiting for, process it
            if msg.message_type == MessageType::InitialResponse {
                if let Some(ref your_nonce) = msg.your_nonce {
                    if your_nonce == &session_nonce {
                        return self.complete_handshake(&session_nonce, msg).await;
                    }
                }
            }

            // Otherwise dispatch the message normally
            self.dispatch_message(msg).await?;
        }
    }

    /// Complete a handshake after receiving the initialResponse.
    async fn complete_handshake(
        &self,
        session_nonce: &str,
        response: AuthMessage,
    ) -> Result<PeerSession, AuthError> {
        // Verify the nonce was created by us
        let valid_nonce = verify_nonce(&self.wallet, session_nonce).await?;
        if !valid_nonce {
            return Err(AuthError::InvalidNonce(format!(
                "our session nonce failed verification: {}",
                session_nonce
            )));
        }

        let peer_nonce = response.initial_nonce.clone().unwrap_or_default();

        // Verify the response signature
        // IMPORTANT: decode each nonce separately then concatenate bytes
        let our_nonce_bytes = base64_decode(session_nonce)?;
        let peer_nonce_bytes = base64_decode(&peer_nonce)?;
        let mut verify_data = our_nonce_bytes;
        verify_data.extend_from_slice(&peer_nonce_bytes);

        let key_id = format!("{} {}", session_nonce, peer_nonce);

        let verify_result = self
            .wallet
            .verify_signature(
                VerifySignatureArgs {
                    data: Some(verify_data),
                    hash_to_directly_verify: None,
                    signature: response.signature.clone().unwrap_or_default(),
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(parse_public_key(&response.identity_key)?),
                    },
                    for_self: None,
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        if !verify_result.valid {
            return Err(AuthError::InvalidSignature(
                "initial response signature verification failed".to_string(),
            ));
        }

        // Update session to authenticated
        let session = PeerSession {
            session_nonce: session_nonce.to_string(),
            peer_identity_key: response.identity_key.clone(),
            peer_nonce,
            is_authenticated: true,
        };

        // Write lock: promote the session to authenticated, refresh its activity
        // timestamp, and opportunistically reap idle sessions.
        {
            let mut mgr = self.session_manager.write().await;
            mgr.update_session(session_nonce, session.clone());
            let now = now_ms();
            mgr.touch(session_nonce, now);
            mgr.reap_idle(now);
        }

        // Push certificates to channel if any
        if let Some(certs) = response.certificates {
            if !certs.is_empty() {
                let _ = self
                    .certificate_tx
                    .send((response.identity_key.clone(), certs))
                    .await;
            }
        }

        // Handle certificate requests from peer embedded in the
        // initialResponse (TS Peer.ts:653-684). Same branching as the
        // standalone certificateRequest path.
        if let Some(ref requested) = response.requested_certificates {
            if !requested.certifiers.is_empty() {
                // Observer channel: non-blocking. If no one has taken the
                // receiver (or the buffer is full), drop silently rather
                // than stall dispatch.
                let _ = self
                    .certificate_request_tx
                    .try_send((response.identity_key.clone(), requested.clone()));

                if self.has_certificate_request_listeners() {
                    self.fire_certificate_request_listeners(&response.identity_key, requested);
                } else {
                    let verifier_pubkey = parse_public_key(&response.identity_key)?;
                    let verifiable =
                        get_verifiable_certificates(&self.wallet, requested, &verifier_pubkey)
                            .await?;
                    if !verifiable.is_empty() {
                        let certs: Vec<Certificate> =
                            verifiable.into_iter().map(|vc| vc.certificate).collect();
                        // Use the session we just authenticated (breaks the
                        // async recursion that would otherwise occur through
                        // `get_authenticated_session` → `initiate_handshake`).
                        self.send_certificate_response_for_session(&session, certs)
                            .await?;
                    }
                }
            }
        }

        Ok(session)
    }

    /// Dispatch an incoming message based on its type.
    /// Dispatch a single incoming auth message directly.
    ///
    /// This is useful when you want to process one specific message without
    /// draining the entire transport channel via `process_pending`.
    pub async fn dispatch_message(&self, msg: AuthMessage) -> Result<(), AuthError> {
        if msg.version != AUTH_VERSION {
            return Err(AuthError::InvalidMessage(format!(
                "unsupported auth version: {}, expected: {}",
                msg.version, AUTH_VERSION
            )));
        }

        match msg.message_type {
            MessageType::InitialRequest => self.handle_initial_request(msg).await,
            MessageType::InitialResponse => {
                // InitialResponse should be handled by initiate_handshake polling.
                // If we get one here unexpectedly, ignore it.
                Ok(())
            }
            MessageType::CertificateRequest => self.process_certificate_request(msg).await,
            MessageType::CertificateResponse => {
                if let Some(certs) = msg.certificates {
                    if !certs.is_empty() {
                        let _ = self
                            .certificate_tx
                            .send((msg.identity_key.clone(), certs))
                            .await;
                    }
                }
                Ok(())
            }
            MessageType::General => self.handle_general_message(msg).await,
        }
    }

    /// Process an inbound `certificateRequest` message.
    ///
    /// Mirrors TS SDK `Peer.processCertificateRequest`:
    /// 1. Verify `yourNonce` was created by us.
    /// 2. Look up the session for that nonce.
    /// 3. Verify the signature over `JSON.stringify(requestedCertificates)`
    ///    (counterparty = peer identity key, keyID = "{nonce} {sessionNonce}").
    /// 4. If `requestedCertificates.certifiers` is non-empty, either fire
    ///    registered listeners OR auto-respond via the wallet.
    ///
    /// The observer channel is notified in all cases (even when no certifiers
    /// are requested or when verification fails) *only* for the non-failure
    /// path, matching the existing observer semantics.
    async fn process_certificate_request(&self, msg: AuthMessage) -> Result<(), AuthError> {
        let your_nonce = msg.your_nonce.as_deref().ok_or_else(|| {
            AuthError::InvalidMessage("missing yourNonce in certificateRequest".to_string())
        })?;

        // 1. Verify our nonce
        let valid_nonce = verify_nonce(&self.wallet, your_nonce).await?;
        if !valid_nonce {
            return Err(AuthError::InvalidNonce(format!(
                "certificateRequest nonce verification failed from: {}",
                msg.identity_key
            )));
        }

        // A signed, session-bound certificateRequest is replay-protected just
        // like a general message: require a per-message nonce.
        let msg_nonce = msg.nonce.as_deref().unwrap_or("");
        if msg_nonce.is_empty() {
            return Err(AuthError::InvalidMessage(format!(
                "missing per-message nonce in certificateRequest from: {}",
                msg.identity_key
            )));
        }

        // 2. Look up session (brief read lock; clone out before crypto await).
        //    TTL-honoring so a stale/captured `yourNonce` stops resolving.
        let now = now_ms();
        let session = self
            .session_manager
            .read()
            .await
            .get_active_session(your_nonce, now)
            .cloned()
            .ok_or_else(|| {
                AuthError::SessionNotFound(format!("session not found for nonce: {}", your_nonce))
            })?;

        // 3. Verify signature over JSON.stringify(requestedCertificates)
        let requested = msg.requested_certificates.as_ref().ok_or_else(|| {
            AuthError::InvalidMessage("missing requestedCertificates in certificateRequest".into())
        })?;

        let sign_data = serde_json::to_vec(requested).map_err(|e| {
            AuthError::SerializationError(format!(
                "failed to serialize requestedCertificates for verification: {}",
                e
            ))
        })?;
        let key_id = format!("{} {}", msg_nonce, session.session_nonce);
        let peer_pubkey = parse_public_key(&session.peer_identity_key)?;

        let verify_result = self
            .wallet
            .verify_signature(
                VerifySignatureArgs {
                    data: Some(sign_data),
                    hash_to_directly_verify: None,
                    signature: msg.signature.clone().unwrap_or_default(),
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(peer_pubkey),
                    },
                    for_self: None,
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        if !verify_result.valid {
            return Err(AuthError::InvalidSignature(format!(
                "invalid signature in certificateRequest from {}",
                session.peer_identity_key
            )));
        }

        // Anti-replay gate (after signature verification, before dispatch).
        // Shares the per-session seen-set with general messages, keyed on the
        // fresh per-message nonce. Brief synchronous write lock, no `.await` held.
        match self.session_manager.write().await.mark_message_seen(
            &session.session_nonce,
            msg_nonce,
            now,
        ) {
            MarkSeen::Fresh => {}
            MarkSeen::Replay => {
                return Err(AuthError::ReplayDetected(format!(
                    "duplicate certificateRequest nonce on session from {}",
                    msg.identity_key
                )));
            }
            MarkSeen::SessionGone => {
                return Err(AuthError::SessionNotFound(format!(
                    "session evicted during verify for nonce: {}",
                    your_nonce
                )));
            }
        }

        // Observer channel: non-blocking. Separate from handler listeners;
        // fire-and-forget if no consumer / buffer full.
        let _ = self
            .certificate_request_tx
            .try_send((msg.identity_key.clone(), requested.clone()));

        // 4. Decide handler vs auto-response path
        if requested.certifiers.is_empty() {
            return Ok(());
        }

        if self.has_certificate_request_listeners() {
            // Handler mode: delegate to registered listeners and stop.
            self.fire_certificate_request_listeners(&msg.identity_key, requested);
            return Ok(());
        }

        // Auto-response path: mirror TS fallback — fetch + send. Use the
        // session we already resolved to avoid re-entering
        // `get_authenticated_session` (which would cycle through handshake).
        let verifier_pubkey = parse_public_key(&msg.identity_key)?;
        let verifiable =
            get_verifiable_certificates(&self.wallet, requested, &verifier_pubkey).await?;
        if verifiable.is_empty() {
            return Ok(());
        }
        let certs: Vec<Certificate> = verifiable.into_iter().map(|vc| vc.certificate).collect();
        self.send_certificate_response_for_session(&session, certs)
            .await
    }

    /// Handle an incoming initialRequest message.
    ///
    /// Creates a session, signs a response, and sends the initialResponse back.
    async fn handle_initial_request(&self, msg: AuthMessage) -> Result<(), AuthError> {
        let peer_initial_nonce = msg.initial_nonce.as_deref().ok_or_else(|| {
            AuthError::InvalidMessage("missing initialNonce in initialRequest".to_string())
        })?;

        if peer_initial_nonce.is_empty() {
            return Err(AuthError::InvalidMessage(
                "empty initialNonce in initialRequest".to_string(),
            ));
        }

        // Create our session nonce
        let session_nonce = create_nonce(&self.wallet).await?;

        // Add session (authenticated -- responder trusts after signature
        // verification). Write lock. Touch for the idle-reaping baseline and
        // opportunistically reap idle sessions on this handshake path.
        {
            let mut mgr = self.session_manager.write().await;
            mgr.add_session(PeerSession {
                session_nonce: session_nonce.clone(),
                peer_identity_key: msg.identity_key.clone(),
                peer_nonce: peer_initial_nonce.to_string(),
                is_authenticated: true,
            });
            let now = now_ms();
            mgr.touch(&session_nonce, now);
            mgr.reap_idle(now);
        }

        // If the peer requested certificates in their initialRequest, resolve
        // them here so we can embed the response in the single-round-trip
        // initialResponse (TS Peer.ts:509-528). Listener mode notifies the
        // handler and leaves `certificates_to_include` as None — the handler
        // can issue a separate certificateResponse if needed.
        let mut certificates_to_include: Option<Vec<Certificate>> = None;
        if let Some(ref requested) = msg.requested_certificates {
            if !requested.certifiers.is_empty() {
                // Observer channel: non-blocking fire-and-forget.
                let _ = self
                    .certificate_request_tx
                    .try_send((msg.identity_key.clone(), requested.clone()));

                if self.has_certificate_request_listeners() {
                    self.fire_certificate_request_listeners(&msg.identity_key, requested);
                } else {
                    let verifier_pubkey = parse_public_key(&msg.identity_key)?;
                    let verifiable =
                        get_verifiable_certificates(&self.wallet, requested, &verifier_pubkey)
                            .await?;
                    if !verifiable.is_empty() {
                        certificates_to_include =
                            Some(verifiable.into_iter().map(|vc| vc.certificate).collect());
                    }
                }
            }
        }

        // Sign the response: data = decode(peer_nonce) ++ decode(our_nonce)
        // IMPORTANT: decode each nonce separately then concatenate bytes
        let peer_nonce_bytes = base64_decode(peer_initial_nonce)?;
        let our_nonce_bytes = base64_decode(&session_nonce)?;
        let mut sign_data = peer_nonce_bytes;
        sign_data.extend_from_slice(&our_nonce_bytes);

        let key_id = format!("{} {}", peer_initial_nonce, session_nonce);

        let identity_result = self
            .wallet
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        let peer_pubkey = parse_public_key(&msg.identity_key)?;

        let sig_result = self
            .wallet
            .create_signature(
                CreateSignatureArgs {
                    data: Some(sign_data),
                    hash_to_directly_sign: None,
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(peer_pubkey),
                    },
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        let response = AuthMessage {
            version: AUTH_VERSION.to_string(),
            message_type: MessageType::InitialResponse,
            identity_key: identity_result.public_key.to_der_hex(),
            nonce: None,
            your_nonce: Some(peer_initial_nonce.to_string()),
            initial_nonce: Some(session_nonce),
            certificates: certificates_to_include,
            requested_certificates: self
                .certificates_to_request
                .read()
                .expect("certificates_to_request lock poisoned")
                .clone(),
            payload: None,
            signature: Some(sig_result.signature),
        };

        self.transport.send(response).await
    }

    /// Verify an incoming general message without any side effects on the
    /// transport or event channels.
    ///
    /// This is the **lock-free, `&self` hot path** intended for the HTTP
    /// server middleware: it verifies the BRC-31 nonce + signature against the
    /// authenticated session and returns. It:
    ///
    /// - takes only a brief `session_manager.read()` lock (cloning the session
    ///   out before the wallet crypto await — the read lock is never held
    ///   across `.await`), so N concurrent verifies on one session proceed
    ///   without contention;
    /// - does **not** call `process_pending()` and does **not** touch the
    ///   transport's `pending` correlation map (that drain/map is confined to
    ///   the handshake path — it was the root cause of the server 400s under
    ///   concurrency);
    /// - does **not** push to the `general_message` channel (the server path
    ///   only needs the verification result, not the decoded payload).
    ///
    /// Callable on `&Peer` (and thus on `Arc<Peer<W>>`), enabling concurrent
    /// in-flight general messages on a single authenticated session.
    pub async fn verify_general_message(&self, msg: AuthMessage) -> Result<(), AuthError> {
        let your_nonce = msg.your_nonce.as_deref().ok_or_else(|| {
            AuthError::InvalidMessage("missing yourNonce in general message".to_string())
        })?;

        // Verify the nonce was created by us
        let valid_nonce = verify_nonce(&self.wallet, your_nonce).await?;
        if !valid_nonce {
            return Err(AuthError::InvalidNonce(format!(
                "general message nonce verification failed from: {}",
                msg.identity_key
            )));
        }

        // Every honest sender mints a fresh 32-byte per-message nonce; a message
        // without one cannot be replay-protected, so reject it outright (stricter
        // than the TS reference, wire-compatible since TS always sets it).
        let msg_nonce = msg.nonce.as_deref().unwrap_or("");
        if msg_nonce.is_empty() {
            return Err(AuthError::InvalidMessage(format!(
                "missing per-message nonce in general message from: {}",
                msg.identity_key
            )));
        }

        // Verify session exists AND is not idle-expired. Brief read lock — clone
        // out before crypto. Honoring the TTL here means a stale/captured
        // `yourNonce` stops resolving a live session once the idle window lapses.
        let now = now_ms();
        let session = self
            .session_manager
            .read()
            .await
            .get_active_session(your_nonce, now)
            .cloned()
            .ok_or_else(|| {
                AuthError::SessionNotFound(format!("session not found for nonce: {}", your_nonce))
            })?;

        // Verify signature
        let payload = msg.payload.clone().unwrap_or_default();
        let key_id = format!("{} {}", msg_nonce, session.session_nonce);

        let peer_pubkey = parse_public_key(&msg.identity_key)?;

        let verify_result = self
            .wallet
            .verify_signature(
                VerifySignatureArgs {
                    data: Some(payload.clone()),
                    hash_to_directly_verify: None,
                    signature: msg.signature.clone().unwrap_or_default(),
                    protocol_id: Protocol {
                        security_level: 2,
                        protocol: AUTH_PROTOCOL_ID.to_string(),
                    },
                    key_id,
                    counterparty: Counterparty {
                        counterparty_type: CounterpartyType::Other,
                        public_key: Some(peer_pubkey),
                    },
                    for_self: None,
                    privileged: false,
                    privileged_reason: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;

        if !verify_result.valid {
            return Err(AuthError::InvalidSignature(format!(
                "invalid signature in general message from {}",
                msg.identity_key
            )));
        }

        // Anti-replay gate (AFTER signature verification, so the seen-set is
        // never poisoned by unauthenticated input; BEFORE dispatch). Brief
        // synchronous write lock — no `.await` is held while it is taken, so the
        // lock-free hot path is not serialized across crypto. The check-and-
        // insert is atomic, so concurrent verifies of the SAME captured message
        // resolve to exactly one acceptance and the rest are rejected.
        match self.session_manager.write().await.mark_message_seen(
            &session.session_nonce,
            msg_nonce,
            now,
        ) {
            MarkSeen::Fresh => {}
            MarkSeen::Replay => {
                return Err(AuthError::ReplayDetected(format!(
                    "duplicate general message nonce on session from {}",
                    msg.identity_key
                )));
            }
            MarkSeen::SessionGone => {
                return Err(AuthError::SessionNotFound(format!(
                    "session evicted during verify for nonce: {}",
                    your_nonce
                )));
            }
        }

        Ok(())
    }

    /// Handle an incoming general message on the dispatch path (client side).
    ///
    /// Verifies via [`Peer::verify_general_message`], then pushes the decoded
    /// `(sender_identity_key, payload)` to the `general_message` channel so the
    /// AuthFetch dispatcher task can route the response by nonce. The server
    /// middleware does NOT use this path — it calls `verify_general_message`
    /// directly to avoid the channel push.
    async fn handle_general_message(&self, msg: AuthMessage) -> Result<(), AuthError> {
        let identity_key = msg.identity_key.clone();
        let payload = msg.payload.clone().unwrap_or_default();

        // Verify nonce + signature against the authenticated session.
        self.verify_general_message(msg).await?;

        // Push to general message channel (non-blocking). The bounded-1024
        // channel and single-consumer dispatcher make drops practically
        // impossible under normal concurrency.
        let _ = self.general_message_tx.try_send((identity_key, payload));

        Ok(())
    }

    /// Get this peer's identity public key as a hex string.
    async fn get_identity_public_key(&self) -> Result<String, AuthError> {
        let result = self
            .wallet
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;
        Ok(result.public_key.to_der_hex())
    }

    /// Test-only: take the transport receiver out of the handshake state so a
    /// test can directly inspect inbound wire messages. Not part of the public
    /// API; the handshake mutex is uncontended in single-threaded tests.
    #[cfg(test)]
    async fn take_transport_rx(&self) -> Option<mpsc::Receiver<AuthMessage>> {
        self.handshake.lock().await.transport_rx.take()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::private_key::PrivateKey;
    use crate::wallet::error::WalletError;
    use crate::wallet::interfaces::*;
    use crate::wallet::types::Protocol as WalletProtocol;
    use crate::wallet::ProtoWallet;
    use async_trait::async_trait;
    use std::sync::Mutex as StdMutex;

    /// Compile-time guarantee: `Peer<W>` (and thus `Arc<Peer<W>>`) is
    /// `Send + Sync` for any `Send + Sync` wallet, so it can be shared across
    /// tasks/threads without an outer `Mutex`. If a future field reintroduces a
    /// non-`Sync` member (e.g. a bare `Cell`/`RefCell`), this fails to compile.
    fn _assert_peer_send_sync<W: WalletInterface + Send + Sync>() {
        fn is_send_sync<T: Send + Sync>() {}
        is_send_sync::<Peer<W>>();
        is_send_sync::<std::sync::Arc<Peer<W>>>();
    }

    // -----------------------------------------------------------------------
    // TestWallet: WalletInterface wrapper around ProtoWallet
    // -----------------------------------------------------------------------

    struct TestWallet {
        inner: ProtoWallet,
    }

    impl TestWallet {
        fn new(pk: PrivateKey) -> Self {
            TestWallet {
                inner: ProtoWallet::new(pk),
            }
        }
    }

    macro_rules! stub_method {
        ($name:ident, $args:ty, $ret:ty) => {
            fn $name<'life0, 'life1, 'async_trait>(
                &'life0 self,
                _args: $args,
                _originator: Option<&'life1 str>,
            ) -> ::core::pin::Pin<
                Box<
                    dyn ::core::future::Future<Output = Result<$ret, WalletError>>
                        + ::core::marker::Send
                        + 'async_trait,
                >,
            >
            where
                'life0: 'async_trait,
                'life1: 'async_trait,
                Self: 'async_trait,
            {
                Box::pin(async move {
                    unimplemented!(concat!(stringify!($name), " not needed for peer tests"))
                })
            }
        };
        ($name:ident, $ret:ty) => {
            fn $name<'life0, 'life1, 'async_trait>(
                &'life0 self,
                _originator: Option<&'life1 str>,
            ) -> ::core::pin::Pin<
                Box<
                    dyn ::core::future::Future<Output = Result<$ret, WalletError>>
                        + ::core::marker::Send
                        + 'async_trait,
                >,
            >
            where
                'life0: 'async_trait,
                'life1: 'async_trait,
                Self: 'async_trait,
            {
                Box::pin(async move {
                    unimplemented!(concat!(stringify!($name), " not needed for peer tests"))
                })
            }
        };
    }

    #[async_trait::async_trait]
    impl WalletInterface for TestWallet {
        stub_method!(create_action, CreateActionArgs, CreateActionResult);
        stub_method!(sign_action, SignActionArgs, SignActionResult);
        stub_method!(abort_action, AbortActionArgs, AbortActionResult);
        stub_method!(list_actions, ListActionsArgs, ListActionsResult);
        stub_method!(
            internalize_action,
            InternalizeActionArgs,
            InternalizeActionResult
        );
        stub_method!(list_outputs, ListOutputsArgs, ListOutputsResult);
        stub_method!(
            relinquish_output,
            RelinquishOutputArgs,
            RelinquishOutputResult
        );

        async fn get_public_key(
            &self,
            args: GetPublicKeyArgs,
            _originator: Option<&str>,
        ) -> Result<GetPublicKeyResult, WalletError> {
            let protocol = args.protocol_id.unwrap_or(WalletProtocol {
                security_level: 0,
                protocol: String::new(),
            });
            let key_id = args.key_id.unwrap_or_default();
            let counterparty = args.counterparty.unwrap_or(Counterparty {
                counterparty_type: CounterpartyType::Uninitialized,
                public_key: None,
            });
            let pk = self.inner.get_public_key_sync(
                &protocol,
                &key_id,
                &counterparty,
                args.for_self.unwrap_or(false),
                args.identity_key,
            )?;
            Ok(GetPublicKeyResult { public_key: pk })
        }

        stub_method!(
            reveal_counterparty_key_linkage,
            RevealCounterpartyKeyLinkageArgs,
            RevealCounterpartyKeyLinkageResult
        );
        stub_method!(
            reveal_specific_key_linkage,
            RevealSpecificKeyLinkageArgs,
            RevealSpecificKeyLinkageResult
        );

        async fn encrypt(
            &self,
            args: EncryptArgs,
            _originator: Option<&str>,
        ) -> Result<EncryptResult, WalletError> {
            let ciphertext = self.inner.encrypt_sync(
                &args.plaintext,
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
            )?;
            Ok(EncryptResult { ciphertext })
        }

        async fn decrypt(
            &self,
            args: DecryptArgs,
            _originator: Option<&str>,
        ) -> Result<DecryptResult, WalletError> {
            let plaintext = self.inner.decrypt_sync(
                &args.ciphertext,
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
            )?;
            Ok(DecryptResult { plaintext })
        }

        async fn create_hmac(
            &self,
            args: CreateHmacArgs,
            _originator: Option<&str>,
        ) -> Result<CreateHmacResult, WalletError> {
            let hmac = self.inner.create_hmac_sync(
                &args.data,
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
            )?;
            Ok(CreateHmacResult { hmac })
        }

        async fn verify_hmac(
            &self,
            args: VerifyHmacArgs,
            _originator: Option<&str>,
        ) -> Result<VerifyHmacResult, WalletError> {
            let valid = self.inner.verify_hmac_sync(
                &args.data,
                &args.hmac,
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
            )?;
            Ok(VerifyHmacResult { valid })
        }

        async fn create_signature(
            &self,
            args: CreateSignatureArgs,
            _originator: Option<&str>,
        ) -> Result<CreateSignatureResult, WalletError> {
            let signature = self.inner.create_signature_sync(
                args.data.as_deref(),
                args.hash_to_directly_sign.as_deref(),
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
            )?;
            Ok(CreateSignatureResult { signature })
        }

        async fn verify_signature(
            &self,
            args: VerifySignatureArgs,
            _originator: Option<&str>,
        ) -> Result<VerifySignatureResult, WalletError> {
            let valid = self.inner.verify_signature_sync(
                args.data.as_deref(),
                args.hash_to_directly_verify.as_deref(),
                &args.signature,
                &args.protocol_id,
                &args.key_id,
                &args.counterparty,
                args.for_self.unwrap_or(false),
            )?;
            Ok(VerifySignatureResult { valid })
        }

        stub_method!(acquire_certificate, AcquireCertificateArgs, Certificate);
        stub_method!(
            list_certificates,
            ListCertificatesArgs,
            ListCertificatesResult
        );
        stub_method!(
            prove_certificate,
            ProveCertificateArgs,
            ProveCertificateResult
        );
        stub_method!(
            relinquish_certificate,
            RelinquishCertificateArgs,
            RelinquishCertificateResult
        );
        stub_method!(
            discover_by_identity_key,
            DiscoverByIdentityKeyArgs,
            DiscoverCertificatesResult
        );
        stub_method!(
            discover_by_attributes,
            DiscoverByAttributesArgs,
            DiscoverCertificatesResult
        );
        stub_method!(is_authenticated, AuthenticatedResult);
        stub_method!(wait_for_authentication, AuthenticatedResult);
        stub_method!(get_height, GetHeightResult);
        stub_method!(get_header_for_height, GetHeaderArgs, GetHeaderResult);
        stub_method!(get_network, GetNetworkResult);
        stub_method!(get_version, GetVersionResult);
    }

    // -----------------------------------------------------------------------
    // MockTransport: in-memory transport that routes between two peers
    // -----------------------------------------------------------------------

    /// A simple mock transport that routes messages to a paired transport.
    /// Each MockTransport has its own incoming channel and sends to its peer's.
    struct MockTransport {
        /// Sender for the peer's incoming channel.
        peer_tx: mpsc::Sender<AuthMessage>,
        /// Our incoming channel receiver (taken once by subscribe()).
        incoming_rx: StdMutex<Option<mpsc::Receiver<AuthMessage>>>,
    }

    /// Create a paired set of mock transports.
    /// Messages sent by transport_a are received by transport_b and vice versa.
    fn create_mock_transport_pair() -> (Arc<MockTransport>, Arc<MockTransport>) {
        let (tx_a, rx_a) = mpsc::channel(32);
        let (tx_b, rx_b) = mpsc::channel(32);

        let transport_a = Arc::new(MockTransport {
            peer_tx: tx_b,
            incoming_rx: StdMutex::new(Some(rx_a)),
        });

        let transport_b = Arc::new(MockTransport {
            peer_tx: tx_a,
            incoming_rx: StdMutex::new(Some(rx_b)),
        });

        (transport_a, transport_b)
    }

    #[async_trait]
    impl Transport for MockTransport {
        async fn send(&self, message: AuthMessage) -> Result<(), AuthError> {
            self.peer_tx
                .send(message)
                .await
                .map_err(|e| AuthError::TransportError(format!("mock send failed: {}", e)))
        }

        fn subscribe(&self) -> mpsc::Receiver<AuthMessage> {
            self.incoming_rx
                .lock()
                .unwrap()
                .take()
                .expect("subscribe() already called on MockTransport")
        }
    }

    // -----------------------------------------------------------------------
    // Integration tests
    // -----------------------------------------------------------------------

    #[tokio::test(flavor = "current_thread")]
    async fn test_full_handshake_and_message_exchange() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                // Create two wallets
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

                // Get identity keys
                let identity_a = wallet_a
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                // Create transport pair
                let (transport_a, transport_b) = create_mock_transport_pair();

                // Create peers
                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                // Set up message receivers before starting
                let mut msg_rx_b = peer_b.on_general_message().unwrap();

                // Step 1: Peer A starts sending (will block waiting for handshake response)
                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"Hello from Peer A!".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });

                // Step 2: Give Peer A time to send the initialRequest
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;

                // Step 3: Peer B processes the initialRequest (sends initialResponse)
                let processed = peer_b.process_pending().await.unwrap();
                assert!(
                    processed > 0,
                    "Peer B should have received the initialRequest"
                );

                // Step 4: Give time for Peer A to receive and process initialResponse
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;

                // Step 5: Get Peer A back (handshake done, general msg sent)
                let peer_a = send_handle.await.unwrap();

                // Step 6: Peer B processes the general message
                let processed = peer_b.process_pending().await.unwrap();
                assert!(
                    processed > 0,
                    "Peer B should have received the general message"
                );

                // Peer B should have received the message on the channel
                let (sender_key, received_payload) = msg_rx_b.try_recv().unwrap();
                assert_eq!(sender_key, identity_a);
                assert_eq!(received_payload, b"Hello from Peer A!");

                // Verify both peers have authenticated sessions
                let sessions_a = peer_a.sessions_for_identity(&identity_b).await;
                assert!(
                    !sessions_a.is_empty(),
                    "Peer A should have a session for Peer B"
                );
                assert!(
                    sessions_a[0].is_authenticated,
                    "Peer A session should be authenticated"
                );

                let sessions_b = peer_b.sessions_for_identity(&identity_a).await;
                assert!(
                    !sessions_b.is_empty(),
                    "Peer B should have a session for Peer A"
                );
                assert!(
                    sessions_b[0].is_authenticated,
                    "Peer B session should be authenticated"
                );
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_cert_request_listener_fires_on_handshake_requested_certs() {
        // When peer A asks peer B for certificates (via
        // set_certificates_to_request -> initialRequest.requestedCertificates),
        // peer B's handle_initial_request fires any registered listener
        // instead of attempting to fetch+include certs itself.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                let (transport_a, transport_b) = create_mock_transport_pair();
                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                // Peer A requests a certificate type from peer B.
                let mut requested = RequestedCertificateSet::default();
                requested.certifiers.push("certifier-key-1".to_string());
                requested.insert("dGVzdA==".to_string(), vec!["name".to_string()]);
                peer_a.set_certificates_to_request(requested);

                // Register a listener on peer B that records invocations.
                let seen = Arc::new(StdMutex::new(
                    Vec::<(String, RequestedCertificateSet)>::new(),
                ));
                let seen_cb = seen.clone();
                peer_b.listen_for_certificates_requested(Arc::new(move |key, req| {
                    seen_cb.lock().unwrap().push((key, req));
                }));

                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"hello".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });

                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                peer_b.process_pending().await.unwrap();
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                let _peer_a = send_handle.await.unwrap();

                let recorded = seen.lock().unwrap();
                assert_eq!(
                    recorded.len(),
                    1,
                    "listener on peer B should fire exactly once during handshake"
                );
                assert_eq!(recorded[0].1.certifiers, vec!["certifier-key-1"]);
                assert!(recorded[0].1.types.contains_key("dGVzdA=="));
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_stop_listening_removes_only_targeted_callback() {
        // Verify stop_listening_for_certificates_requested removes only the
        // named callback. Register two listeners, stop one, handshake with
        // a cert request, and assert only the non-removed listener fires.
        // (This avoids exercising the auto-response path whose wallet
        // stubs would otherwise panic inside process_pending.)
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                let (transport_a, transport_b) = create_mock_transport_pair();
                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                let mut requested = RequestedCertificateSet::default();
                requested.certifiers.push("certifier-key-1".to_string());
                requested.insert("dGVzdA==".to_string(), vec!["name".to_string()]);
                peer_a.set_certificates_to_request(requested);

                let hits_removed = Arc::new(StdMutex::new(0u32));
                let hits_kept = Arc::new(StdMutex::new(0u32));
                let hr = hits_removed.clone();
                let hk = hits_kept.clone();

                let id_removed =
                    peer_b.listen_for_certificates_requested(Arc::new(move |_k, _r| {
                        *hr.lock().unwrap() += 1;
                    }));
                peer_b.listen_for_certificates_requested(Arc::new(move |_k, _r| {
                    *hk.lock().unwrap() += 1;
                }));
                peer_b.stop_listening_for_certificates_requested(id_removed);

                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"hello".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });

                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                peer_b.process_pending().await.unwrap();
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                let _ = send_handle.await.unwrap();

                assert_eq!(
                    *hits_removed.lock().unwrap(),
                    0,
                    "removed listener must not fire"
                );
                assert_eq!(
                    *hits_kept.lock().unwrap(),
                    1,
                    "remaining listener must still fire"
                );
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_cert_request_listener_receives_with_empty_certifiers_skipped() {
        // Guard: TS Peer.ts:512-515 only branches into listener/auto-response
        // when certifiers.len() > 0. Rust must match — otherwise a peer
        // advertising empty certifiers could trigger spurious listener
        // fires. Verified here by sending handshake with empty certifiers
        // and asserting the listener does not fire.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());
                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                let (transport_a, transport_b) = create_mock_transport_pair();
                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                // Empty certifiers means "no cert request" per TS parity.
                let requested = RequestedCertificateSet::default();
                peer_a.set_certificates_to_request(requested);

                let seen = Arc::new(StdMutex::new(0u32));
                let seen_cb = seen.clone();
                peer_b.listen_for_certificates_requested(Arc::new(move |_k, _r| {
                    *seen_cb.lock().unwrap() += 1;
                }));

                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"hello".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });

                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                peer_b.process_pending().await.unwrap();
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                let _ = send_handle.await.unwrap();

                assert_eq!(
                    *seen.lock().unwrap(),
                    0,
                    "listener must not fire when certifiers is empty (TS parity)"
                );
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_send_certificate_response_is_signed() {
        // Regression guard for the TS-parity signing fix: outgoing
        // CertificateResponse must carry a non-empty `signature`.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                // Build a one-way transport that captures what peer A sends
                // so we can inspect the CertificateResponse wire message.
                let (transport_a, transport_b) = create_mock_transport_pair();
                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                // Handshake via send_message so both sides end up with
                // authenticated sessions.
                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"setup".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                peer_b.process_pending().await.unwrap();
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                let peer_a = send_handle.await.unwrap();
                peer_b.process_pending().await.unwrap(); // absorb the general msg

                // Now peer A explicitly sends an empty-cert-list response to B.
                peer_a
                    .send_certificate_response(&identity_b, Vec::new())
                    .await
                    .unwrap();

                // Peer B's transport should have received a signed
                // CertificateResponse. Intercept by draining the incoming
                // channel directly.
                let mut rx = peer_b
                    .take_transport_rx()
                    .await
                    .expect("transport_rx available");
                let msg = tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv())
                    .await
                    .expect("transport recv timed out")
                    .expect("transport channel closed");

                assert_eq!(msg.message_type, MessageType::CertificateResponse);
                assert!(msg.nonce.is_some(), "request nonce must be populated");
                assert!(
                    msg.signature
                        .as_ref()
                        .map(|s| !s.is_empty())
                        .unwrap_or(false),
                    "CertificateResponse must carry a non-empty signature (TS parity)"
                );
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_handshake_creates_sessions_for_both_peers() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
                let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

                let identity_b = wallet_b
                    .get_public_key(
                        GetPublicKeyArgs {
                            identity_key: true,
                            protocol_id: None,
                            key_id: None,
                            counterparty: None,
                            privileged: false,
                            privileged_reason: None,
                            for_self: None,
                            seek_permission: None,
                        },
                        None,
                    )
                    .await
                    .unwrap()
                    .public_key
                    .to_der_hex();

                let (transport_a, transport_b) = create_mock_transport_pair();

                let peer_a = Peer::new(wallet_a, transport_a);
                let peer_b = Peer::new(wallet_b, transport_b);

                // Interleaved handshake
                let identity_b_clone = identity_b.clone();
                let send_handle = tokio::task::spawn_local(async move {
                    peer_a
                        .send_message(&identity_b_clone, b"test".to_vec())
                        .await
                        .unwrap();
                    peer_a
                });

                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                peer_b.process_pending().await.unwrap();
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;

                let peer_a = send_handle.await.unwrap();

                // Peer A should have a session for Peer B
                assert!(
                    peer_a.session_by_identifier(&identity_b).await.is_some(),
                    "Peer A should track Peer B session"
                );
            })
            .await;
    }

    /// Concurrency regression: N general messages on ONE authenticated session
    /// must all verify via the lock-free `&self` hot path on an `Arc<Peer>`,
    /// concurrently, without touching the transport or process_pending.
    ///
    /// This is the server-middleware shape: the responder (peer B) holds an
    /// `Arc<Peer>` and fans out `verify_general_message` across many in-flight
    /// requests bound to the same session. Proves SessionManager's `RwLock`
    /// allows concurrent reads and that verify has no `&mut self` requirement.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_concurrent_general_message_verify_one_session() {
        let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
        let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

        let identity_b = wallet_b
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await
            .unwrap()
            .public_key
            .to_der_hex();

        let (transport_a, transport_b) = create_mock_transport_pair();
        let peer_a = Peer::new(wallet_a, transport_a);
        let peer_b = Peer::new(wallet_b, transport_b);

        // Drive the handshake A -> B so peer B holds an authenticated session
        // for A. peer_a.send_message blocks on the initialResponse, so pump
        // peer_b's dispatch concurrently.
        let identity_b_clone = identity_b.clone();
        let send_handle = tokio::spawn(async move {
            peer_a
                .send_message(&identity_b_clone, b"handshake".to_vec())
                .await
                .unwrap();
            peer_a
        });

        // Pump peer B until it has an authenticated session for A.
        let peer_a = loop {
            peer_b.process_pending().await.unwrap();
            if send_handle.is_finished() {
                break send_handle.await.unwrap();
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        };
        // Absorb the trailing general message from the handshake send.
        peer_b.process_pending().await.unwrap();

        // Build N signed general messages from A bound to the same session.
        // Each carries your_nonce = B's session_nonce, which B verifies
        // against on the inbound hot path.
        let n = 16usize;
        let mut messages = Vec::with_capacity(n);
        for i in 0..n {
            let payload = format!("concurrent-msg-{i}").into_bytes();
            let msg = peer_a
                .create_general_message(&identity_b, payload)
                .await
                .expect("create_general_message");
            messages.push(msg);
        }

        // Wrap B in Arc and verify all N concurrently via the &self hot path.
        let peer_b_arc = Arc::new(peer_b);
        let mut handles = Vec::with_capacity(n);
        for msg in messages {
            let pb = peer_b_arc.clone();
            handles.push(tokio::spawn(
                async move { pb.verify_general_message(msg).await },
            ));
        }

        for h in handles {
            h.await.unwrap().expect("concurrent verify must succeed");
        }
    }

    /// Full interior-mutability proof: a SINGLE `Arc<Peer>` services a live
    /// handshake (responder side — `&self` `process_pending` driving
    /// `handle_initial_request`, which takes the internal `handshake` mutex
    /// and a `SessionManager` *write* lock) AND, interleaved on the very same
    /// `Arc`, a fan-out of concurrent `verify_general_message` calls (lock-free
    /// against the handshake mutex, `SessionManager` *read* lock only) — all
    /// WITHOUT any outer `Mutex<Peer>`.
    ///
    /// This is the server-middleware shape end-to-end. To interleave a genuine
    /// B-side handshake-handler invocation with the verifies on ONE Arc, the
    /// client A sends a SECOND `initialRequest` (over the same transport B is
    /// subscribed to) right as the verify fan-out is launched: B's pump
    /// dispatches `handle_initial_request` for that second request while the
    /// verify tasks run. If the handshake mutex blocked the verify hot path,
    /// or if any handler still required `&mut self`, this would not compile or
    /// would deadlock/serialize.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_handshake_and_concurrent_verify_on_one_arc_peer() {
        let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
        let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

        let identity_b = wallet_b
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await
            .unwrap()
            .public_key
            .to_der_hex();

        let (transport_a, transport_b) = create_mock_transport_pair();
        // A is wrapped in an Arc<Peer> too, proving send_message is &self.
        let peer_a = Arc::new(Peer::new(wallet_a, transport_a));
        let peer_b = Arc::new(Peer::new(wallet_b, transport_b));

        // 1. Establish A -> B session. send_message (&self on Arc<Peer>) blocks
        //    on the initialResponse, so pump B concurrently.
        let pa = peer_a.clone();
        let id_b = identity_b.clone();
        let send_handle =
            tokio::spawn(async move { pa.send_message(&id_b, b"handshake".to_vec()).await });

        let peer_b_pump = peer_b.clone();
        loop {
            peer_b_pump.process_pending().await.unwrap();
            if send_handle.is_finished() {
                send_handle.await.unwrap().unwrap();
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        peer_b.process_pending().await.unwrap(); // absorb trailing general msg

        // 2. Build N signed general messages from A bound to B's session.
        let n = 16usize;
        let mut messages = Vec::with_capacity(n);
        for i in 0..n {
            let payload = format!("interleaved-msg-{i}").into_bytes();
            let msg = peer_a
                .create_general_message(&identity_b, payload)
                .await
                .expect("create_general_message");
            messages.push(msg);
        }

        // 3. Have A initiate a SECOND handshake (fresh session_nonce) into B's
        //    transport. This blocks awaiting B's initialResponse; what matters
        //    is that B's pump will dispatch `handle_initial_request` for it,
        //    interleaving a &self handshake handler (SessionManager WRITE lock)
        //    with the verify fan-out (SessionManager READ locks) on one Arc.
        let pa2 = peer_a.clone();
        let id_b2 = identity_b.clone();
        let second_handshake = tokio::spawn(async move {
            let _ = tokio::time::timeout(
                std::time::Duration::from_millis(500),
                pa2.send_message(&id_b2, b"handshake-2".to_vec()),
            )
            .await;
        });

        // 4. Concurrently: B pumps its transport (servicing the inbound second
        //    initialRequest -> handle_initial_request) WHILE the verify fan-out
        //    runs against the same Arc<Peer> B. No outer mutex anywhere.
        let pump = {
            let pb = peer_b.clone();
            tokio::spawn(async move {
                for _ in 0..40 {
                    pb.process_pending().await.unwrap();
                    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
                }
            })
        };

        let mut handles = Vec::with_capacity(n);
        for msg in messages {
            let pb = peer_b.clone();
            handles.push(tokio::spawn(
                async move { pb.verify_general_message(msg).await },
            ));
        }

        for h in handles {
            h.await
                .unwrap()
                .expect("concurrent verify must succeed during a live handshake");
        }

        pump.await.unwrap();
        let _ = second_handshake.await;

        // Sanity: A still tracks its (first) authenticated session to B after
        // all the interleaved activity.
        let session = peer_a.session_by_identifier(&identity_b).await;
        assert!(
            session.map(|s| s.is_authenticated).unwrap_or(false),
            "A must still hold an authenticated session to B after interleaving"
        );
    }

    /// Drive an A -> B handshake and return `(peer_a, Arc<peer_b>, identity_b)`
    /// with B holding an authenticated session for A. Shared setup for the
    /// anti-replay tests.
    async fn authenticated_pair() -> (Peer<TestWallet>, Arc<Peer<TestWallet>>, String) {
        let wallet_a = TestWallet::new(PrivateKey::from_random().unwrap());
        let wallet_b = TestWallet::new(PrivateKey::from_random().unwrap());

        let identity_b = wallet_b
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await
            .unwrap()
            .public_key
            .to_der_hex();

        let (transport_a, transport_b) = create_mock_transport_pair();
        let peer_a = Peer::new(wallet_a, transport_a);
        let peer_b = Peer::new(wallet_b, transport_b);

        let identity_b_clone = identity_b.clone();
        let send_handle = tokio::spawn(async move {
            peer_a
                .send_message(&identity_b_clone, b"handshake".to_vec())
                .await
                .unwrap();
            peer_a
        });

        let peer_a = loop {
            peer_b.process_pending().await.unwrap();
            if send_handle.is_finished() {
                break send_handle.await.unwrap();
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        };
        // Absorb the trailing general message from the handshake send.
        peer_b.process_pending().await.unwrap();

        (peer_a, Arc::new(peer_b), identity_b)
    }

    /// Item 1: a captured authenticated message replays are REJECTED (the
    /// verified defect at 0.2.87), while a genuinely fresh message still passes.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_general_message_replay_is_rejected() {
        let (peer_a, peer_b, identity_b) = authenticated_pair().await;

        // Capture ONE signed general message (fixed per-message nonce).
        let captured = peer_a
            .create_general_message(&identity_b, b"transfer 100".to_vec())
            .await
            .expect("create_general_message");

        // First delivery: accepted.
        peer_b
            .verify_general_message(captured.clone())
            .await
            .expect("first (fresh) delivery must be accepted");

        // Replay of the identical captured bytes: rejected as a replay.
        let replay = peer_b.verify_general_message(captured.clone()).await;
        assert!(
            matches!(replay, Err(AuthError::ReplayDetected(_))),
            "captured message replay must be rejected, got: {:?}",
            replay
        );

        // A genuinely fresh message (new per-message nonce) still passes — the
        // happy path is preserved.
        let fresh = peer_a
            .create_general_message(&identity_b, b"transfer 100".to_vec())
            .await
            .expect("create_general_message");
        peer_b
            .verify_general_message(fresh)
            .await
            .expect("a fresh-nonce message must still be accepted");
    }

    /// Item 4: N concurrent verifies of the SAME captured message must not
    /// deadlock or serialize, and the atomic check-and-insert must admit exactly
    /// ONE and reject the other N-1 as replays.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_concurrent_identical_replays_admit_exactly_one() {
        let (peer_a, peer_b, identity_b) = authenticated_pair().await;

        let captured = peer_a
            .create_general_message(&identity_b, b"double-spend me".to_vec())
            .await
            .expect("create_general_message");

        let n = 16usize;
        let mut handles = Vec::with_capacity(n);
        for _ in 0..n {
            let pb = peer_b.clone();
            let msg = captured.clone();
            handles.push(tokio::spawn(
                async move { pb.verify_general_message(msg).await },
            ));
        }

        let mut accepted = 0usize;
        let mut replayed = 0usize;
        for h in handles {
            match h.await.expect("verify task must not panic/deadlock") {
                Ok(()) => accepted += 1,
                Err(AuthError::ReplayDetected(_)) => replayed += 1,
                Err(other) => panic!("unexpected error under concurrent replay: {:?}", other),
            }
        }

        assert_eq!(accepted, 1, "exactly one concurrent delivery must be accepted");
        assert_eq!(replayed, n - 1, "all other concurrent deliveries must be replays");
    }
}