zebrad 7.2.0

The Zcash Foundation's 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
//! Fixed test vectors for the inbound gossip block download stream.
//!
//! These are the inbound-gossip siblings of the sync-path tests in
//! `crate::components::sync::downloads::tests`: they cover GHSA-4f6v-mj46-gxg3, where a peer
//! answers a `BlockDownload` request with a canonical header and a rewritten coinbase height. The
//! coinbase scriptSig is excluded from the V5 transaction ID (ZIP-244), so the block hash is
//! unchanged and the response passes the hash check, but the forged height is dropped as too far
//! ahead of the tip, or behind the finalized tip, before consensus validation. The supplying peer
//! must be scored only when the parent header Zebra holds proves the height was rewritten.

use std::{
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::Duration,
};

use futures::stream::StreamExt;
use metrics::{
    Counter, Gauge, Histogram, HistogramFn, Key, KeyName, Metadata, Recorder, SharedString, Unit,
};

use zebra_chain::{
    block::{Block, Height},
    chain_tip::mock::MockChainTip,
    serialization::ZcashDeserializeInto,
};
use zebra_network::{InventoryResponse, PeerSocketAddr};
use zebra_state::MAX_BLOCK_REORG_HEIGHT;
use zebra_test::mock_service::{MockService, PanicAssertion};

use zebra_network as zn;
use zebra_state as zs;

use super::{DownloadAction, Downloads, HeightLimitError, MIN_CONCURRENCY_LIMIT};

use InventoryResponse::*;

/// Maximum time to wait for a request to any test service.
///
/// These tests use only in-process mocks and pause Tokio time, preserving the full no-request
/// observation window without spending that time idle.
const MAX_SERVICE_REQUEST_DELAY: Duration = Duration::from_millis(1000);

/// A peer address used to check whether the supplying peer can be scored.
const ADVERTISER: &str = "127.0.0.1:8233";

type MockNetwork = MockService<zn::Request, zn::Response, PanicAssertion>;
type MockVerifier = MockService<zebra_consensus::Request, zebra_chain::block::Hash, PanicAssertion>;
type MockState = MockService<zs::Request, zs::Response, PanicAssertion>;

/// Build an inbound gossip downloader whose state tip is at `tip_height`, returning the mock
/// network, verifier, and state services so a test can drive and assert on them.
#[allow(clippy::type_complexity)]
fn mock_downloads(
    tip_height: Height,
) -> (
    Downloads<MockNetwork, MockVerifier, MockState, MockChainTip>,
    MockNetwork,
    MockVerifier,
    MockState,
) {
    let network: MockNetwork = MockService::build()
        .with_max_request_delay(MAX_SERVICE_REQUEST_DELAY)
        .for_unit_tests();

    let verifier: MockVerifier = MockService::build()
        .with_max_request_delay(MAX_SERVICE_REQUEST_DELAY)
        .for_unit_tests();

    let state: MockState = MockService::build()
        .with_max_request_delay(MAX_SERVICE_REQUEST_DELAY)
        .for_unit_tests();

    let (latest_chain_tip, chain_tip_sender) = MockChainTip::new();
    chain_tip_sender.send_best_tip_height(tip_height);
    // Dropping the sender is fine: `watch::Receiver::borrow` keeps returning the height we just
    // sent, and no test changes the tip mid-run.

    let downloads = Downloads::new(
        MIN_CONCURRENCY_LIMIT,
        network.clone(),
        verifier.clone(),
        state.clone(),
        latest_chain_tip,
    );

    (downloads, network, verifier, state)
}

/// Load the mainnet block 1 vector, which these tests use as a low-height block body.
fn block_1() -> Arc<Block> {
    zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .expect("hard-coded block vector deserializes")
}

/// Load the mainnet block 2 vector.
fn block_2() -> Arc<Block> {
    zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .expect("hard-coded block vector deserializes")
}

/// Load the mainnet genesis block vector.
fn genesis() -> Arc<Block> {
    zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
        .zcash_deserialize_into()
        .expect("hard-coded block vector deserializes")
}

/// Load the mainnet block 10 vector, which the far-ahead tests use as a high-height block body.
fn block_10() -> Arc<Block> {
    zebra_test::vectors::BLOCK_MAINNET_10_BYTES
        .zcash_deserialize_into()
        .expect("hard-coded block vector deserializes")
}

