zakura 1.8.0

Zakura, an independent, consensus-compatible implementation of a Zcash node
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
//! A download stream that handles gossiped blocks from peers.

use std::{
    collections::HashMap,
    net::IpAddr,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use futures::{
    future::{BoxFuture, FutureExt, TryFutureExt},
    ready,
    stream::{FuturesUnordered, Stream},
};
use pin_project::pin_project;
use tokio::{
    sync::{mpsc, oneshot, Mutex},
    task::JoinHandle,
};
use tower::{Service, ServiceExt};
use tracing::Instrument;

use zakura_chain::{
    block::{self, HeightDiff},
    chain_tip::ChainTip,
    parameters::Network,
};
use zakura_network::{self as zn, PeerSocketAddr};
use zakura_state as zs;

use crate::components::{
    auth_download_height::tip_child_mismatch,
    download_work::has_sufficient_work,
    sync::{lookahead_limit_multiplier, MIN_CONCURRENCY_LIMIT},
};

type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// A gossiped block claims our best tip as its parent, but its coinbase height is not one
/// above the tip height.
///
/// V5+ coinbase `scriptSig`s are not covered by the mined transaction ID, the transaction
/// merkle root, or the block hash, so a peer can rewrite the claimed height of an otherwise
/// canonical body without changing the advertised hash. A tip child's real height is known
/// from our own committed tip, so a mismatch is definitively a poisoned body.
///
/// This is a distinct type rather than a string error so [`super::Inbound`] can score the
/// supplying peer for it.
#[derive(Copy, Clone, Debug, thiserror::Error)]
#[error("gossiped tip child claimed height {height:?} instead of {expected_height:?}: {hash:?}")]
pub struct GossipedTipChildHeightMismatch {
    pub height: block::Height,
    pub expected_height: block::Height,
    pub hash: block::Hash,

    /// Whether the body answered a parent recovery rather than an advertised download.
    ///
    /// A failed recovery is left to the syncer, so it stays within [`MAX_PARENT_RECOVERIES`].
    pub parent_recovery: bool,
}

/// Source key used for inbound block download ordering.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum AdvertiserSource {
    /// Legacy TCP peers are ordered per IP address, preserving existing source attribution.
    LegacyIp(IpAddr),

    /// Zakura peers are ordered per authenticated peer id.
    Zakura(zn::zakura::ZakuraPeerId),
}

impl From<zn::PeerSource> for AdvertiserSource {
    fn from(source: zn::PeerSource) -> Self {
        match source {
            zn::PeerSource::LegacySocket(addr) => Self::LegacyIp(addr.ip()),
            zn::PeerSource::Zakura(peer_id) => Self::Zakura(peer_id),
        }
    }
}

impl AdvertiserSource {
    fn max_in_flight(&self, global_limit: usize) -> usize {
        match self {
            Self::LegacyIp(_) => 1,
            // Authenticated Zakura peers get a per-peer slice of the global queue
            // rather than the whole thing, so one peer cannot monopolize inbound
            // block gossip admission. Never exceed the global limit on small queues.
            Self::Zakura(_) => MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER.min(global_limit),
        }
    }
}

fn peer_source_log_label(source: &zn::PeerSource, expose_peer_addresses: bool) -> String {
    match source {
        zn::PeerSource::LegacySocket(addr) if expose_peer_addresses => {
            format!("legacy:{}", addr.remove_socket_addr_privacy())
        }
        zn::PeerSource::LegacySocket(_) => "legacy:redacted".to_string(),
        zn::PeerSource::Zakura(peer_id) => format!("zakura:{peer_id:?}"),
    }
}

/// The handle of a spawned download and verify task.
type DownloadHandle =
    JoinHandle<Result<block::Hash, (BoxError, block::Hash, Option<PeerSocketAddr>)>>;

/// Why a block is being downloaded.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum DownloadKind {
    /// A peer advertised the block, or a poisoned advertised block is being re-requested.
    Advertised,

    /// An advertised child revealed that this block, its parent, is missing.
    ///
    /// A recovered parent never recovers its own parent: one hop closes the gap between a new
    /// tip and its child, and deeper gaps belong to the syncer.
    ParentRecovery,
}

#[derive(Clone, Debug)]
struct DownloadTask {
    hash: block::Hash,
    download_source: Option<zn::PeerSource>,
    advertiser: Option<AdvertiserSource>,
    kind: DownloadKind,
}

/// What happened when an advertised child revealed that its parent is missing.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ParentRecovery {
    /// The downloads stream has shut down.
    Closed,

    /// The parent already has an inbound download, which the child now waits on.
    Attached,

    /// A recovery download for the parent was started.
    Requested,

    /// [`MAX_PARENT_RECOVERIES`] recoveries are already in flight.
    TooManyRecoveries,

    /// A recovery charged to the child's advertiser is already in flight.
    SourceRecoveryInFlight,

    /// The inbound queue is at capacity.
    FullQueue,

    /// The child's header fails the proof of work checks, so it did not start a recovery.
    InvalidProofOfWork,
}

impl ParentRecovery {
    fn metric_label(self) -> &'static str {
        match self {
            Self::Closed => "closed",
            Self::Attached => "attached",
            Self::Requested => "requested",
            Self::TooManyRecoveries => "too_many_recoveries",
            Self::SourceRecoveryInFlight => "source_recovery_in_flight",
            Self::FullQueue => "full_queue",
            Self::InvalidProofOfWork => "invalid_proof_of_work",
        }
    }
}

/// The maximum number of concurrent inbound download and verify tasks.
/// Also used as the maximum lookahead limit, before block verification.
///
/// We expect the syncer to download and verify checkpoints, so this bound
/// can be small.
///
/// ## Security
///
/// The maximum block size is 2 million bytes. A deserialized malicious
/// block with ~225_000 transparent outputs can take up 9MB of RAM.
/// The total queue bound is `MAX_INBOUND_CONCURRENCY * 9 MB`. Admission is
/// bounded globally by [`Downloads::full_verify_concurrency_limit`], deduped by
/// block hash, and bounded per advertiser source. Legacy TCP sources keep the
/// historical one-in-flight per-IP bound; authenticated Zakura sources are bounded
/// per peer id by [`MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER`], so a single Zakura
/// peer cannot fill the global queue with distinct gossiped hashes and deny
/// admission to honest peers (the block-gossip analogue of the mempool fix for
/// `GHSA-4fc2-h7jh-287c`). Admitted same-source downloads fetch block bodies promptly, then
/// wait on a fair source-local gate before verification. This preserves
/// source-local commit order without needing a later inbound request to drain a
/// passive queue.
/// (See #1880 for more details.)
///
/// Malicious blocks will eventually timeout or fail contextual validation.
/// Once validation fails, the block is dropped, and its memory is deallocated.
pub const MAX_INBOUND_CONCURRENCY: usize = 200;

/// The maximum number of concurrent inbound block download tasks attributable to
/// a single authenticated Zakura advertiser.
///
/// Caps how many slots of [`MAX_INBOUND_CONCURRENCY`] (or the configured
/// `full_verify_concurrency_limit`) one Zakura peer's gossiped block hashes can
/// occupy, so a single peer cannot saturate the global queue with distinct hashes
/// and deny gossip-path block admission to honest peers. This mirrors the mempool
/// per-peer cap added for `GHSA-4fc2-h7jh-287c`. Legacy TCP sources keep their
/// historical one-in-flight per-IP bound; crawler/sync-driven downloads have no
/// advertiser source and are not counted against this cap.
pub const MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER: usize = 5;

/// The maximum number of times a gossiped block hash is re-requested after a peer supplies a
/// body whose coinbase height contradicts our own tip.
///
/// A poisoned response satisfies the gossip request without delivering a usable block, and it
/// occupies the per-hash dedupe slot while it is outstanding — so honest peers' `inv`s for the
/// same hash were already dropped as [`DownloadAction::AlreadyQueued`]. Without a re-request the
/// block waits for the syncer's next round, which is the delay this attack aims to cause.
///
/// The re-request is bounded because it can be poisoned in turn: the supplying peer's ban is
/// queued rather than applied immediately, so a replacement request can still route back to it.
pub const POISONED_GOSSIP_BLOCK_RETRY_LIMIT: usize = 3;

/// Returns the highest gossiped block height accepted above `tip_height`.
///
/// The configured limit counts blocks, so this height window scales with the
/// target spacing at the tip, like the syncer's lookahead limit. The queue
/// capacity stays unscaled, because [`MAX_INBOUND_CONCURRENCY`] bounds its RAM.
pub(crate) fn max_lookahead_height(
    network: &Network,
    tip_height: Option<block::Height>,
    full_verify_concurrency_limit: usize,
) -> block::Height {
    if let Some(tip_height) = tip_height {
        let lookahead = HeightDiff::try_from(
            full_verify_concurrency_limit * lookahead_limit_multiplier(network, tip_height),
        )
        .expect("fits in HeightDiff");
        (tip_height + lookahead).expect("tip is much lower than Height::MAX")
    } else {
        let genesis_lookahead =
            u32::try_from(full_verify_concurrency_limit - 1).expect("fits in u32");
        block::Height(genesis_lookahead)
    }
}

