zebra-network 15.0.0

Networking code for Zebra
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
//! Fixed test vectors for peer connections.
//!
//! TODO: add tests for:
//!   - inbound message as request
//!   - inbound message, but not a request (or a response)

use std::{
    collections::{HashMap, HashSet},
    sync::{atomic::Ordering, Arc, Mutex},
    task::Poll,
    time::{Duration, Instant},
};

use futures::{
    channel::{mpsc, oneshot},
    sink::SinkMapErr,
    FutureExt, SinkExt, StreamExt,
};
use metrics::{
    atomics::AtomicU64, Counter, Gauge, Histogram, Key, KeyName, Metadata, Recorder, SharedString,
    Unit,
};
use tower::load_shed::error::Overloaded;
use tracing::Span;

use zebra_chain::{
    block::{self, Block},
    serialization::{SerializationError, ZcashDeserializeInto},
    transaction::UnminedTx,
};
use zebra_test::mock_service::{MockService, PanicAssertion};

use crate::{
    constants::{MAX_OVERLOAD_DROP_PROBABILITY, MIN_OVERLOAD_DROP_PROBABILITY, REQUEST_TIMEOUT},
    peer::{
        connection::{overload_drop_connection_probability, Connection, Handler, State},
        ClientRequest, ErrorSlot,
    },
    protocol::{
        external::{InventoryHash, Message},
        internal::InventoryResponse,
    },
    types::Nonce,
    PeerError, Request, Response,
};

#[derive(Default)]
struct ConnectionMetricsRecorder {
    counters: Mutex<HashMap<Key, Arc<AtomicU64>>>,
    gauges: Mutex<HashMap<String, Arc<AtomicU64>>>,
}

impl ConnectionMetricsRecorder {
    fn counter(&self, key: Key) -> u64 {
        self.counters
            .lock()
            .expect("test recorder mutex is unpoisoned")
            .get(&key)
            .map_or(0, |value| value.load(Ordering::Relaxed))
    }

    fn state(&self, command: &str) -> f64 {
        let gauges = self
            .gauges
            .lock()
            .expect("test recorder mutex is unpoisoned");
        f64::from_bits(
            gauges
                .get(command)
                .expect("the connection recorded this state")
                .load(Ordering::Relaxed),
        )
    }
}

impl Recorder for ConnectionMetricsRecorder {
    fn describe_counter(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}

    fn describe_gauge(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}

    fn describe_histogram(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}

    fn register_counter(&self, key: &Key, _metadata: &Metadata<'_>) -> Counter {
        Counter::from_arc(
            self.counters
                .lock()
                .expect("test recorder mutex is unpoisoned")
                .entry(key.clone())
                .or_default()
                .clone(),
        )
    }

    fn register_gauge(&self, key: &Key, _metadata: &Metadata<'_>) -> Gauge {
        if key.name() != "zebra.net.connection.state" {
            return Gauge::noop();
        }

        let mut labels = key.labels();
        let command = labels.next().expect("connection state has a command label");
        assert_eq!(command.key(), "command");
        assert!(
            labels.next().is_none(),
            "state must not have per-peer labels"
        );
        let mut gauges = self
            .gauges
            .lock()
            .expect("test recorder mutex is unpoisoned");
        Gauge::from_arc(
            gauges
                .entry(command.value().to_owned())
                .or_default()
                .clone(),
        )
    }

    fn register_histogram(&self, _key: &Key, _metadata: &Metadata<'_>) -> Histogram {
        Histogram::noop()
    }
}

/// Aggregate gauges count concurrent peers and return to zero after transitions and disconnects.
#[tokio::test]
async fn connection_state_metrics_return_to_zero() {
    let _init_guard = zebra_test::init();
    let recorder = ConnectionMetricsRecorder::default();
    let mut series_count = None;

    metrics::with_local_recorder(&recorder, || {
        for cycle in 0..8 {
            let (first, mut client_tx, _service, mut outbound_messages, _error_slot) =
                new_test_connection();
            let (second, _idle_client_tx, _idle_service, _idle_messages, _idle_error_slot) =
                new_test_connection();
            let (mut peer_tx, peer_rx) = mpsc::channel(1);
            let (mut idle_peer_tx, idle_peer_rx) = mpsc::channel(1);
            let first = first.run(peer_rx).shared();
            let second = second.run(idle_peer_rx).shared();

            assert_eq!(first.clone().now_or_never(), None);
            assert_eq!(second.clone().now_or_never(), None);
            assert_eq!(recorder.state("AwaitingRequest"), 2.0);

            // Polling an unchanged state must not count the same connection twice.
            assert_eq!(first.clone().now_or_never(), None);
            assert_eq!(recorder.state("AwaitingRequest"), 2.0);

            let (response_tx, mut response_rx) = oneshot::channel();
            client_tx
                .try_send(ClientRequest {
                    request: Request::Peers,
                    tx: response_tx,
                    inv_collector: None,
                    transient_addr: None,
                    span: Span::none(),
                })
                .expect("the connection is listening for client requests");
            assert_eq!(first.clone().now_or_never(), None);
            assert_eq!(
                outbound_messages.try_recv().expect("the request was sent"),
                Message::GetAddr,
            );
            assert_eq!(first.clone().now_or_never(), None);
            assert_eq!(recorder.state("AwaitingRequest"), 1.0);
            assert_eq!(recorder.state("AwaitingResponse(Peers)"), 1.0);

            peer_tx
                .try_send(Ok(Message::Addr(Vec::new())))
                .expect("the connection is listening for peer messages");
            assert_eq!(first.clone().now_or_never(), None);
            assert_eq!(
                response_rx
                    .try_recv()
                    .expect("the response channel is open")
                    .expect("the response was sent")
                    .expect("the peer returned a valid response"),
                Response::Peers(Vec::new()),
            );
            assert_eq!(recorder.state("AwaitingRequest"), 2.0);
            assert_eq!(recorder.state("AwaitingResponse(Peers)"), 0.0);

            // Exercise both normal disconnects and cancellation of a live connection.
            if cycle % 2 == 0 {
                peer_tx.close_channel();
                assert_eq!(first.clone().now_or_never(), Some(()));
            }
            drop(first);
            assert_eq!(recorder.state("AwaitingRequest"), 1.0);

            // Distinct transport error messages must not create distinct state series.
            idle_peer_tx
                .try_send(Err(
                    std::io::Error::other(format!("peer failure {cycle}")).into()
                ))
                .expect("the idle connection is listening for peer messages");
            assert_eq!(second.clone().now_or_never(), Some(()));
            drop(second);
            drop(new_test_connection().0);

            let gauges = recorder
                .gauges
                .lock()
                .expect("test recorder mutex is unpoisoned");
            assert!(gauges
                .values()
                .all(|value| f64::from_bits(value.load(Ordering::Relaxed)) == 0.0));
            assert_eq!(*series_count.get_or_insert(gauges.len()), gauges.len());
        }
    });
}