/// The tip height that puts block 2 exactly on the lookahead limit.
///
/// The downloader accepts blocks up to `MIN_CONCURRENCY_LIMIT` above the tip, so block 10 is far
/// ahead of this tip, and block 2 is the highest block it still verifies.
fn lookahead_boundary_tip() -> Height {
    Height(2 - u32::try_from(MIN_CONCURRENCY_LIMIT).expect("small constant fits in u32"))
}

/// Regression test for GHSA-4f6v-mj46-gxg3: a gossiped body whose claimed height contradicts the
/// parent we already hold is attributed to the peer that supplied it, and never reaches consensus.
///
/// A peer can answer with a canonical header and rewritten coinbase height because the initial hash
/// check does not recompute the header's commitment to the body's authorizing data. The parent is
/// the proof: a block's height is one more than its parent's.
#[tokio::test(start_paused = true)]
async fn contradicted_behind_tip_height_is_attributed_and_never_verified() {
    let _init_guard = zebra_test::init();

    // The tip is far enough ahead that a claimed height of 1 is behind the reorg limit.
    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(Height(2 * MAX_BLOCK_REORG_HEIGHT));

    // Block 2's header with block 1's body: the hash and parent are block 2's, because the hash
    // covers only the header, but the coinbase now claims height 1 instead of 2. This is the shape
    // of the reported attack, without reproducing the hash-preserving rewrite itself.
    let block_1 = block_1();
    let block_2 = block_2();
    let block = Arc::new(Block {
        header: block_2.header.clone(),
        transactions: block_1.transactions.clone(),
    });
    let hash = block.hash();
    assert_eq!(
        hash,
        block_2.hash(),
        "the block hash covers only the header"
    );
    assert_eq!(
        block.coinbase_height(),
        Some(Height(1)),
        "the body must claim the height the downloader reads"
    );

    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    // The block is not already in the state.
    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    // We hold the real parent, block 1, so the body's real height is 2, not the 1 it claims.
    state
        .expect_request(zs::Request::BlockHeader(
            block.header.previous_block_hash.into(),
        ))
        .await
        .respond(zs::Response::BlockHeader {
            header: block_1.header.clone(),
            hash: block_1.hash(),
            height: Height(1),
            next_block_hash: Some(hash),
        });

    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block behind the reorg limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::BehindTip { .. })
        ),
        "a contradicted behind-tip height must be a scoreable typed error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr,
        Some(advertiser),
        "a contradicted behind-tip height must attribute the drop to the supplying peer"
    );

    // The rewritten body is dropped before consensus validation, which is why the peer must be
    // scored on this path instead.
    verifier.expect_no_requests().await;
}

/// A peer that serves a genuinely old block is not attributed, so it cannot be scored.
///
/// Its height agrees with its parent's, so there is no proof of misbehaviour and the drop must stay
/// anonymous.
#[tokio::test(start_paused = true)]
async fn genuinely_old_block_is_dropped_without_attribution() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(Height(2 * MAX_BLOCK_REORG_HEIGHT));

    let block = block_1();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    // The parent is genesis, one below the height the body claims: the body is authentic.
    let genesis = genesis();
    assert_eq!(
        block.header.previous_block_hash,
        genesis.hash(),
        "block 1's parent is genesis"
    );
    state
        .expect_request(zs::Request::BlockHeader(
            block.header.previous_block_hash.into(),
        ))
        .await
        .respond(zs::Response::BlockHeader {
            header: genesis.header.clone(),
            hash: genesis.hash(),
            height: Height(0),
            next_block_hash: Some(hash),
        });

    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block behind the reorg limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::BehindTip { .. })
        ),
        "an old block must still be a typed behind-tip error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr, None,
        "an authentic old block must not be attributed to its peer"
    );

    verifier.expect_no_requests().await;
}

/// A peer whose old block has a parent we do not hold is not attributed either: without the parent
/// there is no proof the height was rewritten.
#[tokio::test(start_paused = true)]
async fn behind_tip_block_with_unknown_parent_is_not_attributed() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(Height(2 * MAX_BLOCK_REORG_HEIGHT));

    let block = block_1();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    state
        .expect_request(zs::Request::BlockHeader(
            block.header.previous_block_hash.into(),
        ))
        .await
        .respond(Err(zn::BoxError::from("block not found in any chain")));

    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block behind the reorg limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::BehindTip { .. })
        ),
        "a behind-tip drop must be a typed error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr, None,
        "a block whose parent we do not hold must not be attributed"
    );

    verifier.expect_no_requests().await;
}