/// The action taken in response to a peer's gossiped block hash.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DownloadAction {
    /// The block hash was successfully queued for download and verification.
    AddedToQueue,

    /// The block hash is already queued, so this request was ignored.
    ///
    /// Another peer has already gossiped the same hash to us.
    AlreadyQueued,

    /// The queue is at capacity, so this request was ignored.
    ///
    /// The sync service should discover this block later, when we are closer
    /// to the tip. The queue's capacity is [`Downloads::full_verify_concurrency_limit`].
    FullQueue,
}

/// Per-hash re-request budgets for gossiped blocks rejected as poisoned, scoped to one tip.
///
/// The counts and the tip they belong to are paired here because neither is meaningful alone:
/// a count only bounds anything while it is read against the tip it was recorded under.
///
/// # Lifetime
///
/// An exhausted budget is *not* released on exhaustion. Doing so would re-arm it, letting a peer
/// buy a fresh set of re-requests by poisoning the same hash again. Budgets are released in
/// exactly two places:
///
/// - [`Self::release`], when the block is finally downloaded — the only outcome that means the
///   budget did its job.
/// - [`Self::consume`], for *every* hash, on the first call after the tip moves.
///
/// The second is what actually bounds the map, because gossip usually is not the path that
/// resolves the block: exhaustion explicitly leaves it to the syncer, whose downloads never
/// reach [`Self::release`]. It is sound because this check only ever fires for children of the
/// current tip, so an entry recorded under an older tip could never be read again.
///
/// That is also why a tip change cannot re-arm an exhausted budget: once the tip moves, the
/// exhausted hash is no longer a tip child and can never produce a mismatch, so its fresh budget
/// is unreachable. The one exception is a reorg back to the original tip, which costs the
/// attacker further bannable addresses to exploit.
///
/// The clear is lazy — it happens on the next rejection, not when the tip moves — so a node whose
/// attacker has stopped keeps one tip's worth of entries until the next rejection or process exit.
#[derive(Debug, Default)]
struct PoisonedRetryBudgets {
    /// Re-requests already spent, keyed by block hash.
    counts: HashMap<block::Hash, usize>,

    /// The tip [`Self::counts`] is scoped to.
    tip: Option<block::Hash>,
}

impl PoisonedRetryBudgets {
    /// Spends one re-request from `hash`'s budget under `tip_hash`, returning the attempt number.
    ///
    /// Returns `None` when the budget is exhausted, leaving the block to the syncer. Discards
    /// every budget first if `tip_hash` differs from the one they were recorded under.
    fn consume(&mut self, hash: block::Hash, tip_hash: Option<block::Hash>) -> Option<usize> {
        if self.tip != tip_hash {
            self.counts.clear();
            self.tip = tip_hash;
        }

        let spent = self.counts.entry(hash).or_default();

        if *spent >= POISONED_GOSSIP_BLOCK_RETRY_LIMIT {
            return None;
        }

        *spent += 1;

        Some(*spent)
    }

    /// Releases `hash`'s budget, because the block was downloaded.
    fn release(&mut self, hash: &block::Hash) {
        self.counts.remove(hash);
    }
}

/// The maximum number of parent recovery downloads in flight at once.
///
/// A child of the newest tip normally reveals at most one missing parent, and a short fork race
/// a couple more. Each recovery also takes an inbound queue slot, and each advertiser can have
/// only one recovery charged to it, so children with unavailable parents cannot turn into
/// unbounded requests.
pub const MAX_PARENT_RECOVERIES: usize = 4;

/// The farthest above the tip an advertised child can be while still recovering its parent.
///
/// A child two blocks above the tip is missing exactly one block, its parent. Larger gaps need
/// more than one hop, which is the syncer's job.
const MAX_PARENT_RECOVERY_CHILD_HEIGHT_ABOVE_TIP: HeightDiff = 2;

/// Admission bookkeeping, shared by the [`Downloads`] stream and its download tasks.
///
/// Tasks need it because a downloaded child is the first point where a missing parent becomes
/// known, and the parent's download must be deduplicated against every other inbound download.
#[derive(Debug, Default)]
struct Admission {
    /// The downloads stream has shut down and accepts no further recoveries.
    closed: bool,

    /// Cancellation handles for admitted tasks, keyed by block hash. The optional source is
    /// recorded so completion can clear [`Self::source_counts`] and [`Self::source_locks`].
    ///
    /// Every admitted task has exactly one entry, so this is the inbound queue.
    cancel_handles: HashMap<block::Hash, (oneshot::Sender<()>, Option<AdvertiserSource>)>,

    /// Fair source-local verification gates for admitted downloads.
    ///
    /// Tasks are spawned immediately, but same-source tasks must acquire this gate
    /// before committing a downloaded block to the verifier.
    source_locks: HashMap<AdvertiserSource, Arc<Mutex<()>>>,

    /// Number of admitted tasks, active or waiting, per source.
    source_counts: HashMap<AdvertiserSource, usize>,

    /// Parent recovery downloads in flight, keyed by parent hash, with the advertiser of the
    /// child that requested each one.
    ///
    /// Recoveries are not counted in [`Self::source_counts`] and do not take a source lock: the
    /// waiting child already holds its advertiser's slot and lock, so charging the parent to
    /// them would refuse or deadlock the very download the child is waiting for.
    parent_recoveries: HashMap<block::Hash, Option<AdvertiserSource>>,
}

impl Admission {
    fn queue_len(&self) -> usize {
        self.cancel_handles.len()
    }

    /// Releases everything held by the task for `hash`.
    ///
    /// The task calls this as it finishes. The stream only runs when the next inbound request
    /// polls it, and until then a stale entry would misdirect other tasks' parent recoveries.
    fn release(&mut self, hash: &block::Hash) {
        self.parent_recoveries.remove(hash);

        if let Some((_, Some(source))) = self.cancel_handles.remove(hash) {
            let source_count = self
                .source_counts
                .get_mut(&source)
                .expect("source count is inserted when a download task is admitted");
            *source_count = source_count
                .checked_sub(1)
                .expect("source count is positive while a download task is admitted");

            if *source_count == 0 {
                self.source_counts.remove(&source);
                self.source_locks.remove(&source);
            }
        }
    }
}

/// Spawns download and verify tasks, and admits the parent recoveries they ask for.
///
/// Each task holds a clone, so a downloaded child can start its parent's download through the
/// same admission and spawn path as an advertised block, without waiting for the stream to be
/// polled.
#[derive(Debug)]
struct TaskSpawner<ZN, ZV, ZS> {
    /// The configured full verification concurrency limit, after applying the minimum limit.
    full_verify_concurrency_limit: usize,

    /// A service that forwards requests to connected peers, and returns their
    /// responses.
    network: ZN,

    /// A service that verifies downloaded blocks.
    verifier: ZV,

    /// A service that manages cached blockchain state.
    state: ZS,

    /// Allows efficient access to the best tip of the blockchain.
    latest_chain_tip: zs::LatestChainTip,

    /// The network whose target spacing scales the gossip lookahead window.
    chain_network: Network,

    admission: Arc<std::sync::Mutex<Admission>>,

    /// Hands handles of tasks spawned by other tasks to the stream, which collects their
    /// results.
    spawned_sender: mpsc::UnboundedSender<DownloadHandle>,
}

impl<ZN: Clone, ZV: Clone, ZS: Clone> Clone for TaskSpawner<ZN, ZV, ZS> {
    fn clone(&self) -> Self {
        Self {
            full_verify_concurrency_limit: self.full_verify_concurrency_limit,
            network: self.network.clone(),
            verifier: self.verifier.clone(),
            state: self.state.clone(),
            latest_chain_tip: self.latest_chain_tip.clone(),
            chain_network: self.chain_network.clone(),
            admission: self.admission.clone(),
            spawned_sender: self.spawned_sender.clone(),
        }
    }
}

/// Manages download and verification of blocks gossiped to this peer.
#[pin_project(PinnedDrop)]
#[derive(Debug)]
pub struct Downloads<ZN, ZV, ZS>
where
    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
    ZN::Future: Send,
    ZV: Service<zakura_consensus::Request, Response = block::Hash, Error = BoxError>
        + Send
        + Clone
        + 'static,
    ZV::Future: Send,
    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
    ZS::Future: Send,
{
    /// Whether legacy peer address labels in logs are unredacted.
    expose_peer_addresses: bool,

    /// Admits and spawns download tasks.
    spawner: TaskSpawner<ZN, ZV, ZS>,

    /// Active block download and verify tasks.
    #[pin]
    pending: FuturesUnordered<DownloadHandle>,

    /// Tasks spawned by other tasks, waiting to be moved into [`Self::pending`].
    spawned_receiver: mpsc::UnboundedReceiver<DownloadHandle>,

    /// Re-request budgets for gossiped hashes whose body was rejected as poisoned.
    poisoned_retries: PoisonedRetryBudgets,
}