#[test]
fn connection_state_commands_omit_serialization_details() {
    for detail in ["first peer failure", "second peer failure"] {
        let handler = Handler::Finished(Err(PeerError::Serialization(
            std::io::Error::other(detail).into(),
        )));
        assert_eq!(handler.command(), "Finished(Serialization)");
        assert!(
            handler.to_string().contains(detail),
            "logs retain error details",
        );
    }
}

/// Test that the connection run loop works as a future
#[tokio::test]
async fn connection_run_loop_ok() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    let connection = connection.run(peer_rx);

    // The run loop will wait forever for a request from Zebra or the peer,
    // without any errors, channel closes, or bytes written.
    //
    // But the connection closes if we drop the future, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    assert_eq!(result, None);

    let error = shared_error_slot.try_get_error();
    assert!(error.is_none(), "unexpected error: {error:?}");

    assert!(!client_tx.is_closed());
    assert!(!peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop works as a spawned task
#[tokio::test]
async fn connection_run_loop_spawn_ok() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    // Spawn the connection run loop
    let mut connection_join_handle = tokio::spawn(connection.run(peer_rx));

    let error = shared_error_slot.try_get_error();
    assert!(error.is_none(), "unexpected error: {error:?}");

    assert!(!client_tx.is_closed());
    assert!(!peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // Make sure that the connection did not:
    // - panic, or
    // - return.
    //
    // This test doesn't cause any fatal errors,
    // so returning would be incorrect behaviour.
    let connection_result = futures::poll!(&mut connection_join_handle);
    assert!(
        matches!(connection_result, Poll::Pending),
        "unexpected run loop termination: {connection_result:?}",
    );

    // We need to abort the connection, because it holds a lock on the outbound channel.
    connection_join_handle.abort();
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop works as a spawned task with messages in and out
#[tokio::test]
async fn connection_run_loop_message_ok() {
    let _init_guard = zebra_test::init();

    tokio::time::pause();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (mut peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Spawn the connection run loop
    let mut connection_join_handle = tokio::spawn(connection.run(peer_rx));

    // Simulate a message send and receive
    let (request_tx, mut request_rx) = oneshot::channel();
    let request = ClientRequest {
        request: Request::Peers,
        tx: request_tx,
        inv_collector: None,
        transient_addr: None,
        span: Span::current(),
    };

    client_tx
        .try_send(request)
        .expect("internal request channel is valid");
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, Some(Message::GetAddr));

    peer_tx
        .try_send(Ok(Message::Addr(Vec::new())))
        .expect("peer inbound response channel is valid");

    // give the event loop time to run
    tokio::task::yield_now().await;
    let peer_response = request_rx.try_recv();
    assert_eq!(
        peer_response
            .expect("peer internal response channel is valid")
            .expect("response is present")
            .expect("response is a message (not an error)"),
        Response::Peers(Vec::new()),
    );

    let error = shared_error_slot.try_get_error();
    assert!(error.is_none(), "unexpected error: {error:?}");

    assert!(!client_tx.is_closed());
    assert!(!peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // Make sure that the connection did not:
    // - panic, or
    // - return.
    //
    // This test doesn't cause any fatal errors,
    // so returning would be incorrect behaviour.
    let connection_result = futures::poll!(&mut connection_join_handle);
    assert!(
        matches!(connection_result, Poll::Pending),
        "unexpected run loop termination: {connection_result:?}",
    );

    // We need to abort the connection, because it holds a lock on the outbound channel.
    connection_join_handle.abort();
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Public clients can send maintenance requests without panicking or writing to the peer.
#[tokio::test(start_paused = true)]
async fn client_poll_peer_set_returns_nil() {
    use tower::{Service, ServiceExt};

    let _init_guard = zebra_test::init();
    let (connection, client_tx, _inbound_service, mut outbound, error_slot) = new_test_connection();
    let (mut client, _harness) = crate::peer::ClientTestHarness::build().finish();
    client.server_tx = client_tx;
    client.error_slot = error_slot.clone();
    let connection_task = tokio::spawn(connection.run(futures::stream::pending()));

    let response = tokio::time::timeout(Duration::from_secs(1), async {
        client
            .ready()
            .await
            .unwrap()
            .call(Request::PollPeerSet)
            .await
    })
    .await
    .expect("maintenance requests must finish without a peer response")
    .expect("maintenance requests must succeed");
    assert_eq!(response, Response::Nil);
    assert!(outbound.next().now_or_never().is_none());
    assert!(error_slot.try_get_error().is_none());

    connection_task.abort();
    assert!(connection_task.await.unwrap_err().is_cancelled());
}

/// An empty mempool reply releases the connection before the request timeout.
#[tokio::test(start_paused = true)]
async fn empty_mempool_reply_unblocks_queued_block_request() {
    let _init_guard = zebra_test::init();
    let (mut peer_tx, peer_rx) = mpsc::channel(1);
    let (connection, mut client_tx, _inbound_service, mut outbound, error_slot) =
        new_test_connection();
    let connection_task = tokio::spawn(connection.run(peer_rx));

    let (mempool_tx, mempool_rx) = oneshot::channel();
    client_tx
        .try_send(ClientRequest {
            request: Request::MempoolTransactionIds,
            tx: mempool_tx,
            inv_collector: None,
            transient_addr: None,
            span: Span::current(),
        })
        .unwrap();
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(1), outbound.next())
            .await
            .unwrap(),
        Some(Message::Mempool),
    );

    let hash = zebra_chain::block::Hash([1; 32]);
    let (block_tx, block_rx) = oneshot::channel();
    client_tx
        .try_send(ClientRequest {
            request: Request::BlockDownload {
                hash,
                advertiser: None,
            },
            tx: block_tx,
            inv_collector: None,
            transient_addr: None,
            span: Span::current(),
        })
        .unwrap();
    assert!(outbound.next().now_or_never().is_none());

    peer_tx.send(Ok(Message::Inv(Vec::new()))).await.unwrap();
    tokio::time::timeout(Duration::from_secs(1), async {
        assert_eq!(
            mempool_rx.await.unwrap().unwrap(),
            Response::TransactionIds(Vec::new()),
        );
        assert_eq!(
            outbound.next().await,
            Some(Message::GetData(vec![InventoryHash::Block(hash)])),
        );
    })
    .await
    .expect("an empty mempool reply must release the queued block request without a timeout");

    assert!(error_slot.try_get_error().is_none());
    drop(block_rx);
    connection_task.abort();
    assert!(connection_task.await.unwrap_err().is_cancelled());
}

/// A late empty mempool reply must not finish a later block-locator request.
#[tokio::test(start_paused = true)]
async fn cancelled_mempool_reply_does_not_complete_find_blocks() {
    let _init_guard = zebra_test::init();
    let (mut peer_tx, peer_rx) = mpsc::channel(1);
    let (connection, mut client_tx, _inbound_service, mut outbound, error_slot) =
        new_test_connection();
    let connection_task = tokio::spawn(connection.run(peer_rx));

    let (mempool_tx, mempool_rx) = oneshot::channel();
    client_tx
        .try_send(ClientRequest {
            request: Request::MempoolTransactionIds,
            tx: mempool_tx,
            inv_collector: None,
            transient_addr: None,
            span: Span::current(),
        })
        .unwrap();
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(1), outbound.next())
            .await
            .unwrap(),
        Some(Message::Mempool),
    );
    drop(mempool_rx);

    let (find_tx, mut find_rx) = oneshot::channel();
    client_tx
        .send(ClientRequest {
            request: Request::FindBlocks {
                known_blocks: Vec::new(),
                stop: None,
            },
            tx: find_tx,
            inv_collector: None,
            transient_addr: None,
            span: Span::current(),
        })
        .await
        .unwrap();
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(1), outbound.next())
            .await
            .unwrap(),
        Some(Message::GetBlocks {
            known_blocks: Vec::new(),
            stop: None,
        }),
    );

    peer_tx.send(Ok(Message::Inv(Vec::new()))).await.unwrap();
    assert!(
        tokio::time::timeout(Duration::from_secs(1), &mut find_rx)
            .await
            .is_err(),
        "the late empty mempool reply must leave the block-locator request pending",
    );

    let hashes = vec![
        zebra_chain::block::Hash([1; 32]),
        zebra_chain::block::Hash([2; 32]),
    ];
    peer_tx
        .send(Ok(Message::Inv(
            hashes.iter().copied().map(InventoryHash::Block).collect(),
        )))
        .await
        .unwrap();
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(1), find_rx)
            .await
            .unwrap()
            .unwrap()
            .unwrap(),
        Response::BlockHashes(hashes),
    );

    assert!(error_slot.try_get_error().is_none());
    connection_task.abort();
    assert!(connection_task.await.unwrap_err().is_cancelled());
}