/// The parent lookup is bounded: when the state does not answer, the block is still dropped and the
/// peer is still not attributed.
///
/// Paused time lets the runtime advance past `PARENT_LOOKUP_TIMEOUT` as soon as the download task is
/// the only thing waiting, so the test does not sleep for real.
#[tokio::test(start_paused = true)]
async fn behind_tip_parent_lookup_timeout_is_not_attributed() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(Height(2 * MAX_BLOCK_REORG_HEIGHT));

    let block = block_1();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    // The parent lookup is deliberately never answered, so it can only end by timing out.
    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block behind the reorg limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::BehindTip { .. })
        ),
        "a timed-out lookup must still drop with a typed error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr, None,
        "a timed-out parent lookup must not attribute the drop"
    );

    verifier.expect_no_requests().await;
}

/// A block at the oldest height that is still within the reorg limit is verified, not dropped.
///
/// This is the guard against dropping and attributing honest near-boundary blocks:
/// `min_accepted_height` is the boundary, and the behind-tip comparison is strict, so a block
/// exactly on it is a normal download and the parent is never consulted.
#[tokio::test(start_paused = true)]
async fn block_at_reorg_boundary_is_verified_not_dropped() {
    let _init_guard = zebra_test::init();

    // `min_accepted_height` is `Height(1)`, so the height-1 block sits exactly on the boundary.
    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(Height(MAX_BLOCK_REORG_HEIGHT + 1));

    let block = block_1();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    verifier
        .expect_request(zebra_consensus::Request::Commit(block))
        .await
        .respond(hash);

    assert_eq!(
        downloads
            .next()
            .await
            .expect("downloads is non-empty")
            .expect("block on the reorg boundary is verified"),
        hash,
        "a block at min_accepted_height must be verified, not dropped as behind the tip"
    );

    // The parent lookup only runs on the behind-tip drop path, so a boundary block must not trigger
    // one.
    state.expect_no_requests().await;
}

/// The far-ahead sibling of the regression test for GHSA-4f6v-mj46-gxg3: a gossiped body whose
/// claimed height is above the lookahead limit, and contradicts the parent we already hold, is
/// attributed to the peer that supplied it, and never reaches consensus.
///
/// The sync path deliberately leaves its far-ahead drops unscored (GHSA-qhr3-cvch-5fh2), because
/// the serving peer did not choose the height of a genuine block. Here the parent is the proof, so
/// scoring is safe: a genuine block whose parent we hold is at most one above the tip, so its real
/// height is never far ahead.
#[tokio::test(start_paused = true)]
async fn contradicted_far_ahead_height_is_attributed_and_never_verified() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(lookahead_boundary_tip());

    // Block 2's header with block 10's body: the hash and parent are block 2's, because the hash
    // covers only the header, but the coinbase now claims height 10 instead of 2.
    let block_2 = block_2();
    let block_10 = block_10();
    let block = Arc::new(Block {
        header: block_2.header.clone(),
        transactions: block_10.transactions.clone(),
    });
    let hash = block.hash();
    assert_eq!(
        hash,
        block_2.hash(),
        "the block hash covers only the header"
    );
    assert_eq!(
        block.coinbase_height(),
        Some(Height(10)),
        "the body must claim the height the downloader reads"
    );

    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    // We hold the real parent, block 1, so the body's real height is 2, not the 10 it claims.
    let block_1 = block_1();
    state
        .expect_request(zs::Request::BlockHeader(
            block.header.previous_block_hash.into(),
        ))
        .await
        .respond(zs::Response::BlockHeader {
            header: block_1.header.clone(),
            hash: block_1.hash(),
            height: Height(1),
            next_block_hash: Some(hash),
        });

    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block above the lookahead limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::AboveLookahead { .. })
        ),
        "a contradicted far-ahead height must be a scoreable typed error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr,
        Some(advertiser),
        "a contradicted far-ahead height must attribute the drop to the supplying peer"
    );

    verifier.expect_no_requests().await;
}