#[pin_project::pinned_drop]
impl<ZN, ZV, ZS> PinnedDrop for Downloads<ZN, ZV, ZS>
where
    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
    ZN::Future: Send,
    ZV: Service<zakura_consensus::Request, Response = block::Hash, Error = BoxError>
        + Send
        + Clone
        + 'static,
    ZV::Future: Send,
    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
    ZS::Future: Send,
{
    fn drop(self: Pin<&mut Self>) {
        let mut admission = self.spawner.admission();
        // Tasks retain the admission state, so the stream must cancel them explicitly.
        admission.closed = true;
        admission.cancel_handles.clear();
    }
}

impl<ZN, ZV, ZS> Stream for Downloads<ZN, ZV, ZS>
where
    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
    ZN::Future: Send,
    ZV: Service<zakura_consensus::Request, Response = block::Hash, Error = BoxError>
        + Send
        + Clone
        + 'static,
    ZV::Future: Send,
    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
    ZS::Future: Send,
{
    type Item = Result<block::Hash, (BoxError, Option<PeerSocketAddr>)>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let mut this = self.project();

        // Collect tasks spawned by other tasks first, so a stream whose own tasks have all
        // finished still yields their results. This also registers a wakeup for later ones.
        while let Poll::Ready(Some(handle)) = this.spawned_receiver.poll_recv(cx) {
            this.pending.push(handle);
        }

        // CORRECTNESS
        //
        // The current task must be scheduled for wakeup every time we return
        // `Poll::Pending`.
        //
        // If no download and verify tasks have exited since the last poll, this
        // task is scheduled for wakeup when the next task becomes ready.
        //
        // TODO: this would be cleaner with poll_map (#2693)
        if let Some(join_result) = ready!(this.pending.as_mut().poll_next(cx)) {
            let result = match join_result.expect("block download and verify tasks must not panic")
            {
                Ok(hash) => {
                    // The block finally arrived, so its poisoned-retry budget is spent.
                    this.poisoned_retries.release(&hash);
                    Ok(hash)
                }
                Err((e, _hash, advertiser_addr)) => Err((e, advertiser_addr)),
            };
            Poll::Ready(Some(result))
        } else {
            Poll::Ready(None)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.pending.size_hint()
    }
}

impl<ZN, ZV, ZS> Downloads<ZN, ZV, ZS>
where
    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
    ZN::Future: Send,
    ZV: Service<zakura_consensus::Request, Response = block::Hash, Error = BoxError>
        + Send
        + Clone
        + 'static,
    ZV::Future: Send,
    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
    ZS::Future: Send,
{
    /// Initialize a new download stream with the provided `network`, `verifier`, and `state` services.
    /// The `latest_chain_tip` must be linked to the provided `state` service.
    ///
    /// The [`Downloads`] stream is agnostic to the network policy, so retry and
    /// timeout limits should be applied to the `network` service passed into
    /// this constructor.
    pub fn new(
        full_verify_concurrency_limit: usize,
        expose_peer_addresses: bool,
        network: ZN,
        verifier: ZV,
        state: ZS,
        latest_chain_tip: zs::LatestChainTip,
        chain_network: Network,
    ) -> Self {
        // The syncer already warns about the minimum.
        let full_verify_concurrency_limit =
            full_verify_concurrency_limit.clamp(MIN_CONCURRENCY_LIMIT, MAX_INBOUND_CONCURRENCY);

        let (spawned_sender, spawned_receiver) = mpsc::unbounded_channel();

        Self {
            expose_peer_addresses,
            spawner: TaskSpawner {
                full_verify_concurrency_limit,
                network,
                verifier,
                state,
                latest_chain_tip,
                chain_network,
                admission: Arc::default(),
                spawned_sender,
            },
            pending: FuturesUnordered::new(),
            spawned_receiver,
            poisoned_retries: PoisonedRetryBudgets::default(),
        }
    }

    /// Re-request a gossiped block whose body was rejected as poisoned, from any peer.
    ///
    /// The replacement is requested without a download source, so it routes through the peer
    /// set's inventory rather than back to the peer that supplied the poisoned body. That peer's
    /// ban is only queued at this point, so the request can still reach it — hence the
    /// [`POISONED_GOSSIP_BLOCK_RETRY_LIMIT`] budget, which is consumed per hash.
    ///
    /// Returns `None` once the budget for `hash` is exhausted, leaving the block to the syncer.
    /// Exhaustion is sticky for as long as the entry lives: a peer cannot buy a fresh set of
    /// re-requests by poisoning the same hash again.
    ///
    /// Budgets are scoped to the tip they were recorded against, and dropped on the first
    /// rejection after the tip moves — the clear is lazy, so if the attack simply stops, one
    /// tip's worth of entries stays resident until the next rejection or process exit. That is
    /// the natural lifetime: this check only ever fires for children of the *current* tip, so an
    /// entry from an older tip could never be consulted again. It also bounds the map without
    /// relying on the gossip path resolving the block, which it usually does not — the syncer
    /// commonly downloads it instead, which is what exhaustion explicitly asks for, and the
    /// syncer's downloads never reach the release point in this stream's `poll_next`.
    ///
    /// Clearing on a tip change is not a way to re-arm an exhausted budget. Once the tip moves,
    /// the exhausted hash is no longer a child of it, so it can never produce a mismatch again
    /// and its fresh budget is unreachable. The one exception is a reorg back to the original
    /// tip, which costs the attacker further bannable addresses to exploit.
    ///
    /// The tip is read here, not when the body was rejected, so the two can disagree — most often
    /// because the syncer committed that very block in between. The consequences are contained:
    /// the entry is filed under a tip the hash is not a child of, where it is dead weight until
    /// the next clear, and the replacement download is dispatched for a block that may already be
    /// committed. The latter is benign only because `download_and_verify` queries the state for
    /// the block before issuing any network request, so it short-circuits without touching a
    /// peer. That ordering is a real dependency of this design.
    ///
    /// Returns the [`DownloadAction`] otherwise. The queue bounds can refuse the replacement, in
    /// which case the budget is spent without dispatching anything; that case is logged here, so
    /// callers do not need to inspect the result.
    pub fn retry_poisoned(&mut self, hash: block::Hash) -> Option<DownloadAction> {
        // The tip is read here, later than the rejection read it, so the two can disagree —
        // usually because the syncer committed the block in between. See the method docs.
        let tip_hash = self.spawner.latest_chain_tip.best_tip_hash();

        let Some(retry_attempt) = self.poisoned_retries.consume(hash, tip_hash) else {
            warn!(
                ?hash,
                retry_limit = POISONED_GOSSIP_BLOCK_RETRY_LIMIT,
                "poisoned gossip block retry budget exhausted, leaving the block to the syncer"
            );
            metrics::counter!("gossip.poisoned.block.retry.limit.count").increment(1);

            return None;
        };

        // Report what actually happened, not what was attempted: the replacement can be refused
        // by the queue bounds, which spends the budget without dispatching anything.
        let action = self.download_and_verify(hash, None);

        match action {
            DownloadAction::AddedToQueue => {
                info!(
                    ?hash,
                    retry_attempt,
                    retry_limit = POISONED_GOSSIP_BLOCK_RETRY_LIMIT,
                    "gossiped block body was poisoned, re-requesting the block from another peer"
                );
                metrics::counter!("gossip.poisoned.block.requeued.count").increment(1);
            }
            DownloadAction::AlreadyQueued | DownloadAction::FullQueue => {
                warn!(
                    ?hash,
                    ?action,
                    retry_attempt,
                    retry_limit = POISONED_GOSSIP_BLOCK_RETRY_LIMIT,
                    "poisoned gossip block re-request was refused, \
                     spending the retry budget without dispatching"
                );
                metrics::counter!("gossip.poisoned.block.requeue.refused.count").increment(1);
            }
        }

        Some(action)
    }

    /// Queue a block for download and verification.
    ///
    /// When `download_source` is `Some`, the block request is directed to that
    /// source. Admission is still controlled by the global queue bound and
    /// per-hash dedupe, so valid consecutive blocks from one source are not
    /// dropped solely because an earlier block is still being verified.
    ///
    /// If the downloaded block's parent is missing, the task recovers it: see
    /// [`TaskSpawner::recover_parent`].
    #[instrument(
        skip(self, hash, download_source),
        fields(hash = %hash, source = tracing::field::Empty)
    )]
    pub fn download_and_verify(
        &mut self,
        hash: block::Hash,
        download_source: Option<zn::PeerSource>,
    ) -> DownloadAction {
        let source_label = download_source
            .as_ref()
            .map(|source| peer_source_log_label(source, self.expose_peer_addresses))
            .unwrap_or_else(|| "none".to_string());
        tracing::Span::current().record("source", source_label.as_str());

        let full_verify_concurrency_limit = self.spawner.full_verify_concurrency_limit;
        let mut admission = self.spawner.admission();
        let queue_len = admission.queue_len();

        if admission.cancel_handles.contains_key(&hash) {
            debug!(
                ?hash,
                queue_len,
                concurrency_limit = full_verify_concurrency_limit,
                "block hash already queued for inbound download: ignored block",
            );

            metrics::gauge!("gossip.queued.block.count").set(queue_len as f64);
            metrics::counter!("gossip.already.queued.dropped.block.hash.count").increment(1);

            return DownloadAction::AlreadyQueued;
        }

        if queue_len >= full_verify_concurrency_limit {
            debug!(
                ?hash,
                queue_len,
                concurrency_limit = full_verify_concurrency_limit,
                "too many blocks queued for inbound download: ignored block",
            );

            metrics::gauge!("gossip.queued.block.count").set(queue_len as f64);
            metrics::counter!("gossip.full.queue.dropped.block.hash.count").increment(1);

            return DownloadAction::FullQueue;
        }

        let advertiser = download_source.clone().map(AdvertiserSource::from);
        if let Some(source) = &advertiser {
            let source_count = admission
                .source_counts
                .get(source)
                .copied()
                .unwrap_or_default();
            let source_limit = source.max_in_flight(full_verify_concurrency_limit);
            if source_count >= source_limit {
                debug!(
                    ?hash,
                    source_count,
                    source_limit,
                    queue_len,
                    concurrency_limit = full_verify_concurrency_limit,
                    "too many blocks queued for inbound download from one source: ignored block",
                );

                metrics::gauge!("gossip.queued.block.count").set(queue_len as f64);
                metrics::counter!("gossip.source.queue.dropped.block.hash.count").increment(1);

                return DownloadAction::FullQueue;
            }
        }

        let download = DownloadTask {
            hash,
            advertiser,
            download_source,
            kind: DownloadKind::Advertised,
        };

        let task = self.spawner.spawn_download_task(&mut admission, download);
        let queue_len = admission.queue_len();
        drop(admission);
        self.pending.push(task);

        debug!(
            ?hash,
            queue_len,
            concurrency_limit = full_verify_concurrency_limit,
            "queued hash for download",
        );
        metrics::gauge!("gossip.queued.block.count").set(queue_len as f64);

        DownloadAction::AddedToQueue
    }
}