/// An empty `getblocks` result sends nothing, so peers can't take it for an empty mempool reply,
/// while a nonempty result is still sent as an inventory.
#[tokio::test(start_paused = true)]
async fn empty_find_blocks_result_sends_no_inventory() {
    let _init_guard = zebra_test::init();
    let (mut peer_tx, peer_rx) = mpsc::channel(1);
    let (connection, _client_tx, mut inbound_service, mut outbound, error_slot) =
        new_test_connection();
    let connection_task = tokio::spawn(connection.run(peer_rx));
    let get_blocks = Message::GetBlocks {
        known_blocks: Vec::new(),
        stop: None,
    };
    let find_blocks = Request::FindBlocks {
        known_blocks: Vec::new(),
        stop: None,
    };

    peer_tx.send(Ok(get_blocks.clone())).await.unwrap();
    inbound_service
        .expect_request(find_blocks.clone())
        .await
        .respond(Response::BlockHashes(Vec::new()));
    assert!(
        tokio::time::timeout(Duration::from_secs(1), outbound.next())
            .await
            .is_err(),
        "an empty getblocks result must not be sent as an empty inventory",
    );

    let hash = zebra_chain::block::Hash([1; 32]);
    peer_tx.send(Ok(get_blocks)).await.unwrap();
    inbound_service
        .expect_request(find_blocks)
        .await
        .respond(Response::BlockHashes(vec![hash]));
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(1), outbound.next())
            .await
            .unwrap(),
        Some(Message::Inv(vec![InventoryHash::Block(hash)])),
    );

    assert!(error_slot.try_get_error().is_none());
    connection_task.abort();
    assert!(connection_task.await.unwrap_err().is_cancelled());
}