/// A peer that serves a genuinely far-ahead block is not attributed, so it cannot be scored.
///
/// This is the common case while Zebra is catching up: the block's parent is not in the state yet,
/// so there is no proof of misbehaviour and the drop must stay anonymous.
#[tokio::test(start_paused = true)]
async fn genuinely_far_ahead_block_is_dropped_without_attribution() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(lookahead_boundary_tip());

    let block = block_10();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    // The parent, block 9, is far ahead too, so we do not hold it.
    state
        .expect_request(zs::Request::BlockHeader(
            block.header.previous_block_hash.into(),
        ))
        .await
        .respond(Err(zn::BoxError::from("block hash or height not found")));

    let (error, advertiser_addr) = downloads
        .next()
        .await
        .expect("downloads is non-empty")
        .expect_err("block above the lookahead limit is dropped");

    assert!(
        matches!(
            error.downcast_ref::<HeightLimitError>(),
            Some(HeightLimitError::AboveLookahead { .. })
        ),
        "a far-ahead drop must be a typed error, but was: {error:?}"
    );
    assert_eq!(
        advertiser_addr, None,
        "a genuinely far-ahead block must not be attributed to its peer"
    );

    verifier.expect_no_requests().await;
}

/// A block at the highest height that is still within the lookahead limit is verified, not dropped.
///
/// This is the guard against dropping and attributing honest near-boundary blocks:
/// `max_lookahead_height` is the boundary, and the far-ahead comparison is strict, so a block exactly
/// on it is a normal download and the parent is never consulted.
#[tokio::test(start_paused = true)]
async fn block_at_lookahead_boundary_is_verified_not_dropped() {
    let _init_guard = zebra_test::init();

    let (mut downloads, mut network, mut verifier, mut state) =
        mock_downloads(lookahead_boundary_tip());

    let block = block_2();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(
        matches!(
            downloads.download_and_verify(hash, Some(advertiser)),
            DownloadAction::AddedToQueue
        ),
        "download is queued"
    );

    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block.clone(),
            Some(advertiser),
        ))]));

    verifier
        .expect_request(zebra_consensus::Request::Commit(block))
        .await
        .respond(hash);

    assert_eq!(
        downloads
            .next()
            .await
            .expect("downloads is non-empty")
            .expect("block on the lookahead boundary is verified"),
        hash,
        "a block at max_lookahead_height must be verified, not dropped as far ahead"
    );

    // The parent lookup only runs on the height limit drop paths, so a boundary block must not
    // trigger one.
    state.expect_no_requests().await;
}

mod network_checkpoint;

/// A gossip download cannot wait indefinitely for readiness or reset its budget at dispatch.
#[tokio::test(start_paused = true)]
async fn download_deadline_includes_readiness_and_response() {
    use tokio::time::{sleep, timeout_at, Instant};
    use tower::{limit::ConcurrencyLimit, ServiceExt};

    let _init_guard = zebra_test::init();
    let budget = zn::constants::REQUEST_TIMEOUT + super::BLOCK_DOWNLOAD_TIMEOUT;
    for release_capacity in [false, true] {
        let mut network: MockNetwork = MockService::build().for_unit_tests();
        let limited = ConcurrencyLimit::new(network.clone(), 1);
        let mut reservation = limited.clone();
        reservation.ready().await.unwrap();
        let verifier: MockVerifier = MockService::build().for_unit_tests();
        let mut state: MockState = MockService::build().for_unit_tests();
        let (tip, _sender) = MockChainTip::new();
        let mut downloads = Downloads::new(2, limited, verifier, state.clone(), tip);
        let hash = block_1().hash();
        assert!(matches!(
            downloads.download_and_verify(hash, None),
            DownloadAction::AddedToQueue,
        ));
        state
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
        let started = Instant::now();
        tokio::task::yield_now().await;
        let _response = if release_capacity {
            sleep(budget / 2).await;
            drop(reservation);
            Some(
                network
                    .expect_request(zn::Request::BlockDownload {
                        hash,
                        advertiser: None,
                    })
                    .await,
            )
        } else {
            None
        };
        let (error, advertiser) =
            timeout_at(started + budget + Duration::from_secs(1), downloads.next())
                .await
                .expect("gossip readiness and response must be bounded")
                .expect("the queued download has a result")
                .expect_err("the unanswered download expires");
        assert!(error.is::<tokio::time::error::Elapsed>());
        assert_eq!(advertiser, None);
        assert_eq!(Instant::now() - started, budget);
    }
}