impl<ZN, ZV, ZS> TaskSpawner<ZN, ZV, ZS>
where
    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
    ZN::Future: Send,
    ZV: Service<zakura_consensus::Request, Response = block::Hash, Error = BoxError>
        + Send
        + Clone
        + 'static,
    ZV::Future: Send,
    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
    ZS::Future: Send,
{
    /// Locks the admission bookkeeping. Callers must not hold the guard across an `await`.
    fn admission(&self) -> std::sync::MutexGuard<'_, Admission> {
        self.admission
            .lock()
            .expect("admission is only mutated by non-panicking bookkeeping code")
    }

    /// Starts recovering `parent`, which an advertised child at `child_height` revealed to be
    /// missing from the state.
    ///
    /// If `parent` already has an inbound download, the child waits on it. Otherwise one
    /// recovery download is requested with `child_source` as its source. The peer set sends it
    /// to a peer that advertised `parent` if there is one, and otherwise to the child's
    /// advertiser, which has the parent if it validated the child. A child without a source
    /// routes the request through the peer set's inventory.
    ///
    /// A failed recovery is not retried here: the syncer recovers the parent as before.
    ///
    /// # Security
    ///
    /// Recoveries are bounded by [`MAX_PARENT_RECOVERIES`] in total, by one per child
    /// advertiser, by the inbound queue limit, and to a single hop, because recovered parents
    /// never recover their own parents. The caller only calls this for children close enough
    /// to the tip that one hop could connect them, and whose headers carry valid proof of work,
    /// so a peer cannot occupy these slots with blocks that cost nothing to make.
    fn recover_parent(
        &self,
        parent: block::Hash,
        child_source: Option<zn::PeerSource>,
    ) -> ParentRecovery {
        let mut admission = self.admission();

        if admission.closed {
            return ParentRecovery::Closed;
        }

        if admission.cancel_handles.contains_key(&parent) {
            return ParentRecovery::Attached;
        }

        if admission.parent_recoveries.len() >= MAX_PARENT_RECOVERIES {
            return ParentRecovery::TooManyRecoveries;
        }

        let charged_source = child_source.clone().map(AdvertiserSource::from);
        if admission
            .parent_recoveries
            .values()
            .any(|source| *source == charged_source)
        {
            return ParentRecovery::SourceRecoveryInFlight;
        }

        if admission.queue_len() >= self.full_verify_concurrency_limit {
            return ParentRecovery::FullQueue;
        }

        let download = DownloadTask {
            hash: parent,
            download_source: child_source,
            advertiser: None,
            kind: DownloadKind::ParentRecovery,
        };
        let task = self.spawn_download_task(&mut admission, download);
        admission.parent_recoveries.insert(parent, charged_source);
        drop(admission);

        // Dropping the stream closes admission and drops every cancellation sender.
        let _ = self.spawned_sender.send(task);

        ParentRecovery::Requested
    }

    /// Spawns the download and verify task for `download`, and records it in `admission`.
    fn spawn_download_task(
        &self,
        admission: &mut Admission,
        download: DownloadTask,
    ) -> DownloadHandle {
        let DownloadTask {
            hash,
            download_source,
            advertiser,
            kind,
        } = download;

        let source_lock = advertiser.as_ref().map(|source| {
            *admission.source_counts.entry(source.clone()).or_default() += 1;
            admission
                .source_locks
                .entry(source.clone())
                .or_insert_with(|| Arc::new(Mutex::new(())))
                .clone()
        });

        // This oneshot is used to signal cancellation to the download task.
        let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();

        let spawner = self.clone();
        let network = self.network.clone();
        let chain_network = self.chain_network.clone();
        let verifier = self.verifier.clone();
        let state = self.state.clone();
        let latest_chain_tip = self.latest_chain_tip.clone();
        let full_verify_concurrency_limit = self.full_verify_concurrency_limit;

        // Boxed with an explicit `Send` bound, because this future can spawn another task built
        // by this same function.
        let fut: BoxFuture<'static, _> = async move {
            // Check if the full block body is already in the state. `KnownBlock`
            // can be true for header-only Zakura sync state, but inbound gossip
            // still needs to fetch and verify the block body in that case.
            match state
                .clone()
                .oneshot(zs::Request::AnyChainBlock(hash.into()))
                .await
            {
                Ok(zs::Response::Block(None)) => Ok(()),
                Ok(zs::Response::Block(Some(_))) => Err("already present".into()),
                Ok(_) => unreachable!("wrong response"),
                Err(e) => Err(e),
            }
            .map_err(|e| (e, None))?;

            let request_hashes = std::iter::once(hash).collect();
            let request = match download_source.clone() {
                Some(source) => zn::Request::BlocksByHashFrom {
                    hashes: request_hashes,
                    source,
                },
                None => zn::Request::BlocksByHash(request_hashes),
            };

            let (block, advertiser_addr) = if let zn::Response::Blocks(blocks) =
                network.oneshot(request).await.map_err(|e| (e, None))?
            {
                // A peer must answer a single-hash block request with exactly one
                // block entry. A malformed or empty response is a peer fault (e.g.
                // a Zakura peer that tore its connection down mid-response), not a
                // local invariant, so fail the download gracefully rather than
                // panicking the task.
                if blocks.len() != 1 {
                    return Err((
                        format!(
                            "wrong number of blocks in response to a single hash: got {}",
                            blocks.len()
                        )
                        .into(),
                        None,
                    ));
                }

                let Some(available) = blocks.first().expect("just checked length").available()
                else {
                    return Err((
                        "unexpected missing block status: single block failures should be errors"
                            .into(),
                        None,
                    ));
                };
                available
            } else {
                unreachable!("wrong response to block request");
            };

            // Bind the delivered block to the hash we requested. A peer that
            // substitutes a different (even valid) block must not be able to
            // corrupt our hash/source accounting: the verifier returns the
            // committed block's hash, and queue cleanup keys on it, so a
            // mismatch would leave the originally requested entry stale.
            if block.hash() != hash {
                return Err((
                    format!(
                        "peer returned block {} in response to a request for {hash}",
                        block.hash()
                    )
                    .into(),
                    advertiser_addr,
                ));
            }
            metrics::counter!("gossip.downloaded.block.count").increment(1);

            // # Security & Performance
            //
            // Reject blocks that are too far ahead of our tip,
            // and blocks that are behind the finalized tip.
            //
            // Avoids denial of service attacks. Also reduces wasted work on high blocks
            // that will timeout before being verified, and low blocks that can never be finalized.
            let tip_height = latest_chain_tip.best_tip_height();

            // Read separately from `tip_height`, and used only by the new tip-child height check
            // below. Deriving `tip_height` from this pair instead would couple the existing
            // lookahead and behind-tip policies to hash availability: a chain tip reporting a
            // height but not yet a hash would fall into the no-tip regime.
            let best_tip = latest_chain_tip.best_tip_height_and_hash();

            let max_lookahead_height =
                max_lookahead_height(&chain_network, tip_height, full_verify_concurrency_limit);

            // Get the finalized tip height, assuming we're using the non-finalized state.
            //
            // It doesn't matter if we're a few blocks off here, because blocks this low
            // are part of a fork with much less work. So they would be rejected anyway.
            //
            // And if we're still checkpointing, the checkpointer will reject blocks behind
            // the finalized tip anyway.
            //
            // TODO: get the actual finalized tip height
            let min_accepted_height = tip_height
                .map(|tip_height| {
                    block::Height(tip_height.0.saturating_sub(zs::MAX_BLOCK_REORG_HEIGHT))
                })
                .unwrap_or(block::Height(0));

            let block_height = block
                .coinbase_height()
                .ok_or_else(|| {
                    debug!(
                        ?hash,
                        "gossiped block with no height: dropped downloaded block"
                    );
                    metrics::counter!("gossip.no.height.dropped.block.count").increment(1);

                    BoxError::from("gossiped block with no height")
                })
                .map_err(|e| (e, None))?;

            // Security: authenticate the claimed coinbase height against our own tip before the
            // height policies below run. See `crate::components::auth_download_height`.
            //
            // This matters more here than on the syncer path: an `inv` for the new tip normally
            // reaches gossip before the syncer asks for it, and `download_and_verify` drops
            // honest peers' `inv`s for the same hash as `AlreadyQueued` while a download is
            // outstanding. So a single poisoned response can consume the node's only chance at
            // the new block until the next sync round, which is what leaves a mining backend
            // issuing work on an obsolete tip.
            if let Some(expected_height) =
                tip_child_mismatch(block.header.previous_block_hash, block_height, best_tip)
            {
                debug!(
                    ?hash,
                    ?block_height,
                    ?expected_height,
                    "gossiped tip child claimed the wrong coinbase height: \
                     dropped downloaded block"
                );
                metrics::counter!("gossip.tip.child.height.mismatch.count").increment(1);

                Err((
                    BoxError::from(GossipedTipChildHeightMismatch {
                        height: block_height,
                        expected_height,
                        hash,
                        parent_recovery: kind == DownloadKind::ParentRecovery,
                    }),
                    advertiser_addr,
                ))?;
            }

            if block_height > max_lookahead_height {
                debug!(
                    ?hash,
                    ?block_height,
                    ?tip_height,
                    ?max_lookahead_height,
                    lookahead_limit = full_verify_concurrency_limit,
                    "gossiped block height too far ahead of the tip: dropped downloaded block",
                );
                metrics::counter!("gossip.max.height.limit.dropped.block.count").increment(1);

                Err("gossiped block height too far ahead").map_err(|e| (e.into(), None))?;
            } else if block_height < min_accepted_height {
                debug!(
                    ?hash,
                    ?block_height,
                    ?tip_height,
                    ?min_accepted_height,
                    behind_tip_limit = ?zs::MAX_BLOCK_REORG_HEIGHT,
                    "gossiped block height behind the finalized tip: dropped downloaded block",
                );
                metrics::counter!("gossip.min.height.limit.dropped.block.count").increment(1);

                Err("gossiped block height behind the finalized tip")
                    .map_err(|e| (e.into(), None))?;
            }

            if !has_sufficient_work(
                &chain_network,
                tip_height,
                block_height,
                block.header.difficulty_threshold,
            ) {
                metrics::counter!("gossip.insufficient_work.dropped.block.count").increment(1);
                return Err((
                    "gossiped block target is easier than the Mainnet admission floor".into(),
                    advertiser_addr,
                ));
            }

            // The parent is checked after the height policies, so only blocks this node would
            // verify can start a recovery, and before the source lock, so a recovery is not
            // delayed by earlier blocks from the same source.
            if kind == DownloadKind::Advertised {
                let parent = block.header.previous_block_hash;
                let one_hop_from_tip = tip_height
                    .and_then(|tip| tip + MAX_PARENT_RECOVERY_CHILD_HEIGHT_ABOVE_TIP)
                    .is_some_and(|max_height| block_height <= max_height);

                // A failed read only skips the recovery: the verifier still waits for the
                // parent as before.
                let parent_is_missing = one_hop_from_tip
                    && matches!(
                        state.oneshot(zs::Request::KnownBlock(parent)).await,
                        Ok(zs::Response::KnownBlock(None))
                    );

                if parent_is_missing {
                    let header = block.header.clone();
                    let proof_of_work_is_valid = tokio::task::spawn_blocking(move || {
                        zakura_consensus::proof_of_work_is_valid(
                            &header,
                            &chain_network,
                            &block_height,
                            &hash,
                        )
                    })
                    .await
                    .unwrap_or(false);

                    let recovery = if proof_of_work_is_valid {
                        spawner.recover_parent(parent, download_source)
                    } else {
                        ParentRecovery::InvalidProofOfWork
                    };
                    debug!(
                        ?hash,
                        ?parent,
                        ?block_height,
                        ?recovery,
                        "gossiped block's parent is missing",
                    );
                    metrics::counter!(
                        "gossip.missing.parent.count",
                        "outcome" => recovery.metric_label(),
                    )
                    .increment(1);
                }
            }

            let _source_guard = match source_lock {
                Some(source_lock) => Some(source_lock.lock_owned().await),
                None => None,
            };

            verifier
                .oneshot(zakura_consensus::Request::Commit(block))
                .await
                .map(|hash| (hash, block_height))
                .map_err(|e| (e, advertiser_addr))
        }
        .map_ok(move |(hash, height)| {
            match kind {
                DownloadKind::Advertised => {
                    info!(?height, "downloaded and verified gossiped block")
                }
                DownloadKind::ParentRecovery => {
                    info!(
                        ?height,
                        "downloaded and verified missing parent of gossiped block"
                    )
                }
            }
            metrics::counter!("gossip.verified.block.count").increment(1);
            hash
        })
        // Tack the hash onto the error so poll_next can look up the cancel
        // handle and advertising IP on failure as well as success.
        .map_err(move |(e, advertiser_addr)| (e, hash, advertiser_addr))
        .in_current_span()
        .boxed();

        let task_admission = self.admission.clone();
        let task = tokio::spawn(async move {
            // Prefer the cancel handle if both are ready.
            let result = tokio::select! {
                biased;
                _ = &mut cancel_rx => {
                    trace!("task cancelled prior to completion");
                    metrics::counter!("gossip.cancelled.count").increment(1);
                    Err(("canceled".into(), hash, None))
                }
                verification = fut => verification,
            };

            // `spawn_download_task` holds this lock until it has recorded the task.
            task_admission
                .lock()
                .expect("admission is only mutated by non-panicking bookkeeping code")
                .release(&hash);

            result
        });

        assert!(
            admission
                .cancel_handles
                .insert(hash, (cancel_tx, advertiser))
                .is_none(),
            "blocks are only queued once"
        );

        task
    }
}