/// Dedicated block adverts preserve the ordinary request counter and cancellation labels.
#[test]
fn block_advert_request_metrics_include_cancellation() {
    let (runtime, _init_guard) = zebra_test::init_async();
    let recorder = ConnectionMetricsRecorder::default();

    metrics::with_local_recorder(&recorder, || {
        runtime.block_on(async {
            tokio::time::pause();
            tokio::time::timeout(Duration::from_secs(1), async {
                let (mut connection, _client_tx, _service, mut outbound_messages, _error_slot) =
                    new_test_connection();
                let hash = block::Hash([1; 32]);
                let (result, delivery) = tokio::sync::oneshot::channel();
                let (_, message) = tokio::join!(
                    connection.send_block_advert(crate::peer_set::BlockAdvert { hash, result }),
                    outbound_messages.next(),
                );
                assert_eq!(
                    message,
                    Some(Message::Inv(vec![InventoryHash::Block(hash)]))
                );
                delivery
                    .await
                    .expect("the completed write sends an acknowledgement")
                    .expect("the connected test transport accepts the advert");

                let (result, delivery) = tokio::sync::oneshot::channel();
                drop(delivery);
                connection
                    .send_block_advert(crate::peer_set::BlockAdvert { hash, result })
                    .await;
                assert!(outbound_messages.try_recv().is_err());

                assert_eq!(
                    recorder.counter(Key::from_parts(
                        "zebra.net.out.requests",
                        &[("command", Request::AdvertiseBlock(hash, None).command())],
                    )),
                    1,
                );
                assert_eq!(
                    recorder.counter(Key::from_parts(
                        "zebra.net.out.requests.canceled",
                        &[("command", Request::AdvertiseBlockToAll(hash).command())],
                    )),
                    1,
                );
                assert_eq!(recorder.counter(Key::from_name("peer.canceled")), 1);
            })
            .await
            .expect("the local transport and canceled advert complete without remote responses");
        });
    });
}
/// Block adverts bypass pending responses without replacing their handlers or closing the client.
#[tokio::test]
async fn block_advert_while_awaiting_response() {
    let _init_guard = zebra_test::init();
    tokio::time::pause();

    tokio::time::timeout(Duration::from_secs(1), async {
        let (mut peer_tx, peer_rx) = mpsc::channel(1);
        let (
            mut connection,
            mut client_tx,
            _inbound_service,
            mut peer_outbound_messages,
            shared_error_slot,
        ) = new_test_connection();
        let (block_advert_tx, block_advert_rx) = tokio::sync::mpsc::channel(4);
        connection.block_advert_rx = block_advert_rx;
        let connection_task = tokio::spawn(connection.run(peer_rx));

        // Exercise the idle path before leaving an address request awaiting its response.
        let idle_hash = block::Hash([1; 32]);
        let (result, idle_delivery) = tokio::sync::oneshot::channel();
        block_advert_tx
            .try_send(crate::peer_set::BlockAdvert {
                hash: idle_hash,
                result,
            })
            .unwrap();
        assert_eq!(
            peer_outbound_messages.next().await,
            Some(Message::Inv(vec![InventoryHash::Block(idle_hash)]))
        );
        idle_delivery.await.unwrap().unwrap();

        let (request_tx, mut request_rx) = oneshot::channel();
        client_tx
            .try_send(ClientRequest {
                request: Request::Peers,
                tx: request_tx,
                inv_collector: None,
                transient_addr: None,
                span: Span::current(),
            })
            .unwrap();
        assert_eq!(peer_outbound_messages.next().await, Some(Message::GetAddr));

        let busy_hash = block::Hash([2; 32]);
        let (result, busy_delivery) = tokio::sync::oneshot::channel();
        block_advert_tx
            .try_send(crate::peer_set::BlockAdvert {
                hash: busy_hash,
                result,
            })
            .unwrap();
        assert_eq!(
            peer_outbound_messages.next().await,
            Some(Message::Inv(vec![InventoryHash::Block(busy_hash)]))
        );
        busy_delivery.await.unwrap().unwrap();
        assert!(request_rx.try_recv().unwrap().is_none());

        // Closing only the advert channel must leave the original request alive.
        drop(block_advert_tx);
        peer_tx.try_send(Ok(Message::Addr(Vec::new()))).unwrap();
        assert_eq!(
            request_rx.await.unwrap().unwrap(),
            Response::Peers(Vec::new())
        );
        assert!(shared_error_slot.try_get_error().is_none());

        drop(client_tx);
        connection_task.await.unwrap();
    })
    .await
    .expect("adverts and the original response finish before the request timeout");
}

/// A pending GetBlocks response must not be displaced by a simultaneous unsolicited advert.
#[tokio::test]
async fn getblocks_response_precedes_ready_block_advert() {
    let _init_guard = zebra_test::init();
    tokio::time::pause();

    tokio::time::timeout(Duration::from_secs(1), async {
        let (mut peer_tx, peer_rx) = mpsc::channel(1);
        let (
            mut connection,
            client_tx,
            mut inbound_service,
            mut peer_outbound_messages,
            shared_error_slot,
        ) = new_test_connection();
        let (block_advert_tx, block_advert_rx) = tokio::sync::mpsc::channel(4);
        connection.block_advert_rx = block_advert_rx;
        let response_hash = block::Hash([3; 32]);
        let advert_hash = block::Hash([4; 32]);

        // Queue both inputs before starting the loop, making selection order deterministic.
        peer_tx
            .try_send(Ok(Message::GetBlocks {
                known_blocks: Vec::new(),
                stop: None,
            }))
            .unwrap();
        let (result, _delivery) = tokio::sync::oneshot::channel();
        block_advert_tx
            .try_send(crate::peer_set::BlockAdvert {
                hash: advert_hash,
                result,
            })
            .unwrap();
        let connection_task = tokio::spawn(connection.run(peer_rx));

        tokio::join!(
            async {
                inbound_service
                    .expect_request(Request::FindBlocks {
                        known_blocks: Vec::new(),
                        stop: None,
                    })
                    .await
                    .respond(Response::BlockHashes(vec![response_hash]));
            },
            async {
                assert_eq!(
                    peer_outbound_messages.next().await,
                    Some(Message::Inv(vec![InventoryHash::Block(response_hash)]))
                );
                assert_eq!(
                    peer_outbound_messages.next().await,
                    Some(Message::Inv(vec![InventoryHash::Block(advert_hash)]))
                );
            }
        );
        assert!(shared_error_slot.try_get_error().is_none());

        drop(client_tx);
        connection_task.await.unwrap();
    })
    .await
    .expect("the response and advert are both delivered");
}