/// The sample count and the most recent sample of one histogram.
#[derive(Default)]
struct Samples {
    count: AtomicU64,
    last: AtomicU64,
}

impl Samples {
    fn get(&self) -> (u64, f64) {
        (
            self.count.load(Ordering::SeqCst),
            f64::from_bits(self.last.load(Ordering::SeqCst)),
        )
    }
}

impl HistogramFn for Samples {
    fn record(&self, value: f64) {
        self.last.store(value.to_bits(), Ordering::SeqCst);
        self.count.fetch_add(1, Ordering::SeqCst);
    }
}

/// Records the gossiped block timing histograms and ignores every other metric.
#[derive(Default)]
struct GossipTimingRecorder {
    download: Arc<Samples>,
    verify_commit: Arc<Samples>,
}

impl Recorder for GossipTimingRecorder {
    fn describe_counter(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
    fn describe_gauge(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
    fn describe_histogram(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}

    fn register_counter(&self, _: &Key, _: &Metadata<'_>) -> Counter {
        Counter::noop()
    }

    fn register_gauge(&self, _: &Key, _: &Metadata<'_>) -> Gauge {
        Gauge::noop()
    }

    fn register_histogram(&self, key: &Key, _: &Metadata<'_>) -> Histogram {
        let samples = match key.name() {
            "gossip.block.download.duration_seconds" => &self.download,
            "gossip.block.verify_commit.duration_seconds" => &self.verify_commit,
            _ => return Histogram::noop(),
        };
        assert_eq!(
            key.labels().count(),
            0,
            "gossip timing histograms are unlabeled"
        );
        Histogram::from_arc(samples.clone())
    }
}

/// A verified gossiped block records how long its download and its verification and commit took.
#[tokio::test(start_paused = true)]
async fn verified_block_records_download_and_verify_durations() {
    const DOWNLOAD: Duration = Duration::from_millis(7);
    const VERIFY: Duration = Duration::from_millis(3);

    // The current-thread runtime runs the download task on this thread, so the local recorder
    // sees it.
    let recorder = GossipTimingRecorder::default();
    let _recorder_guard = metrics::set_default_local_recorder(&recorder);
    let (mut downloads, mut network, mut verifier, mut state) = mock_downloads(Height(0));
    let block = block_1();
    let hash = block.hash();
    let advertiser: PeerSocketAddr = ADVERTISER.parse().expect("hard-coded address is valid");

    assert!(matches!(
        downloads.download_and_verify(hash, Some(advertiser)),
        DownloadAction::AddedToQueue
    ));
    state
        .expect_request(zs::Request::KnownBlock(hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    let download = network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: Some(advertiser),
        })
        .await;
    tokio::time::advance(DOWNLOAD).await;
    download.respond(zn::Response::Blocks(vec![Available((
        block.clone(),
        Some(advertiser),
    ))]));
    let verify = verifier
        .expect_request(zebra_consensus::Request::Commit(block))
        .await;
    assert_eq!(recorder.download.get(), (1, DOWNLOAD.as_secs_f64()));
    assert_eq!(
        recorder.verify_commit.get().0,
        0,
        "the block is not verified yet"
    );
    tokio::time::advance(VERIFY).await;
    verify.respond(hash);

    assert_eq!(
        downloads
            .next()
            .await
            .expect("downloads is non-empty")
            .expect("the block is verified"),
        hash,
    );
    assert_eq!(recorder.download.get(), (1, DOWNLOAD.as_secs_f64()));
    assert_eq!(recorder.verify_commit.get(), (1, VERIFY.as_secs_f64()));
}

/// Only failures that score the peer, and that the block verifier returns after its part of the
/// checks that authenticate a block for early relay, can be exempt from scoring for a peer that
/// negotiated compact block relay.
///
/// Failures of those checks keep their score, including subsidy failures with the same shape as
/// the miner fee failures. So do bodies that don't match their authorizing data commitment, and
/// all the checkpoint verifier's failures.
#[test]
fn only_scored_failures_after_the_early_relay_checks_are_later_validation_failures() {
    use zebra_chain::{
        block::{merkle, CommitmentError},
        parameters::subsidy::SubsidyError,
    };
    use zebra_consensus::{
        error::TransactionError, router::RouterError, BlockError, VerifyBlockError,
        VerifyCheckpointError, MAX_BLOCK_SIGOPS,
    };

    use super::is_later_validation_failure;

    let _init_guard = zebra_test::init();

    let hash = block_1().hash();
    let height = Height(1);
    let subsidy = |error| VerifyBlockError::Block {
        source: BlockError::Transaction(TransactionError::Subsidy(error)),
    };

    let later_failures = [
        VerifyBlockError::Transaction(TransactionError::BadBalance),
        VerifyBlockError::Block {
            source: BlockError::TooManyTransparentSignatureOperations {
                height,
                hash,
                sigops: MAX_BLOCK_SIGOPS + 1,
            },
        },
        subsidy(SubsidyError::InvalidMinerFees),
        subsidy(SubsidyError::Overflow),
    ];
    for error in later_failures {
        assert_ne!(error.misbehavior_score(), 0, "{error:?}");
        assert!(is_later_validation_failure(&error), "{error:?}");
        let error = RouterError::from(error);
        assert!(is_later_validation_failure(&error), "{error:?}");
    }

    let auth_commitment_mismatch =
        VerifyBlockError::Commit(zs::CommitBlockError::ValidateContextError(Box::new(
            zs::ValidateContextError::InvalidBlockCommitment(
                CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
                    expected: [1; 32],
                    actual: [2; 32],
                },
            ),
        )));
    let early_relay_check_failures = [
        VerifyBlockError::Block {
            source: BlockError::BadMerkleRoot {
                actual: merkle::Root([1; 32]),
                expected: merkle::Root([2; 32]),
            },
        },
        VerifyBlockError::Block {
            source: BlockError::InvalidDifficulty(height, hash),
        },
        VerifyBlockError::Block {
            source: BlockError::Transaction(TransactionError::CoinbasePosition),
        },
        subsidy(SubsidyError::FundingStreamNotFound),
        VerifyBlockError::Subsidy(SubsidyError::NoCoinbase),
        auth_commitment_mismatch,
    ];
    for error in early_relay_check_failures {
        assert_ne!(error.misbehavior_score(), 0, "{error:?}");
        assert!(!is_later_validation_failure(&error), "{error:?}");
        let error = RouterError::from(error);
        assert!(!is_later_validation_failure(&error), "{error:?}");
    }

    let checkpoint = RouterError::from(VerifyCheckpointError::CoinbaseHeight { hash });
    assert_ne!(checkpoint.misbehavior_score(), 0);
    assert!(!is_later_validation_failure(&checkpoint));

    // A failure that doesn't score the peer has nothing to exempt.
    let duplicate = VerifyBlockError::Commit(zs::CommitBlockError::Duplicate {
        hash_or_height: None,
        location: zs::KnownBlock::BestChain,
    });
    assert_eq!(duplicate.misbehavior_score(), 0);
    assert!(!is_later_validation_failure(&duplicate));

    // Other errors, like verification timeouts, aren't block verifier failures.
    let local_error = zn::BoxError::from("block verification timed out");
    assert!(!is_later_validation_failure(&*local_error));
}

/// A peer gets at most one unpenalized later failure per parent block, for a block that passed the
/// checks that authenticate it for early relay. Every other later failure on that parent is scored.
/// Peers are grouped like bans, so another port, or another address in the same IPv6 `/64`, doesn't
/// get another allowance for the same parent.
#[test]
fn early_relay_allowance_is_one_failure_per_peer_group_and_parent() {
    use zebra_chain::block;

    use super::EarlyRelayAllowances;

    let _init_guard = zebra_test::init();

    let peer: PeerSocketAddr = "192.0.2.1:8233"
        .parse()
        .expect("hard-coded address is valid");
    let parent = block::Hash([1; 32]);
    let other_parent = block::Hash([2; 32]);

    let mut allowances = EarlyRelayAllowances::default();
    assert!(
        allowances.try_use(peer, parent),
        "the first failure is allowed",
    );
    assert!(
        !allowances.try_use(peer, parent),
        "another failure on the same parent is scored",
    );
    assert!(
        !allowances.try_use(peer, parent),
        "every later failure on the same parent is scored",
    );

    assert!(
        allowances.try_use(peer, other_parent),
        "a failure on another parent is allowed",
    );

    let other_peer: PeerSocketAddr = "192.0.2.2:8233"
        .parse()
        .expect("hard-coded address is valid");
    assert!(
        allowances.try_use(other_peer, parent),
        "another peer's failure on the same parent is allowed",
    );

    let same_ip = "192.0.2.1:18233"
        .parse()
        .expect("hard-coded address is valid");
    let ipv4_mapped = "[::ffff:192.0.2.1]:8233"
        .parse()
        .expect("hard-coded address is valid");
    let ipv6_peer = "[2001:db8::1]:8233"
        .parse()
        .expect("hard-coded address is valid");
    let same_ipv6_group = "[2001:db8::ffff:2]:8233"
        .parse()
        .expect("hard-coded address is valid");
    let other_ipv6_group = "[2001:db8:0:1::1]:8233"
        .parse()
        .expect("hard-coded address is valid");
    assert!(
        !allowances.try_use(same_ip, parent),
        "another port of the same IP is the same peer group",
    );
    assert!(
        !allowances.try_use(ipv4_mapped, parent),
        "an IPv4-mapped IPv6 address is the same peer group",
    );
    assert!(allowances.try_use(ipv6_peer, parent));
    assert!(
        !allowances.try_use(same_ipv6_group, parent),
        "another address in the same IPv6 /64 is the same peer group",
    );
    assert!(
        allowances.try_use(other_ipv6_group, parent),
        "an address in another IPv6 /64 is another peer group",
    );
}

/// Returns a distinct block hash for each `n`.
fn numbered_hash(n: usize) -> zebra_chain::block::Hash {
    let mut hash = [0; 32];
    let n = u64::try_from(n).expect("test numbers are small");
    hash[..8].copy_from_slice(&n.to_le_bytes());
    zebra_chain::block::Hash(hash)
}

/// The allowances that have been used are bounded, and the oldest ones are forgotten first.
#[test]
fn early_relay_allowances_forget_the_oldest_first() {
    use super::{EarlyRelayAllowances, MAX_EARLY_RELAY_ALLOWANCES};

    let _init_guard = zebra_test::init();

    let peer: PeerSocketAddr = "192.0.2.1:8233"
        .parse()
        .expect("hard-coded address is valid");
    let parent = numbered_hash;

    let mut allowances = EarlyRelayAllowances::default();
    for n in 0..MAX_EARLY_RELAY_ALLOWANCES {
        assert!(allowances.try_use(peer, parent(n)));
    }
    assert!(
        !allowances.try_use(peer, parent(0)),
        "the oldest allowance is still used while the set is full",
    );

    // One more allowance forgets the oldest one, and only that one.
    assert!(allowances.try_use(peer, parent(MAX_EARLY_RELAY_ALLOWANCES)));
    assert!(
        !allowances.try_use(peer, parent(1)),
        "the second oldest allowance is still used",
    );
    assert!(
        !allowances.try_use(peer, parent(MAX_EARLY_RELAY_ALLOWANCES)),
        "the newest allowance is still used",
    );
    assert!(
        allowances.try_use(peer, parent(0)),
        "the oldest allowance is forgotten",
    );
}

/// The rejected early relay blocks that a downloader remembers are bounded, and the oldest ones are
/// forgotten first.
#[test]
fn rejected_early_blocks_forget_the_oldest_first() {
    use indexmap::IndexSet;

    use super::{remember_rejected_early_block, MAX_REJECTED_EARLY_BLOCKS};

    let _init_guard = zebra_test::init();

    let mut rejected = IndexSet::new();
    for n in 0..MAX_REJECTED_EARLY_BLOCKS {
        remember_rejected_early_block(&mut rejected, numbered_hash(n));
    }
    remember_rejected_early_block(&mut rejected, numbered_hash(0));
    assert!(
        rejected.contains(&numbered_hash(0)),
        "a block that is already remembered doesn't forget the oldest one",
    );

    remember_rejected_early_block(&mut rejected, numbered_hash(MAX_REJECTED_EARLY_BLOCKS));
    assert_eq!(rejected.len(), MAX_REJECTED_EARLY_BLOCKS);
    assert!(
        !rejected.contains(&numbered_hash(0)),
        "the oldest block is forgotten",
    );
    assert!(
        rejected.contains(&numbered_hash(1)),
        "the second oldest block is still remembered",
    );
    assert!(
        rejected.contains(&numbered_hash(MAX_REJECTED_EARLY_BLOCKS)),
        "the newest block is remembered",
    );
}