#[cfg(test)]
mod missing_parent_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt as _;
    use indexmap::IndexSet;
    use std::{collections::HashSet, future, time::Duration};
    use tower::{service_fn, util::BoxCloneService};
    use zakura_chain::{block::Block, parameters::Network, serialization::ZcashDeserializeInto};
    use zakura_network::InventoryResponse::Available;

    use crate::components::auth_download_height::poison_coinbase_height;

    type PendingNetwork = BoxCloneService<zn::Request, zn::Response, BoxError>;
    type PendingVerifier = BoxCloneService<zakura_consensus::Request, block::Hash, BoxError>;
    type PendingState = BoxCloneService<zs::Request, zs::Response, BoxError>;

    fn hash(byte: u8) -> block::Hash {
        block::Hash([byte; 32])
    }

    #[test]
    fn peer_source_log_labels_require_explicit_opt_in() {
        let source = zn::PeerSource::LegacySocket(
            "192.0.2.1:8233".parse().expect("valid test peer address"),
        );

        assert_eq!(peer_source_log_label(&source, false), "legacy:redacted");
        assert_eq!(
            peer_source_log_label(&source, true),
            "legacy:192.0.2.1:8233"
        );
    }

    fn pending_downloads() -> Downloads<PendingNetwork, PendingVerifier, PendingState> {
        let (_tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        pending_downloads_with_tip(latest_chain_tip)
    }

    /// [`pending_downloads`], with a caller-supplied chain tip.
    fn pending_downloads_with_tip(
        latest_chain_tip: zs::LatestChainTip,
    ) -> Downloads<PendingNetwork, PendingVerifier, PendingState> {
        Downloads::new(
            MAX_INBOUND_CONCURRENCY,
            false,
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<zn::Response, BoxError>>()
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<block::Hash, BoxError>>()
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<zs::Response, BoxError>>()
            })),
            latest_chain_tip,
            Network::Mainnet,
        )
    }

    #[tokio::test]
    async fn source_admission_limits_preserve_legacy_bound_and_allow_zakura_burst() {
        let mut downloads = pending_downloads();
        let legacy_a = zn::PeerSource::LegacySocket(([127, 0, 0, 1], 8233).into());
        let legacy_same_ip = zn::PeerSource::LegacySocket(([127, 0, 0, 1], 18233).into());
        let zakura_a = zn::PeerSource::Zakura(
            zn::zakura::ZakuraPeerId::new(vec![7; 32]).expect("test peer id is within bounds"),
        );
        let zakura_b = zn::PeerSource::Zakura(
            zn::zakura::ZakuraPeerId::new(vec![8; 32]).expect("test peer id is within bounds"),
        );

        assert_eq!(
            downloads.download_and_verify(hash(1), Some(legacy_a)),
            DownloadAction::AddedToQueue
        );
        assert_eq!(downloads.pending.len(), 1);
        assert_eq!(
            downloads.download_and_verify(hash(2), Some(legacy_same_ip)),
            DownloadAction::FullQueue
        );
        assert_eq!(downloads.pending.len(), 1);
        assert_eq!(
            downloads.download_and_verify(hash(3), Some(zakura_a.clone())),
            DownloadAction::AddedToQueue
        );
        assert_eq!(downloads.pending.len(), 2);
        assert_eq!(
            downloads.download_and_verify(hash(4), Some(zakura_a.clone())),
            DownloadAction::AddedToQueue
        );
        assert_eq!(downloads.pending.len(), 3);
        assert_eq!(
            downloads.download_and_verify(hash(5), Some(zakura_a)),
            DownloadAction::AddedToQueue
        );
        assert_eq!(downloads.pending.len(), 4);
        assert_eq!(
            downloads.download_and_verify(hash(6), Some(zakura_b)),
            DownloadAction::AddedToQueue
        );
        assert_eq!(downloads.pending.len(), 5);
        assert_eq!(downloads.spawner.admission().queue_len(), 5);
        assert_eq!(
            downloads.download_and_verify(hash(6), None),
            DownloadAction::AlreadyQueued
        );
    }

    #[tokio::test]
    async fn single_zakura_source_cannot_monopolize_inbound_block_queue() {
        let mut downloads = pending_downloads();
        let zakura_a = zn::PeerSource::Zakura(
            zn::zakura::ZakuraPeerId::new(vec![7; 32]).expect("test peer id is within bounds"),
        );
        let zakura_b = zn::PeerSource::Zakura(
            zn::zakura::ZakuraPeerId::new(vec![8; 32]).expect("test peer id is within bounds"),
        );

        // A single Zakura source may occupy at most
        // `MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER` slots of the global inbound
        // queue, even though the global queue still has plenty of room.
        for index in 0..MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER {
            let byte = u8::try_from(index).expect("per-peer cap fits in u8");
            assert_eq!(
                downloads.download_and_verify(hash(byte), Some(zakura_a.clone())),
                DownloadAction::AddedToQueue
            );
        }
        assert_eq!(
            downloads.pending.len(),
            MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER
        );

        // The next distinct hash from the same source is rejected: one Zakura peer
        // cannot keep advertising until it owns the whole global gossip queue.
        let over_cap = hash(
            u8::try_from(MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER).expect("per-peer cap fits in u8"),
        );
        assert_eq!(
            downloads.download_and_verify(over_cap, Some(zakura_a)),
            DownloadAction::FullQueue
        );
        assert_eq!(
            downloads.pending.len(),
            MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER
        );

        // A different honest Zakura peer is still admitted while the first is at
        // its cap, so no single peer monopolizes gossip admission.
        assert_eq!(
            downloads.download_and_verify(hash(200), Some(zakura_b)),
            DownloadAction::AddedToQueue
        );
        assert_eq!(
            downloads.pending.len(),
            MAX_INBOUND_BLOCK_CONCURRENCY_PER_PEER + 1
        );
    }

    #[tokio::test]
    async fn global_inbound_download_queue_bounds_admission() {
        let (_tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        let mut downloads = Downloads::new(
            MIN_CONCURRENCY_LIMIT,
            false,
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<zn::Response, BoxError>>()
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<block::Hash, BoxError>>()
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<zs::Response, BoxError>>()
            })),
            latest_chain_tip,
            Network::Mainnet,
        );

        for index in 0..MIN_CONCURRENCY_LIMIT {
            let byte = u8::try_from(index).expect("minimum concurrency limit fits in u8");
            assert_eq!(
                downloads.download_and_verify(hash(byte), None),
                DownloadAction::AddedToQueue
            );
        }
        let overflow_hash = hash(
            u8::try_from(MIN_CONCURRENCY_LIMIT).expect("minimum concurrency limit fits in u8"),
        );
        assert_eq!(
            downloads.download_and_verify(overflow_hash, None),
            DownloadAction::FullQueue
        );
    }

    #[tokio::test]
    async fn same_source_downloads_fetch_promptly_and_verify_in_order() -> Result<(), BoxError> {
        let block_one: Arc<block::Block> =
            zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
        let block_two: Arc<block::Block> =
            zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
        let hash_one = block_one.hash();
        let hash_two = block_two.hash();
        let peer_id =
            zn::zakura::ZakuraPeerId::new(vec![7; 32]).expect("test peer id is within bounds");
        let source = zn::PeerSource::Zakura(peer_id.clone());

        let blocks = Arc::new(HashMap::from([
            (hash_one, block_one.clone()),
            (hash_two, block_two.clone()),
        ]));
        let (network_tx, mut network_rx) = tokio::sync::mpsc::unbounded_channel::<zn::Request>();
        let network = BoxCloneService::new(service_fn(move |request: zn::Request| {
            let blocks = blocks.clone();
            let network_tx = network_tx.clone();

            async move {
                network_tx.send(request.clone())?;

                let zn::Request::BlocksByHashFrom { hashes, .. } = request else {
                    return Err("unexpected network request".into());
                };
                let hash = hashes
                    .iter()
                    .next()
                    .copied()
                    .expect("download requests contain one hash");
                let block = blocks
                    .get(&hash)
                    .cloned()
                    .expect("test network has a block for the requested hash");

                Ok(zn::Response::Blocks(vec![Available((block, None))]))
            }
        }));

        let (commit_tx, mut commit_rx) = tokio::sync::mpsc::unbounded_channel();
        let (release_tx, release_rx) = oneshot::channel();
        let release_rx = Arc::new(Mutex::new(Some(release_rx)));
        let verifier =
            BoxCloneService::new(service_fn(move |request: zakura_consensus::Request| {
                let commit_tx = commit_tx.clone();
                let release_rx = release_rx.clone();

                async move {
                    let zakura_consensus::Request::Commit(block) = request else {
                        return Err("unexpected verifier request".into());
                    };
                    let hash = block.hash();
                    commit_tx.send(hash)?;

                    if hash == hash_one {
                        let release_rx = release_rx
                            .lock()
                            .await
                            .take()
                            .expect("first block verifier is released once");
                        release_rx.await?;
                    }

                    Ok(hash)
                }
            }));

        let (_tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        let mut downloads = Downloads::new(
            MAX_INBOUND_CONCURRENCY,
            false,
            network,
            verifier,
            BoxCloneService::new(service_fn(|request| async move {
                match request {
                    zs::Request::AnyChainBlock(_) => Ok(zs::Response::Block(None)),
                    request => Err(format!("unexpected state request: {request:?}").into()),
                }
            })),
            latest_chain_tip,
            Network::Mainnet,
        );

        assert_eq!(
            downloads.download_and_verify(hash_one, Some(source.clone())),
            DownloadAction::AddedToQueue
        );
        assert_eq!(
            downloads.download_and_verify(hash_two, Some(source)),
            DownloadAction::AddedToQueue
        );

        let first_request = tokio::time::timeout(Duration::from_secs(1), network_rx.recv())
            .await
            .expect("first same-source download starts")
            .expect("network request channel is open");
        assert_eq!(
            first_request,
            zn::Request::BlocksByHashFrom {
                hashes: IndexSet::from([hash_one]),
                source: zn::PeerSource::Zakura(peer_id.clone()),
            }
        );

        assert_eq!(
            tokio::time::timeout(Duration::from_secs(1), commit_rx.recv())
                .await
                .expect("first block reaches verifier"),
            Some(hash_one)
        );

        let second_request = tokio::time::timeout(Duration::from_secs(1), network_rx.recv())
            .await
            .expect("second same-source download starts without waiting for verifier cleanup")
            .expect("network request channel is open");
        assert!(
            tokio::time::timeout(Duration::from_millis(100), commit_rx.recv())
                .await
                .is_err(),
            "second same-source verifier commit must wait until the first verifier finishes",
        );

        release_tx
            .send(())
            .expect("first verifier task is waiting for release");

        assert_eq!(
            second_request,
            zn::Request::BlocksByHashFrom {
                hashes: IndexSet::from([hash_two]),
                source: zn::PeerSource::Zakura(peer_id),
            }
        );
        assert_eq!(
            tokio::time::timeout(Duration::from_secs(1), commit_rx.recv())
                .await
                .expect("second block reaches verifier after first release"),
            Some(hash_two)
        );

        let first_result = tokio::time::timeout(Duration::from_secs(1), downloads.next())
            .await
            .expect("first completed download is yielded")
            .expect("downloads stream is open")
            .expect("first download succeeds");
        let second_result = tokio::time::timeout(Duration::from_secs(1), downloads.next())
            .await
            .expect("second completed download is yielded")
            .expect("downloads stream is open")
            .expect("second download succeeds");
        assert_eq!(
            HashSet::from([first_result, second_result]),
            HashSet::from([hash_one, hash_two])
        );
        assert_eq!(downloads.spawner.admission().queue_len(), 0);
        let admission = downloads.spawner.admission();
        assert!(admission.source_locks.is_empty());
        assert!(admission.source_counts.is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn zakura_advertiser_source_is_sent_to_network_download_request() {
        let hash = hash(9);
        let peer_id =
            zn::zakura::ZakuraPeerId::new(vec![9; 32]).expect("test peer id is within bounds");
        let (network_tx, mut network_rx) = tokio::sync::mpsc::unbounded_channel();
        let (_tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        let mut downloads = Downloads::new(
            MAX_INBOUND_CONCURRENCY,
            false,
            BoxCloneService::new(service_fn(move |request| {
                let network_tx = network_tx.clone();
                async move {
                    network_tx.send(request)?;
                    future::pending::<Result<zn::Response, BoxError>>().await
                }
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<block::Hash, BoxError>>()
            })),
            BoxCloneService::new(service_fn(|request| async move {
                match request {
                    zs::Request::AnyChainBlock(_) => Ok(zs::Response::Block(None)),
                    request => Err(format!("unexpected state request: {request:?}").into()),
                }
            })),
            latest_chain_tip,
            Network::Mainnet,
        );

        assert_eq!(
            downloads.download_and_verify(hash, Some(zn::PeerSource::Zakura(peer_id.clone())),),
            DownloadAction::AddedToQueue
        );
        let poll_task = tokio::spawn(async move {
            let _ = downloads.next().await;
        });
        let request = tokio::time::timeout(Duration::from_secs(1), network_rx.recv())
            .await
            .expect("network request is sent")
            .expect("network request channel is open");
        assert_eq!(
            request,
            zn::Request::BlocksByHashFrom {
                hashes: IndexSet::from([hash]),
                source: zn::PeerSource::Zakura(peer_id),
            }
        );
        poll_task.abort();
    }

    #[tokio::test]
    async fn substituted_block_response_is_rejected_and_cleans_up_requested_hash(
    ) -> Result<(), BoxError> {
        let requested_block: Arc<block::Block> =
            zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
        let substitute_block: Arc<block::Block> =
            zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
        let requested_hash = requested_block.hash();
        assert_ne!(requested_hash, substitute_block.hash());

        let peer_id =
            zn::zakura::ZakuraPeerId::new(vec![7; 32]).expect("test peer id is within bounds");
        let source = zn::PeerSource::Zakura(peer_id);

        // The peer answers a single-hash request with a *different* valid block.
        let substitute = substitute_block.clone();
        let network = BoxCloneService::new(service_fn(move |request: zn::Request| {
            let substitute = substitute.clone();
            async move {
                let (zn::Request::BlocksByHashFrom { .. } | zn::Request::BlocksByHash(_)) = request
                else {
                    return Err("unexpected network request".into());
                };
                Ok(zn::Response::Blocks(vec![Available((substitute, None))]))
            }
        }));

        // The verifier would happily commit whatever block it is handed.
        let verifier = BoxCloneService::new(service_fn(
            |request: zakura_consensus::Request| async move {
                let zakura_consensus::Request::Commit(block) = request else {
                    return Err("unexpected verifier request".into());
                };
                Ok(block.hash())
            },
        ));

        let (_tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        let mut downloads = Downloads::new(
            MAX_INBOUND_CONCURRENCY,
            false,
            network,
            verifier,
            BoxCloneService::new(service_fn(|request| async move {
                match request {
                    zs::Request::AnyChainBlock(_) => Ok(zs::Response::Block(None)),
                    request => Err(format!("unexpected state request: {request:?}").into()),
                }
            })),
            latest_chain_tip,
            Network::Mainnet,
        );

        assert_eq!(
            downloads.download_and_verify(requested_hash, Some(source)),
            DownloadAction::AddedToQueue
        );

        // The download must fail rather than accept the substituted block.
        let result = tokio::time::timeout(Duration::from_secs(1), downloads.next())
            .await
            .expect("download completes")
            .expect("downloads stream is open");
        assert!(
            result.is_err(),
            "a substituted block must be rejected, not accepted as {result:?}",
        );

        // Cleanup must key on the requested hash: no stale queue or source-count
        // state may remain under the originally requested hash.
        let admission = downloads.spawner.admission();
        assert!(
            admission.cancel_handles.is_empty(),
            "queue entry under the requested hash must be removed",
        );
        assert!(
            admission.source_counts.is_empty(),
            "source accounting must be decremented for the requested hash",
        );
        assert!(admission.source_locks.is_empty());
        assert_eq!(admission.queue_len(), 0);

        Ok(())
    }

    /// Builds a [`zs::LatestChainTip`] reporting `height` and `hash` as the best tip.
    ///
    /// The tip block's contents are irrelevant to the height check, so an arbitrary block is
    /// reused and its identity fields overridden.
    fn chain_tip_at(
        height: block::Height,
        hash: block::Hash,
    ) -> (zs::ChainTipSender, zs::LatestChainTip) {
        let any_block: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_1_BYTES
            .zcash_deserialize_into()
            .expect("test vector deserializes");

        let mut tip_block: zs::ChainTipBlock =
            zs::SemanticallyVerifiedBlock::from(any_block).into();
        tip_block.hash = hash;
        tip_block.height = height;

        let (mut tip_sender, latest_chain_tip, _tip_change) =
            zs::ChainTipSender::new(None, &Network::Mainnet);
        tip_sender.set_finalized_tip(tip_block);

        (tip_sender, latest_chain_tip)
    }

    /// Moves the tip reported by a [`chain_tip_at`] sender.
    fn set_tip(tip_sender: &mut zs::ChainTipSender, height: block::Height, hash: block::Hash) {
        let any_block: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_1_BYTES
            .zcash_deserialize_into()
            .expect("test vector deserializes");

        let mut tip_block: zs::ChainTipBlock =
            zs::SemanticallyVerifiedBlock::from(any_block).into();
        tip_block.hash = hash;
        tip_block.height = height;

        tip_sender.set_finalized_tip(tip_block);
    }

    /// Builds a gossip [`Downloads`] whose network service returns `block` for any request.
    fn downloads_returning(
        block: Arc<Block>,
        advertiser_addr: PeerSocketAddr,
        latest_chain_tip: zs::LatestChainTip,
    ) -> Downloads<PendingNetwork, PendingVerifier, PendingState> {
        Downloads::new(
            MAX_INBOUND_CONCURRENCY,
            false,
            BoxCloneService::new(service_fn(move |_request| {
                let block = block.clone();
                async move {
                    Ok(zn::Response::Blocks(vec![Available((
                        block,
                        Some(advertiser_addr),
                    ))]))
                }
            })),
            BoxCloneService::new(service_fn(|_request| {
                future::pending::<Result<block::Hash, BoxError>>()
            })),
            // The download path asks the state whether it already has the block, before any
            // height check runs. Answering `None` lets the download proceed.
            BoxCloneService::new(service_fn(|request| async move {
                match request {
                    zs::Request::AnyChainBlock(_) => Ok(zs::Response::Block(None)),
                    request => Err(format!("unexpected state request: {request:?}").into()),
                }
            })),
            latest_chain_tip,
            Network::Mainnet,
        )
    }

    /// The gossip path must reject a tip child whose coinbase height was rewritten, and keep the
    /// advertiser so the peer can be scored.
    ///
    /// This is the path that matters most for miners: an `inv` for the new tip normally arrives
    /// here first, and honest peers' `inv`s for the same hash are dropped as `AlreadyQueued`
    /// while the poisoned download is outstanding.
    #[tokio::test]
    async fn gossiped_tip_child_rejects_poisoned_coinbase_height() {
        let canonical: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_1687107_BYTES
            .zcash_deserialize_into()
            .expect("test vector deserializes");
        let canonical_hash = canonical.hash();
        let parent_hash = canonical.header.previous_block_hash;

        let poisoned = poison_coinbase_height(&canonical, block::Height(1));
        assert_eq!(
            poisoned.hash(),
            canonical_hash,
            "the poisoned body still answers for the advertised hash"
        );

        let advertiser_addr: PeerSocketAddr = "127.0.0.1:8233".parse().expect("valid peer address");
        let (_tip_sender, latest_chain_tip) = chain_tip_at(block::Height(1_687_106), parent_hash);

        let mut downloads = downloads_returning(poisoned, advertiser_addr, latest_chain_tip);

        assert_eq!(
            downloads.download_and_verify(
                canonical_hash,
                Some(zn::PeerSource::LegacySocket(advertiser_addr)),
            ),
            DownloadAction::AddedToQueue
        );

        let (error, addr) = downloads
            .next()
            .await
            .expect("the download task produces a result")
            .expect_err("a poisoned tip child must be rejected");

        assert_eq!(
            addr,
            Some(advertiser_addr),
            "the advertiser must be preserved so Inbound can score the peer"
        );

        let mismatch = error
            .downcast_ref::<GossipedTipChildHeightMismatch>()
            .expect("the error must be the typed mismatch that Inbound scores");

        assert_eq!(mismatch.height, block::Height(1));
        assert_eq!(mismatch.expected_height, block::Height(1_687_107));
        assert_eq!(mismatch.hash, canonical_hash);
    }

    /// Weak-work gossip must fail before parent recovery or semantic verification.
    #[tokio::test]
    async fn mainnet_work_floor_rejects_gossip_before_parent_recovery() {
        use zakura_chain::work::difficulty::ParameterDifficulty as _;

        let floor = crate::components::download_work::MAINNET_WORK_FLOOR_HEIGHT;
        for tip_height in [floor.previous().unwrap(), floor] {
            // An unrelated parent skips tip-child authentication. Neither an old nor a
            // new claimed height can bypass the floor once our tip reaches the fixed height.
            for height in [floor.previous().unwrap(), floor, floor.next().unwrap()] {
                if tip_height < floor && height <= floor {
                    continue;
                }
                let canonical: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_1687107_BYTES
                    .zcash_deserialize_into()
                    .expect("test vector deserializes");
                let mut candidate = poison_coinbase_height(&canonical, height);
                let block = Arc::make_mut(&mut candidate);
                *Arc::make_mut(&mut block.transactions[0]).expiry_height_mut() = height;
                let header = Arc::make_mut(&mut block.header);
                header.previous_block_hash = hash(0x55);
                header.difficulty_threshold =
                    Network::Mainnet.target_difficulty_limit().to_compact();
                header.merkle_root = block.transactions.iter().map(|tx| tx.hash()).collect();
                let candidate_hash = candidate.hash();
                let advertiser_addr = "127.0.0.1:8233".parse().unwrap();
                let (_tip_sender, latest_chain_tip) = chain_tip_at(tip_height, hash(0xAA));
                let mut downloads =
                    downloads_returning(candidate, advertiser_addr, latest_chain_tip);
                downloads.spawner.verifier = BoxCloneService::new(service_fn(|_| async {
                    Err::<block::Hash, BoxError>(
                        "weak-work block reached semantic verification".into(),
                    )
                }));

                assert_eq!(
                    downloads.download_and_verify(
                        candidate_hash,
                        Some(zn::PeerSource::LegacySocket(advertiser_addr)),
                    ),
                    DownloadAction::AddedToQueue
                );
                let (error, addr) = tokio::time::timeout(Duration::from_secs(5), downloads.next())
                    .await
                    .expect("the work floor rejects without waiting on the parent")
                    .unwrap()
                    .unwrap_err();
                assert!(
                    error.to_string().contains("Mainnet admission floor"),
                    "{error}"
                );
                assert_eq!(addr, Some(advertiser_addr));
                assert!(crate::components::inbound::block_misbehavior(error, addr).is_none());
            }
        }
    }

    /// A gossiped block that is not a tip child keeps the existing behind-tip policy, and stays
    /// unattributed as before.
    #[tokio::test]
    async fn gossiped_non_tip_child_keeps_the_behind_tip_policy() {
        let block1: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_1_BYTES
            .zcash_deserialize_into()
            .expect("test vector deserializes");
        let block1_hash = block1.hash();

        let advertiser_addr: PeerSocketAddr = "127.0.0.1:8233".parse().expect("valid peer address");
        // A tip far ahead of block 1, which is not block 1's parent.
        let (_tip_sender, latest_chain_tip) = chain_tip_at(block::Height(1_000_000), hash(0x11));

        let mut downloads = downloads_returning(block1, advertiser_addr, latest_chain_tip);

        assert_eq!(
            downloads.download_and_verify(
                block1_hash,
                Some(zn::PeerSource::LegacySocket(advertiser_addr)),
            ),
            DownloadAction::AddedToQueue
        );

        let (error, addr) = downloads
            .next()
            .await
            .expect("the download task produces a result")
            .expect_err("a block behind the finalized tip is still dropped");

        assert!(
            error
                .downcast_ref::<GossipedTipChildHeightMismatch>()
                .is_none(),
            "a non-tip-child must not be reported as a height mismatch"
        );
        assert_eq!(addr, None, "the behind-tip policy is unchanged");
    }

    /// The poisoned-body re-request is bounded, so a second attacker cannot keep the gossip
    /// path re-requesting the same hash indefinitely.
    #[tokio::test]
    async fn poisoned_retries_are_bounded_per_hash() {
        let mut downloads = pending_downloads();
        let poisoned_hash = hash(1);

        assert_eq!(
            downloads.retry_poisoned(poisoned_hash),
            Some(DownloadAction::AddedToQueue),
            "the first retry dispatches a replacement download"
        );

        // The replacement is still in flight, so further retries are refused by the per-hash
        // dedupe. They still spend the budget, which is why `retry_poisoned` logs the action
        // rather than claiming the block was re-requested.
        for attempt in 2..=POISONED_GOSSIP_BLOCK_RETRY_LIMIT {
            assert_eq!(
                downloads.retry_poisoned(poisoned_hash),
                Some(DownloadAction::AlreadyQueued),
                "retry {attempt} is within the budget, but is refused while one is in flight"
            );
        }

        assert!(
            downloads.retry_poisoned(poisoned_hash).is_none(),
            "the block is left to the syncer once the budget is exhausted"
        );

        // The budget is per hash, so an unrelated block is unaffected.
        assert!(
            downloads.retry_poisoned(hash(2)).is_some(),
            "a different hash keeps its own budget"
        );

        // Exhaustion is sticky. Clearing the entry here would let a peer buy three more
        // re-requests by poisoning the same hash again.
        for _ in 0..3 {
            assert!(
                downloads.retry_poisoned(poisoned_hash).is_none(),
                "an exhausted budget must not re-arm for the same hash"
            );
        }
    }

    /// Poisoned-retry budgets are dropped when the tip moves.
    ///
    /// The syncer, not gossip, commonly resolves a block whose gossip budget was exhausted —
    /// that is exactly what exhaustion asks for — and the syncer's downloads never reach this
    /// stream's `poll_next`. Without tip scoping those entries would accumulate for the life of
    /// the process.
    #[tokio::test]
    async fn poisoned_retry_budgets_are_scoped_to_the_tip() {
        let (mut tip_sender, latest_chain_tip) = chain_tip_at(block::Height(100), hash(0xAA));
        let mut downloads = pending_downloads_with_tip(latest_chain_tip);
        let poisoned_hash = hash(1);

        for _ in 0..POISONED_GOSSIP_BLOCK_RETRY_LIMIT {
            assert!(downloads.retry_poisoned(poisoned_hash).is_some());
        }
        assert!(
            downloads.retry_poisoned(poisoned_hash).is_none(),
            "the budget is exhausted while the tip is unchanged"
        );
        assert_eq!(downloads.poisoned_retries.counts.len(), 1);

        // The block is resolved by the syncer, so the tip moves without this stream ever seeing
        // a successful download for the hash.
        set_tip(&mut tip_sender, block::Height(101), hash(0xBB));

        assert!(
            downloads.retry_poisoned(hash(2)).is_some(),
            "a child of the new tip gets a fresh budget"
        );
        assert!(
            !downloads
                .poisoned_retries
                .counts
                .contains_key(&poisoned_hash),
            "the stale entry must be dropped when the tip moves, not held for the process life"
        );
        assert_eq!(downloads.poisoned_retries.counts.len(), 1);
    }

    /// A downloaded block releases its budget, so a later poisoning of the same hash starts
    /// fresh.
    ///
    /// This is the one release path the `Downloads`-level tests cannot reach: they use
    /// `pending_downloads`, whose downloads never complete.
    #[test]
    fn a_downloaded_block_releases_its_budget() {
        let mut budgets = PoisonedRetryBudgets::default();
        let tip = Some(hash(0xAA));
        let poisoned_hash = hash(1);

        for _ in 0..POISONED_GOSSIP_BLOCK_RETRY_LIMIT {
            assert!(budgets.consume(poisoned_hash, tip).is_some());
        }
        assert_eq!(budgets.consume(poisoned_hash, tip), None);

        budgets.release(&poisoned_hash);

        assert_eq!(
            budgets.consume(poisoned_hash, tip),
            Some(1),
            "the budget restarts once the block has actually been downloaded"
        );
        assert_eq!(
            budgets.consume(hash(2), tip),
            Some(1),
            "releasing one hash leaves the others alone"
        );
    }
}