/// Test that the connection run loop fails correctly when dropped
#[tokio::test]
async fn connection_run_loop_future_drop() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    let connection = connection.run(peer_rx);

    // now_or_never implicitly drops the connection future.
    let result = connection.now_or_never();
    assert_eq!(result, None);

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ConnectionDropped",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when the internal client closes the connection channel
#[tokio::test]
async fn connection_run_loop_client_close() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    let connection = connection.run(peer_rx);

    // Explicitly close the client channel.
    client_tx.close_channel();

    // If we drop the future, the connection will close anyway, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    assert_eq!(result, Some(()));

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ClientDropped",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when the internal client drops the connection channel
#[tokio::test]
async fn connection_run_loop_client_drop() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    let connection = connection.run(peer_rx);

    // Drop the client channel.
    std::mem::drop(client_tx);

    // If we drop the future, the connection will close anyway, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    assert_eq!(result, Some(()));

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ClientDropped",
    );

    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when the peer channel is closed.
/// (We're not sure if tokio closes or drops the TcpStream when the TCP connection closes.)
#[tokio::test]
async fn connection_run_loop_inbound_close() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (mut peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    let connection = connection.run(peer_rx);

    // Explicitly close the inbound peer channel.
    peer_tx.close_channel();

    // If we drop the future, the connection will close anyway, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    assert_eq!(result, Some(()));

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ConnectionClosed",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when the peer channel is dropped
/// (We're not sure if tokio closes or drops the TcpStream when the TCP connection closes.)
#[tokio::test]
async fn connection_run_loop_inbound_drop() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (connection, client_tx, mut inbound_service, mut peer_outbound_messages, shared_error_slot) =
        new_test_connection();

    let connection = connection.run(peer_rx);

    // Drop the inbound peer channel.
    std::mem::drop(peer_tx);

    // If we drop the future, the connection will close anyway, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    assert_eq!(result, Some(()));

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ConnectionClosed",
    );

    assert!(client_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly on internal connection errors.
#[tokio::test]
async fn connection_run_loop_failed() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        mut connection,
        client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Simulate an internal connection error.
    connection.state = State::Failed;
    shared_error_slot
        .try_update_error(PeerError::Overloaded.into())
        .expect("unexpected previous error in tests");

    let connection = connection.run(peer_rx);

    // If we drop the future, the connection will close anyway, so we avoid the drop by cloning it.
    let connection = connection.shared();
    let connection_guard = connection.clone();
    let result = connection.now_or_never();
    // Because the peer error mutex is a sync mutex,
    // the connection can't exit until it reaches the outer async loop.
    assert_eq!(result, Some(()));

    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "Overloaded",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // We need to drop the future, because it holds a mutable reference to the bytes.
    std::mem::drop(connection_guard);
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when sending a message to a peer times out,
/// but we are not expecting a response message from the peer.
#[tokio::test]
async fn connection_run_loop_send_timeout_nil_response() {
    let _init_guard = zebra_test::init();

    tokio::time::pause();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Spawn the connection run loop
    let mut connection_join_handle = tokio::spawn(connection.run(peer_rx));

    // Simulate a message send timeout
    let (request_tx, mut request_rx) = oneshot::channel();
    let request = ClientRequest {
        request: Request::AdvertiseTransactionIds(HashSet::new(), None),
        tx: request_tx,
        inv_collector: None,
        transient_addr: None,
        span: Span::current(),
    };

    client_tx.try_send(request).expect("channel is valid");

    // Make the send timeout
    tokio::time::sleep(REQUEST_TIMEOUT + Duration::from_secs(1)).await;

    // Send timeouts close the connection
    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ConnectionSendTimeout",
    );

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, Some(Message::Inv(Vec::new())));

    let peer_response = request_rx.try_recv();
    assert_eq!(
        peer_response
            .expect("peer internal response channel is valid")
            .expect("response is present")
            .expect_err("response is an error (not a message)")
            .inner_debug(),
        "ConnectionSendTimeout",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // Make sure that the connection finished, but did not panic.
    let connection_result = futures::poll!(&mut connection_join_handle);
    assert!(
        matches!(connection_result, Poll::Ready(Ok(()))),
        "expected run loop termination, but run loop continued: {connection_result:?}",
    );

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop fails correctly when sending a message to a peer times out,
/// and we are expecting a response message from the peer.
#[tokio::test]
async fn connection_run_loop_send_timeout_expect_response() {
    let _init_guard = zebra_test::init();

    tokio::time::pause();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Spawn the connection run loop
    let mut connection_join_handle = tokio::spawn(connection.run(peer_rx));

    // Simulate a message send timeout
    let (request_tx, mut request_rx) = oneshot::channel();
    let request = ClientRequest {
        request: Request::Peers,
        tx: request_tx,
        inv_collector: None,
        transient_addr: None,
        span: Span::current(),
    };

    client_tx.try_send(request).expect("channel is valid");

    // Make the send timeout
    tokio::time::sleep(REQUEST_TIMEOUT + Duration::from_secs(1)).await;

    // Send timeouts close the connection
    let error = shared_error_slot.try_get_error();
    assert_eq!(
        error.expect("missing expected error").inner_debug(),
        "ConnectionSendTimeout",
    );

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, Some(Message::GetAddr));

    let peer_response = request_rx.try_recv();
    assert_eq!(
        peer_response
            .expect("peer internal response channel is valid")
            .expect("response is present")
            .expect_err("response is an error (not a message)")
            .inner_debug(),
        "ConnectionSendTimeout",
    );

    assert!(client_tx.is_closed());
    assert!(peer_tx.is_closed());

    inbound_service.expect_no_requests().await;

    // Make sure that the connection finished, but did not panic.
    let connection_result = futures::poll!(&mut connection_join_handle);
    assert!(
        matches!(connection_result, Poll::Ready(Ok(()))),
        "expected run loop termination, but run loop continued: {connection_result:?}",
    );

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection returns an error to the client, rather than panicking,
/// when the connection task is cancelled while it is sending a message to a peer.
///
/// Regression test for [GHSA-6v36-c42v-v98p].
///
/// [GHSA-6v36-c42v-v98p]: https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-6v36-c42v-v98p
#[tokio::test]
async fn connection_run_loop_cancelled_during_send() {
    let _init_guard = zebra_test::init();

    tokio::time::pause();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (_peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Spawn the connection run loop
    let connection_join_handle = tokio::spawn(connection.run(peer_rx));

    let (request_tx, mut request_rx) = oneshot::channel();
    let request = ClientRequest {
        request: Request::AdvertiseTransactionIds(HashSet::new(), None),
        tx: request_tx,
        inv_collector: None,
        transient_addr: None,
        span: Span::current(),
    };

    client_tx.try_send(request).expect("channel is valid");

    // The peer isn't reading messages, so the send blocks.
    // Let the connection start sending, but stop before the send times out.
    tokio::time::sleep(REQUEST_TIMEOUT / 2).await;

    let error = shared_error_slot.try_get_error();
    assert!(error.is_none(), "unexpected error: {error:?}");
    assert!(
        matches!(request_rx.try_recv(), Ok(None)),
        "the request should still be sending",
    );

    // Simulate `Client::drop()`, which sets the error slot, then aborts the connection task.
    shared_error_slot
        .try_update_error(PeerError::ClientDropped.into())
        .expect("the connection hasn't errored yet");
    connection_join_handle.abort();

    let connection_result = connection_join_handle.await;
    assert!(
        connection_result
            .as_ref()
            .is_err_and(|error| error.is_cancelled()),
        "expected cancelled run loop, but it panicked or finished: {connection_result:?}",
    );

    let peer_response = request_rx.try_recv();
    assert_eq!(
        peer_response
            .expect("response sender was used before it was dropped")
            .expect("response is present")
            .expect_err("response is an error (not a message)")
            .inner_debug(),
        "ClientDropped",
    );

    assert!(client_tx.is_closed());

    inbound_service.expect_no_requests().await;

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, Some(Message::Inv(Vec::new())));

    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Test that the connection run loop continues but returns an error to the client,
/// when a peer accepts a message, but does not send an expected response.
#[tokio::test]
async fn connection_run_loop_receive_timeout() {
    let _init_guard = zebra_test::init();

    tokio::time::pause();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        mut inbound_service,
        mut peer_outbound_messages,
        shared_error_slot,
    ) = new_test_connection();

    // Spawn the connection run loop
    let mut connection_join_handle = tokio::spawn(connection.run(peer_rx));

    // Simulate a message receive timeout
    let (request_tx, mut request_rx) = oneshot::channel();
    let request = ClientRequest {
        request: Request::Peers,
        tx: request_tx,
        inv_collector: None,
        transient_addr: None,
        span: Span::current(),
    };

    client_tx.try_send(request).expect("channel is valid");
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, Some(Message::GetAddr));

    // Make the receive timeout
    tokio::time::sleep(REQUEST_TIMEOUT + Duration::from_secs(1)).await;

    // Receive timeouts don't close the connection
    let error = shared_error_slot.try_get_error();
    assert!(error.is_none(), "unexpected error: {error:?}");

    assert!(!client_tx.is_closed());
    assert!(!peer_tx.is_closed());

    let peer_response = request_rx.try_recv();
    assert_eq!(
        peer_response
            .expect("peer internal response channel is valid")
            .expect("response is present")
            .expect_err("response is an error (not a message)")
            .inner_debug(),
        "ConnectionReceiveTimeout",
    );

    inbound_service.expect_no_requests().await;

    // Make sure that the connection did not:
    // - panic, or
    // - return.
    //
    // This test doesn't cause any fatal errors,
    // so returning would be incorrect behaviour.
    let connection_result = futures::poll!(&mut connection_join_handle);
    assert!(
        matches!(connection_result, Poll::Pending),
        "unexpected run loop termination: {connection_result:?}",
    );

    // We need to abort the connection, because it holds a lock on the outbound channel.
    connection_join_handle.abort();
    let outbound_message = peer_outbound_messages.next().await;
    assert_eq!(outbound_message, None);
}

/// Check basic properties of overload probabilities
#[test]
fn overload_probability_reduces_over_time() {
    let now = Instant::now();

    // Edge case: previous is in the future due to OS monotonic clock bugs
    let prev = now + Duration::from_secs(1);
    assert_eq!(
        overload_drop_connection_probability(now, Some(prev)),
        MAX_OVERLOAD_DROP_PROBABILITY,
        "if the overload time is in the future (OS bugs?), it should have maximum drop probability",
    );

    // Overload/DoS case/edge case: rapidly repeated overloads
    let prev = now;
    assert_eq!(
        overload_drop_connection_probability(now, Some(prev)),
        MAX_OVERLOAD_DROP_PROBABILITY,
        "if the overload times are the same, overloads should have maximum drop probability",
    );

    // Overload/DoS case: rapidly repeated overloads
    let prev = now - Duration::from_micros(1);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability <= MAX_OVERLOAD_DROP_PROBABILITY,
        "if the overloads are very close together, drops can optionally decrease: {drop_probability} <= {MAX_OVERLOAD_DROP_PROBABILITY}",
    );
    assert!(
        MAX_OVERLOAD_DROP_PROBABILITY - drop_probability < 0.001,
        "if the overloads are very close together, drops can only decrease slightly: {drop_probability}",
    );
    let last_probability = drop_probability;

    // Overload/DoS case: rapidly repeated overloads
    let prev = now - Duration::from_millis(1);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability < last_probability,
        "if the overloads decrease, drops should decrease: {drop_probability} < {last_probability}",
    );
    assert!(
        MAX_OVERLOAD_DROP_PROBABILITY - drop_probability < 0.001,
        "if the overloads are very close together, drops can only decrease slightly: {drop_probability}",
    );
    let last_probability = drop_probability;

    // Overload/DoS case: rapidly repeated overloads
    let prev = now - Duration::from_millis(10);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability < last_probability,
        "if the overloads decrease, drops should decrease: {drop_probability} < {last_probability}",
    );
    assert!(
        MAX_OVERLOAD_DROP_PROBABILITY - drop_probability < 0.001,
        "if the overloads are very close together, drops can only decrease slightly: {drop_probability}",
    );
    let last_probability = drop_probability;

    // Overload case: frequent overloads
    let prev = now - Duration::from_millis(100);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability < last_probability,
        "if the overloads decrease, drops should decrease: {drop_probability} < {last_probability}",
    );
    assert!(
        MAX_OVERLOAD_DROP_PROBABILITY - drop_probability < 0.01,
        "if the overloads are very close together, drops can only decrease slightly: {drop_probability}",
    );
    let last_probability = drop_probability;

    // Overload case: occasional but repeated overloads
    let prev = now - Duration::from_secs(1);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability < last_probability,
        "if the overloads decrease, drops should decrease: {drop_probability} < {last_probability}",
    );
    assert!(
        MAX_OVERLOAD_DROP_PROBABILITY - drop_probability > 0.4,
        "if the overloads are distant, drops should decrease a lot: {drop_probability}",
    );
    let last_probability = drop_probability;

    // Overload case: occasional overloads
    let prev = now - Duration::from_secs(5);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert!(
        drop_probability < last_probability,
        "if the overloads decrease, drops should decrease: {drop_probability} < {last_probability}",
    );
    assert_eq!(
        drop_probability, MIN_OVERLOAD_DROP_PROBABILITY,
        "if overloads are far apart, drops should have minimum drop probability: {drop_probability}",
    );
    let _last_probability = drop_probability;

    // Base case: infrequent overloads
    let prev = now - Duration::from_secs(10);
    let drop_probability = overload_drop_connection_probability(now, Some(prev));
    assert_eq!(
        drop_probability, MIN_OVERLOAD_DROP_PROBABILITY,
        "if overloads are far apart, drops should have minimum drop probability: {drop_probability}",
    );

    // Base case: no previous overload
    let drop_probability = overload_drop_connection_probability(now, None);
    assert_eq!(
        drop_probability, MIN_OVERLOAD_DROP_PROBABILITY,
        "if there is no previous overload time, overloads should have minimum drop probability: {drop_probability}",
    );
}

/// Test that connections are randomly terminated in response to `Overloaded` errors.
///
/// TODO: do a similar test on the real service stack created in the `start` command.
#[tokio::test(flavor = "multi_thread")]
async fn connection_is_randomly_disconnected_on_overload() {
    let _init_guard = zebra_test::init();

    // The number of times we repeat the test
    const TEST_RUNS: usize = 220;
    // The expected number of tests before a test failure due to random chance.
    // Based on 10 tests per PR, 100 PR pushes per week, 50 weeks per year.
    const TESTS_BEFORE_FAILURE: f32 = 50_000.0;

    let test_runs = TEST_RUNS.try_into().expect("constant fits in i32");
    // The probability of random test failure is:
    // MIN_OVERLOAD_DROP_PROBABILITY^TEST_RUNS + MAX_OVERLOAD_DROP_PROBABILITY^TEST_RUNS
    assert!(
        1.0 / MIN_OVERLOAD_DROP_PROBABILITY.powi(test_runs) > TESTS_BEFORE_FAILURE,
        "not enough test runs: failures must be frequent enough to happen in almost all tests"
    );
    assert!(
        1.0 / MAX_OVERLOAD_DROP_PROBABILITY.powi(test_runs) > TESTS_BEFORE_FAILURE,
        "not enough test runs: successes must be frequent enough to happen in almost all tests"
    );

    let mut connection_continues = 0;
    let mut connection_closes = 0;

    for _ in 0..TEST_RUNS {
        // The real stream and sink are from a split TCP connection,
        // but that doesn't change how the state machine behaves.
        let (mut peer_tx, peer_rx) = mpsc::channel(1);

        let (
            connection,
            _client_tx,
            mut inbound_service,
            mut peer_outbound_messages,
            shared_error_slot,
        ) = new_test_connection();

        // The connection hasn't run so it must not have errors
        let error = shared_error_slot.try_get_error();
        assert!(
            error.is_none(),
            "unexpected error before starting the connection event loop: {error:?}",
        );

        // Start the connection run loop future in a spawned task
        let connection_handle = tokio::spawn(connection.run(peer_rx));
        tokio::time::sleep(Duration::from_millis(1)).await;

        // The connection hasn't received any messages, so it must not have errors
        let error = shared_error_slot.try_get_error();
        assert!(
            error.is_none(),
            "unexpected error before sending messages to the connection event loop: {error:?}",
        );

        // Simulate an overloaded connection error in response to an inbound request.
        let inbound_req = Message::GetAddr;
        peer_tx
            .send(Ok(inbound_req))
            .await
            .expect("send to channel always succeeds");
        tokio::time::sleep(Duration::from_millis(1)).await;

        // The connection hasn't got a response, so it must not have errors
        let error = shared_error_slot.try_get_error();
        assert!(
            error.is_none(),
            "unexpected error before sending responses to the connection event loop: {error:?}",
        );

        inbound_service
            .expect_request(Request::Peers)
            .await
            .respond_error(Overloaded::new().into());
        tokio::time::sleep(Duration::from_millis(1)).await;

        let outbound_result = peer_outbound_messages.try_recv();
        assert!(
            outbound_result.is_err(),
            "unexpected outbound message after Overloaded error:\n\
             {outbound_result:?}\n\
             note: Err(TryRecvError::Empty) means no messages, Err(TryRecvError::Closed) means the channel is closed"
        );

        let error = shared_error_slot.try_get_error();
        if error.is_some() {
            connection_closes += 1;
        } else {
            connection_continues += 1;
        }

        // We need to terminate the spawned task
        connection_handle.abort();
    }

    assert!(
        connection_closes > 0,
        "some overloaded connections must be closed at random"
    );
    assert!(
        connection_continues > 0,
        "some overloaded errors must be ignored at random"
    );
}

#[tokio::test]
async fn connection_ping_pong_round_trip() {
    let _init_guard = zebra_test::init();

    // The real stream and sink are from a split TCP connection,
    // but that doesn't change how the state machine behaves.
    let (peer_tx, peer_rx) = mpsc::channel(1);

    let (
        connection,
        mut client_tx,
        _inbound_service,
        mut peer_outbound_messages,
        _shared_error_slot,
    ) = new_test_connection();

    let connection = tokio::spawn(connection.run(peer_rx));

    // === Client sends Ping request ===
    let (response_tx, response_rx) = oneshot::channel();
    let nonce = Nonce::default();

    client_tx
        .send(ClientRequest {
            request: Request::Ping(nonce),
            tx: response_tx,
            inv_collector: None,
            transient_addr: None,
            span: Span::none(),
        })
        .await
        .expect("send to connection should succeed");

    // === Peer receives Ping message ===
    let outbound_msg = peer_outbound_messages
        .next()
        .await
        .expect("expected outbound Ping message");

    let ping_nonce = match outbound_msg {
        Message::Ping(nonce) => nonce,
        msg => panic!("expected Ping message, but got: {msg:?}"),
    };

    assert_eq!(
        nonce, ping_nonce,
        "Ping nonce in request must match message sent to peer"
    );

    // === Peer sends matching Pong ===
    let pong_rtt = Duration::from_millis(42);
    tokio::time::sleep(pong_rtt).await;

    peer_tx
        .clone()
        .send(Ok(Message::Pong(ping_nonce)))
        .await
        .expect("sending Pong to connection should succeed");

    // === Client receives Pong response and verifies RTT ===
    match response_rx.await.expect("response channel must succeed") {
        Ok(Response::Pong(rtt)) => {
            assert!(
                rtt >= pong_rtt,
                "measured RTT {rtt:?} must be >= simulated RTT {pong_rtt:?}"
            );
        }
        Ok(resp) => panic!("unexpected response: {resp:?}"),
        Err(err) => panic!("unexpected error: {err:?}"),
    }

    drop(peer_tx);
    let _ = connection.await;
}

/// Test that a `notfound` for a cancelled request doesn't end a later request for other inventory.
#[tokio::test]
async fn connection_ignores_notfound_for_cancelled_requests() {
    let _init_guard = zebra_test::init();

    let blocks: Vec<Arc<Block>> = [
        zebra_test::vectors::BLOCK_MAINNET_1_BYTES.as_slice(),
        zebra_test::vectors::BLOCK_MAINNET_2_BYTES.as_slice(),
    ]
    .into_iter()
    .map(|bytes| {
        bytes
            .zcash_deserialize_into()
            .expect("block vectors are valid")
    })
    .collect();
    let transactions: Vec<UnminedTx> = blocks
        .iter()
        .map(|block| UnminedTx::from(&block.transactions[0]))
        .collect();
    let block_request = |block: &Arc<Block>| Request::BlocksByHash(HashSet::from([block.hash()]));
    let transaction_request = |tx: &UnminedTx| Request::TransactionsById(HashSet::from([tx.id]));

    // A cancelled transaction request, then a block request.
    let response = cancelled_notfound_then_response(
        transaction_request(&transactions[0]),
        transactions[0].id.into(),
        block_request(&blocks[1]),
        Message::Block(blocks[1].clone()),
    )
    .await;
    assert_eq!(
        response,
        Response::Blocks(vec![InventoryResponse::Available((
            blocks[1].clone(),
            None
        ))])
    );

    // A cancelled block request, then a transaction request.
    let response = cancelled_notfound_then_response(
        block_request(&blocks[0]),
        blocks[0].hash().into(),
        transaction_request(&transactions[1]),
        Message::Tx(transactions[1].clone()),
    )
    .await;
    assert_eq!(
        response,
        Response::Transactions(vec![InventoryResponse::Available((
            transactions[1].clone(),
            None
        ))])
    );

    // A cancelled block request, then a request for a different block.
    let response = cancelled_notfound_then_response(
        block_request(&blocks[0]),
        blocks[0].hash().into(),
        block_request(&blocks[1]),
        Message::Block(blocks[1].clone()),
    )
    .await;
    assert_eq!(
        response,
        Response::Blocks(vec![InventoryResponse::Available((
            blocks[1].clone(),
            None
        ))])
    );
}

/// Cancels `cancelled`, sends `request`, then delivers the peer's `notfound` for `missing` from
/// the cancelled request before `reply`. Returns the response to `request`.
async fn cancelled_notfound_then_response(
    cancelled: Request,
    missing: InventoryHash,
    request: Request,
    reply: Message,
) -> Response {
    let (mut peer_tx, peer_rx) = mpsc::channel(1);
    let (connection, mut client_tx, mut inbound_service, mut peer_outbound_messages, error_slot) =
        new_test_connection();
    let connection = tokio::spawn(connection.run(peer_rx));

    let mut response_rx = None;
    for request in [cancelled, request] {
        // Dropping the previous receiver cancels its request.
        drop(response_rx.take());
        let (tx, rx) = oneshot::channel();
        client_tx
            .send(ClientRequest {
                request,
                tx,
                inv_collector: None,
                transient_addr: None,
                span: Span::none(),
            })
            .await
            .expect("connection accepts requests");
        assert!(matches!(
            peer_outbound_messages.next().await,
            Some(Message::GetData(_))
        ));
        response_rx = Some(rx);
    }

    for message in [Message::NotFound(vec![missing]), reply] {
        peer_tx
            .send(Ok(message))
            .await
            .expect("connection is running");
    }
    let response = response_rx
        .expect("the loop sends the request")
        .await
        .expect("connection responds")
        .expect("the notfound for the cancelled request is ignored");

    assert!(error_slot.try_get_error().is_none());
    inbound_service.expect_no_requests().await;

    drop(peer_tx);
    let _ = connection.await;
    response
}

/// Creates a new [`Connection`] instance for unit tests.
fn new_test_connection() -> (
    Connection<
        MockService<Request, Response, PanicAssertion>,
        SinkMapErr<mpsc::Sender<Message>, fn(mpsc::SendError) -> SerializationError>,
    >,
    mpsc::Sender<ClientRequest>,
    MockService<Request, Response, PanicAssertion>,
    mpsc::Receiver<Message>,
    ErrorSlot,
) {
    super::new_test_connection()
}