zebrad 4.3.1

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
//! Fixed test vectors for the mempool.

#![allow(clippy::unwrap_in_result)]

use std::{sync::Arc, time::Duration};

use color_eyre::Report;
use tokio::time::{self, timeout};
use tower::{ServiceBuilder, ServiceExt};

use rand::{seq::SliceRandom, thread_rng};
use zebra_chain::{
    amount::Amount,
    block::Block,
    fmt::humantime_seconds,
    parameters::Network,
    serialization::ZcashDeserializeInto,
    transaction::{Transaction, VerifiedUnminedTx},
    transparent::{self, OutPoint},
};
use zebra_consensus::transaction as tx;
use zebra_state::{Config as StateConfig, CHAIN_TIP_UPDATE_WAIT_LIMIT};
use zebra_test::mock_service::{MockService, PanicAssertion};

use crate::components::{
    mempool::{self, *},
    sync::RecentSyncLengths,
};

/// A [`MockService`] representing the network service.
type MockPeerSet = MockService<zn::Request, zn::Response, PanicAssertion>;

/// The unmocked Zebra state service's type.
type StateService = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;

/// A [`MockService`] representing the Zebra transaction verifier service.
type MockTxVerifier = MockService<tx::Request, tx::Response, PanicAssertion, TransactionError>;

#[tokio::test]
async fn mempool_service_basic() -> Result<(), Report> {
    // Test multiple times to catch intermittent bugs since eviction is randomized
    for _ in 0..10 {
        mempool_service_basic_single().await?;
    }
    Ok(())
}

async fn mempool_service_basic_single() -> Result<(), Report> {
    // Using the mainnet for now
    let network = Network::Mainnet;

    // get the genesis block transactions from the Zcash blockchain.
    let mut unmined_transactions = network.unmined_transactions_in_blocks(1..=10);
    let genesis_transaction = unmined_transactions
        .next()
        .expect("Missing genesis transaction");
    let last_transaction = unmined_transactions.next_back().unwrap();
    let more_transactions = unmined_transactions.collect::<Vec<_>>();

    // Use as cost limit the costs of all transactions that will be
    // inserted except one (the genesis block transaction).
    let cost_limit = more_transactions.iter().map(|tx| tx.cost()).sum();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    // Enable the mempool
    service.enable(&mut recent_syncs).await;

    // Insert the genesis block coinbase transaction into the mempool storage.
    let mut inserted_ids = HashSet::new();
    service
        .storage()
        .insert(genesis_transaction.clone(), Vec::new(), None)?;
    inserted_ids.insert(genesis_transaction.transaction.id);

    // Test `Request::TransactionIds`
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::TransactionIds)
        .await
        .unwrap();
    let genesis_transaction_ids = match response {
        Response::TransactionIds(ids) => ids,
        _ => unreachable!("will never happen in this test"),
    };

    // Test `Request::TransactionsById`
    let genesis_transactions_hash_set = genesis_transaction_ids
        .iter()
        .copied()
        .collect::<HashSet<_>>();
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::TransactionsById(
            genesis_transactions_hash_set.clone(),
        ))
        .await
        .unwrap();
    let transactions = match response {
        Response::Transactions(transactions) => transactions,
        _ => unreachable!("will never happen in this test"),
    };

    // Make sure the transaction from the blockchain test vector is the same as the
    // response of `Request::TransactionsById`
    assert_eq!(genesis_transaction.transaction, transactions[0]);

    // Test `Request::TransactionsByMinedId`
    // TODO: use a V5 tx to test if it's really matched by mined ID
    let genesis_transactions_mined_hash_set = genesis_transaction_ids
        .iter()
        .map(|txid| txid.mined_id())
        .collect::<HashSet<_>>();
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::TransactionsByMinedId(
            genesis_transactions_mined_hash_set,
        ))
        .await
        .unwrap();
    let transactions = match response {
        Response::Transactions(transactions) => transactions,
        _ => unreachable!("will never happen in this test"),
    };

    // Make sure the transaction from the blockchain test vector is the same as the
    // response of `Request::TransactionsByMinedId`
    assert_eq!(genesis_transaction.transaction, transactions[0]);

    // Insert more transactions into the mempool storage.
    // This will cause the genesis transaction to be moved into rejected.
    // Skip the last (will be used later)
    for tx in more_transactions {
        inserted_ids.insert(tx.transaction.id);
        // Error must be ignored because a insert can trigger an eviction and
        // an error is returned if the transaction being inserted in chosen.
        let _ = service.storage().insert(tx.clone(), Vec::new(), None);
    }

    // Test `Request::RejectedTransactionIds`
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::RejectedTransactionIds(
            genesis_transactions_hash_set,
        ))
        .await
        .unwrap();
    let rejected_ids = match response {
        Response::RejectedTransactionIds(ids) => ids,
        _ => unreachable!("will never happen in this test"),
    };

    assert!(rejected_ids.is_subset(&inserted_ids));

    // Test `Request::Queue`
    // Use the ID of the last transaction in the list
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![last_transaction.transaction.id.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());
    assert_eq!(service.tx_downloads().in_flight(), 1);

    // Test `Request::QueueStats`
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::QueueStats)
        .await
        .unwrap();

    let (actual_size, actual_bytes, actual_usage) = match response {
        Response::QueueStats {
            size,
            bytes,
            usage,
            fully_notified: None,
        } => (size, bytes, usage),
        _ => unreachable!("expected QueueStats response"),
    };

    // Expected values based on storage contents
    let expected_size = service.storage().transaction_count();
    let expected_bytes: usize = service
        .storage()
        .transactions()
        .values()
        .map(|tx| tx.transaction.size)
        .sum();

    // TODO: Derive memory usage when available
    let expected_usage = expected_bytes;

    assert_eq!(actual_size, expected_size, "QueueStats size mismatch");
    assert_eq!(actual_bytes, expected_bytes, "QueueStats bytes mismatch");
    assert_eq!(actual_usage, expected_usage, "QueueStats usage mismatch");

    Ok(())
}

#[tokio::test]
async fn mempool_queue() -> Result<(), Report> {
    // Test multiple times to catch intermittent bugs since eviction is randomized
    for _ in 0..10 {
        mempool_queue_single().await?;
    }
    Ok(())
}

async fn mempool_queue_single() -> Result<(), Report> {
    // Using the mainnet for now
    let network = Network::Mainnet;

    // Get transactions to use in the test
    let unmined_transactions = network.unmined_transactions_in_blocks(1..=10);
    let mut transactions = unmined_transactions.collect::<Vec<_>>();
    // Split unmined_transactions into:
    // [transactions..., new_tx]
    // A transaction not in the mempool that will be Queued
    let new_tx = transactions.pop().unwrap();

    // Use as cost limit the costs of all transactions that will be
    // inserted except the last.
    let cost_limit = transactions
        .iter()
        .take(transactions.len() - 1)
        .map(|tx| tx.cost())
        .sum();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    // Enable the mempool
    service.enable(&mut recent_syncs).await;

    // Insert [transactions...] into the mempool storage.
    // This will cause the at least one transaction to be rejected, since
    // the cost limit is the sum of all costs except of the last transaction.
    for tx in transactions.iter() {
        // Error must be ignored because a insert can trigger an eviction and
        // an error is returned if the transaction being inserted in chosen.
        let _ = service.storage().insert(tx.clone(), Vec::new(), None);
    }

    // Test `Request::Queue` for a new transaction
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![new_tx.transaction.id.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());

    // Test `Request::Queue` with all previously inserted transactions.
    // They should all be rejected; either because they are already in the mempool,
    // or because they are in the recently evicted list.
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(
            transactions
                .iter()
                .map(|tx| tx.transaction.id.into())
                .collect(),
        ))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), transactions.len());

    // Check if the responses are consistent
    let mut in_mempool_count = 0;
    let mut evicted_count = 0;
    for response in queued_responses {
        match response.unbox_mempool_error() {
            MempoolError::StorageEffectsChain(SameEffectsChainRejectionError::RandomlyEvicted) => {
                evicted_count += 1
            }
            MempoolError::InMempool => in_mempool_count += 1,
            error => panic!("transaction should not be rejected with reason {error:?}"),
        }
    }
    assert_eq!(in_mempool_count, transactions.len() - 1);
    assert_eq!(evicted_count, 1);

    Ok(())
}

#[tokio::test]
async fn mempool_service_disabled() -> Result<(), Report> {
    // Using the mainnet for now
    let network = Network::Mainnet;

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // get the genesis block transactions from the Zcash blockchain.
    let mut unmined_transactions = network.unmined_transactions_in_blocks(1..=10);
    let genesis_transaction = unmined_transactions
        .next()
        .expect("Missing genesis transaction");
    let more_transactions = unmined_transactions;

    // Test if mempool is disabled (it should start disabled)
    assert!(!service.is_enabled());

    // Enable the mempool
    service.enable(&mut recent_syncs).await;

    assert!(service.is_enabled());

    // Insert the genesis block coinbase transaction into the mempool storage.
    service
        .storage()
        .insert(genesis_transaction.clone(), Vec::new(), None)?;

    // Test if the mempool answers correctly (i.e. is enabled)
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::TransactionIds)
        .await
        .unwrap();
    let _genesis_transaction_ids = match response {
        Response::TransactionIds(ids) => ids,
        _ => unreachable!("will never happen in this test"),
    };

    // Queue a transaction for download
    // Use the ID of the last transaction in the list
    let txid = more_transactions.last().unwrap().transaction.id;
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![txid.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());
    assert_eq!(service.tx_downloads().in_flight(), 1);

    // Disable the mempool
    service.disable(&mut recent_syncs).await;

    // Test if mempool is disabled again
    assert!(!service.is_enabled());

    // Test if the mempool returns no transactions when disabled
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::TransactionIds)
        .await
        .unwrap();
    match response {
        Response::TransactionIds(ids) => {
            assert_eq!(
                ids.len(),
                0,
                "mempool should return no transactions when disabled"
            )
        }
        _ => unreachable!("will never happen in this test"),
    };

    // Test if the mempool returns to Queue requests correctly when disabled
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![txid.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };

    assert_eq!(queued_responses.len(), 1);
    assert_eq!(
        queued_responses
            .into_iter()
            .next()
            .unwrap()
            .unbox_mempool_error(),
        MempoolError::Disabled
    );

    // Test if mempool returns to QueueStats request correctly when disabled
    let response = service
        .ready()
        .await
        .unwrap()
        .call(Request::QueueStats)
        .await
        .unwrap();

    let (size, bytes, usage, fully_notified) = match response {
        Response::QueueStats {
            size,
            bytes,
            usage,
            fully_notified,
        } => (size, bytes, usage, fully_notified),
        _ => unreachable!("expected QueueStats response"),
    };

    assert_eq!(size, 0, "size should be zero when mempool is disabled");
    assert_eq!(bytes, 0, "bytes should be zero when mempool is disabled");
    assert_eq!(usage, 0, "usage should be zero when mempool is disabled");
    assert_eq!(
        fully_notified, None,
        "fully_notified should be None when mempool is disabled"
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn mempool_cancel_mined() -> Result<(), Report> {
    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let block2: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .unwrap();

    // Using the mainnet for now
    let network = Network::Mainnet;

    let (
        mut mempool,
        _peer_set,
        mut state_service,
        mut chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        mut mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // Enable the mempool
    mempool.enable(&mut recent_syncs).await;
    assert!(mempool.is_enabled());

    // Query the mempool to make it poll chain_tip_change
    mempool.dummy_call().await;

    // Push block 1 to the state
    state_service
        .ready()
        .await
        .unwrap()
        .call(zebra_state::Request::CommitCheckpointVerifiedBlock(
            block1.clone().into(),
        ))
        .await
        .unwrap();

    // Wait for the chain tip update
    if let Err(timeout_error) = timeout(
        CHAIN_TIP_UPDATE_WAIT_LIMIT,
        chain_tip_change.wait_for_tip_change(),
    )
    .await
    .map(|change_result| change_result.expect("unexpected chain tip update failure"))
    {
        info!(
            timeout = ?humantime_seconds(CHAIN_TIP_UPDATE_WAIT_LIMIT),
            ?timeout_error,
            "timeout waiting for chain tip change after committing block"
        );
    }

    // Query the mempool to make it poll chain_tip_change
    mempool.dummy_call().await;

    // Queue transaction from block 2 for download.
    // It can't be queued before because block 1 triggers a network upgrade,
    // which cancels all downloads.
    let txid = block2.transactions[0].unmined_id();
    let response = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![txid.into()]))
        .await
        .unwrap();
    let mut queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);

    let queued_response = queued_responses
        .pop()
        .expect("already checked that there is exactly 1 item in Vec")
        .expect("initial queue checks result should be Ok");

    assert_eq!(mempool.tx_downloads().in_flight(), 1);

    // Push block 2 to the state
    state_service
        .oneshot(zebra_state::Request::CommitCheckpointVerifiedBlock(
            block2.clone().into(),
        ))
        .await
        .unwrap();

    // Wait for the chain tip update
    if let Err(timeout_error) = timeout(
        CHAIN_TIP_UPDATE_WAIT_LIMIT,
        chain_tip_change.wait_for_tip_change(),
    )
    .await
    .map(|change_result| change_result.expect("unexpected chain tip update failure"))
    {
        info!(
            timeout = ?humantime_seconds(CHAIN_TIP_UPDATE_WAIT_LIMIT),
            ?timeout_error,
            "timeout waiting for chain tip change after committing block"
        );
    }

    // This is done twice because after the first query the cancellation
    // is picked up by select!, and after the second the mempool gets the
    // result and the download future is removed.
    for _ in 0..2 {
        // Query the mempool just to poll it and make it cancel the download.
        mempool.dummy_call().await;
        // Sleep to avoid starvation and make sure the cancellation is picked up.
        time::sleep(time::Duration::from_millis(100)).await;
    }

    // Check if download was cancelled.
    assert_eq!(mempool.tx_downloads().in_flight(), 0);

    assert!(
        queued_response
            .await
            .expect("channel should not be closed")
            .is_err(),
        "queued tx should fail to download and verify due to chain tip change"
    );

    let mempool_change = timeout(Duration::from_secs(3), mempool_transaction_receiver.recv())
        .await
        .expect("should not timeout")
        .expect("recv should return Ok");

    assert_eq!(
        mempool_change,
        MempoolChange::invalidated([txid].into_iter().collect())
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn mempool_cancel_downloads_after_network_upgrade() -> Result<(), Report> {
    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let block2: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .unwrap();

    // Using the mainnet for now
    let network = Network::Mainnet;

    let (
        mut mempool,
        mut peer_set,
        mut state_service,
        mut chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // Enable the mempool
    mempool.enable(&mut recent_syncs).await;
    assert!(mempool.is_enabled());

    // Queue transaction from block 2 for download
    let txid = block2.transactions[0].unmined_id();
    let response = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![txid.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());
    assert_eq!(mempool.tx_downloads().in_flight(), 1);

    // Query the mempool to make it poll chain_tip_change
    mempool.dummy_call().await;

    // Push block 1 to the state. This is considered a network upgrade,
    // and thus must cancel all pending transaction downloads.
    state_service
        .ready()
        .await
        .unwrap()
        .call(zebra_state::Request::CommitCheckpointVerifiedBlock(
            block1.clone().into(),
        ))
        .await
        .unwrap();

    // Wait for the chain tip update
    if let Err(timeout_error) = timeout(
        CHAIN_TIP_UPDATE_WAIT_LIMIT,
        chain_tip_change.wait_for_tip_change(),
    )
    .await
    .map(|change_result| change_result.expect("unexpected chain tip update failure"))
    {
        info!(
            timeout = ?humantime_seconds(CHAIN_TIP_UPDATE_WAIT_LIMIT),
            ?timeout_error,
            "timeout waiting for chain tip change after committing block"
        );
    }

    // Ignore all the previous network requests.
    while let Some(_request) = peer_set.try_next_request().await {}

    // Query the mempool to make it poll chain_tip_change
    mempool.dummy_call().await;

    // Check if download was cancelled and transaction was retried.
    let request = peer_set
        .try_next_request()
        .await
        .expect("unexpected missing mempool retry");

    assert_eq!(
        request.request(),
        &zebra_network::Request::TransactionsById(iter::once(txid).collect()),
    );
    assert_eq!(mempool.tx_downloads().in_flight(), 1);

    Ok(())
}

/// Check if a transaction that fails verification is rejected by the mempool.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_failed_verification_is_rejected() -> Result<(), Report> {
    // Using the mainnet for now
    let network = Network::Mainnet;

    let (
        mut mempool,
        _peer_set,
        _state_service,
        _chain_tip_change,
        mut tx_verifier,
        mut recent_syncs,
        mut mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // Get transactions to use in the test
    let mut unmined_transactions = network.unmined_transactions_in_blocks(1..=2);
    let rejected_tx = unmined_transactions.next().unwrap().clone();

    // Enable the mempool
    mempool.enable(&mut recent_syncs).await;

    // Queue first transaction for verification
    // (queue the transaction itself to avoid a download).
    let request = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![rejected_tx.transaction.clone().into()]));
    // Make the mock verifier return that the transaction is invalid.
    let verification = tx_verifier.expect_request_that(|_| true).map(|responder| {
        responder.respond(Err(TransactionError::BadBalance));
    });
    let (response, _) = futures::join!(request, verification);
    let queued_responses = match response.unwrap() {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    // Check that the request was enqueued successfully.
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());

    for _ in 0..2 {
        // Query the mempool just to poll it and make get the downloader/verifier result.
        mempool.dummy_call().await;
        // Sleep to avoid starvation and make sure the verification failure is picked up.
        time::sleep(time::Duration::from_millis(100)).await;
    }

    // Try to queue the same transaction by its ID and check if it's correctly
    // rejected.
    let response = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![rejected_tx.transaction.id.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(matches!(
        queued_responses
            .into_iter()
            .next()
            .unwrap()
            .unbox_mempool_error(),
        MempoolError::StorageExactTip(ExactTipRejectionError::FailedVerification(_))
    ));

    let mempool_change = timeout(Duration::from_secs(3), mempool_transaction_receiver.recv())
        .await
        .expect("should not timeout")
        .expect("recv should return Ok");

    assert_eq!(
        mempool_change,
        MempoolChange::invalidated([rejected_tx.transaction.id].into_iter().collect())
    );

    Ok(())
}

/// Check if a transaction that fails download is _not_ rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_failed_download_is_not_rejected() -> Result<(), Report> {
    // Using the mainnet for now
    let network = Network::Mainnet;

    let (
        mut mempool,
        mut peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        mut mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // Get transactions to use in the test
    let mut unmined_transactions = network.unmined_transactions_in_blocks(1..=2);
    let rejected_valid_tx = unmined_transactions.next().unwrap().clone();

    // Enable the mempool
    mempool.enable(&mut recent_syncs).await;

    // Queue second transaction for download and verification.
    let request = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![rejected_valid_tx
            .transaction
            .id
            .into()]));
    // Make the mock peer set return that the download failed.
    let verification = peer_set
        .expect_request_that(|r| matches!(r, zn::Request::TransactionsById(_)))
        .map(|responder| {
            responder.respond(zn::Response::Transactions(vec![]));
        });
    let (response, _) = futures::join!(request, verification);
    let queued_responses = match response.unwrap() {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    // Check that the request was enqueued successfully.
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());

    for _ in 0..2 {
        // Query the mempool just to poll it and make get the downloader/verifier result.
        mempool.dummy_call().await;
        // Sleep to avoid starvation and make sure the download failure is picked up.
        time::sleep(time::Duration::from_millis(100)).await;
    }

    // Try to queue the same transaction by its ID and check if it's not being
    // rejected.
    let response = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![rejected_valid_tx
            .transaction
            .id
            .into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());

    let mempool_change = timeout(Duration::from_secs(3), mempool_transaction_receiver.recv())
        .await
        .expect("should not timeout")
        .expect("recv should return Ok");

    assert_eq!(
        mempool_change,
        MempoolChange::invalidated([rejected_valid_tx.transaction.id].into_iter().collect())
    );

    Ok(())
}

/// Check that transactions are re-verified if the tip changes
/// during verification.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reverifies_after_tip_change() -> Result<(), Report> {
    let network = Network::Mainnet;

    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let block2: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let block3: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_3_BYTES
        .zcash_deserialize_into()
        .unwrap();

    let (
        mut mempool,
        mut peer_set,
        mut state_service,
        mut chain_tip_change,
        mut tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;

    // Enable the mempool
    mempool.enable(&mut recent_syncs).await;
    assert!(mempool.is_enabled());

    // Queue transaction from block 3 for download
    let tx = block3.transactions[0].clone();
    let txid = block3.transactions[0].unmined_id();
    let response = mempool
        .ready()
        .await
        .unwrap()
        .call(Request::Queue(vec![txid.into()]))
        .await
        .unwrap();
    let queued_responses = match response {
        Response::Queued(queue_responses) => queue_responses,
        _ => unreachable!("will never happen in this test"),
    };
    assert_eq!(queued_responses.len(), 1);
    assert!(queued_responses[0].is_ok());
    assert_eq!(mempool.tx_downloads().in_flight(), 1);

    // Verify the transaction

    peer_set
        .expect_request_that(|req| matches!(req, zn::Request::TransactionsById(_)))
        .map(|responder| {
            responder.respond(zn::Response::Transactions(vec![
                zn::InventoryResponse::Available((tx.clone().into(), None)),
            ]));
        })
        .await;

    tx_verifier
        .expect_request_that(|_| true)
        .map(|responder| {
            let transaction = responder
                .request()
                .clone()
                .mempool_transaction()
                .expect("unexpected non-mempool request");

            // Set a dummy fee and sigops.
            responder.respond(transaction::Response::from(
                VerifiedUnminedTx::new(
                    transaction,
                    Amount::try_from(1_000_000).expect("invalid value"),
                    0,
                    std::sync::Arc::new(vec![]),
                )
                .expect("verification should pass"),
            ));
        })
        .await;

    // Push block 1 to the state. This is considered a network upgrade,
    // and must cancel all pending transaction downloads with a `TipAction::Reset`.
    state_service
        .ready()
        .await
        .unwrap()
        .call(zebra_state::Request::CommitCheckpointVerifiedBlock(
            block1.clone().into(),
        ))
        .await
        .unwrap();

    // Wait for the chain tip update without a timeout
    // (skipping the chain tip change here will fail the test)
    chain_tip_change
        .wait_for_tip_change()
        .await
        .expect("unexpected chain tip update failure");

    // Query the mempool to make it poll chain_tip_change and try reverifying its state for the `TipAction::Reset`
    mempool.dummy_call().await;

    // Check that there is still an in-flight tx_download and that
    // no transactions were inserted in the mempool.
    assert_eq!(mempool.tx_downloads().in_flight(), 1);
    assert_eq!(mempool.storage().transaction_count(), 0);

    // Verify the transaction again

    peer_set
        .expect_request_that(|req| matches!(req, zn::Request::TransactionsById(_)))
        .map(|responder| {
            responder.respond(zn::Response::Transactions(vec![
                zn::InventoryResponse::Available((tx.into(), None)),
            ]));
        })
        .await;

    // Verify the transaction now that the mempool has already checked chain_tip_change
    tx_verifier
        .expect_request_that(|_| true)
        .map(|responder| {
            let transaction = responder
                .request()
                .clone()
                .mempool_transaction()
                .expect("unexpected non-mempool request");

            // Set a dummy fee and sigops.
            responder.respond(transaction::Response::from(
                VerifiedUnminedTx::new(
                    transaction,
                    Amount::try_from(1_000_000).expect("invalid value"),
                    0,
                    std::sync::Arc::new(vec![]),
                )
                .expect("verification should pass"),
            ));
        })
        .await;

    // Push block 2 to the state. This will increase the tip height past the expected
    // tip height that the tx was verified at.
    state_service
        .ready()
        .await
        .unwrap()
        .call(zebra_state::Request::CommitCheckpointVerifiedBlock(
            block2.clone().into(),
        ))
        .await
        .unwrap();

    // Wait for the chain tip update without a timeout
    // (skipping the chain tip change here will fail the test)
    chain_tip_change
        .wait_for_tip_change()
        .await
        .expect("unexpected chain tip update failure");

    // Query the mempool to make it poll tx_downloads.pending and try reverifying transactions
    // because the tip height has changed.
    mempool.dummy_call().await;

    // Check that there is still an in-flight tx_download and that
    // no transactions were inserted in the mempool.
    assert_eq!(mempool.tx_downloads().in_flight(), 1);
    assert_eq!(mempool.storage().transaction_count(), 0);

    Ok(())
}

/// Checks that the mempool service responds to AwaitOutput requests after verifying transactions
/// that create those outputs, or immediately if the outputs had been created by transaction that
/// are already in the mempool.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_responds_to_await_output() -> Result<(), Report> {
    let network = Network::Mainnet;

    let (
        mut mempool,
        _peer_set,
        _state_service,
        _chain_tip_change,
        mut tx_verifier,
        mut recent_syncs,
        mut mempool_transaction_receiver,
    ) = setup(&network, u64::MAX, true).await;
    mempool.enable(&mut recent_syncs).await;

    let verified_unmined_tx = network
        .unmined_transactions_in_blocks(1..=10)
        .find(|tx| !tx.transaction.transaction.outputs().is_empty())
        .expect("should have at least 1 tx with transparent outputs");

    let unmined_tx = verified_unmined_tx.transaction.clone();
    let unmined_tx_id = unmined_tx.id;
    let output_index = 0;
    let outpoint = OutPoint::from_usize(unmined_tx.id.mined_id(), output_index);
    let expected_output = unmined_tx
        .transaction
        .outputs()
        .get(output_index)
        .expect("already checked that tx has outputs")
        .clone();

    // Call mempool with an AwaitOutput request

    let request = Request::AwaitOutput(outpoint);
    let await_output_response_fut = mempool.ready().await.unwrap().call(request);

    // Queue the transaction with the pending output to be added to the mempool

    let request = Request::Queue(vec![Gossip::Tx(unmined_tx)]);
    let queue_response_fut = mempool.ready().await.unwrap().call(request);
    let mock_verify_tx_fut = tx_verifier.expect_request_that(|_| true).map(|responder| {
        responder.respond(transaction::Response::Mempool {
            transaction: verified_unmined_tx,
            spent_mempool_outpoints: Vec::new(),
        });
    });

    let (response, _) = futures::join!(queue_response_fut, mock_verify_tx_fut);
    let Response::Queued(mut results) = response.expect("response should be Ok") else {
        panic!("wrong response from mempool to Queued request");
    };

    let result_rx = results.remove(0).expect("should pass initial checks");
    assert!(results.is_empty(), "should have 1 result for 1 queued tx");

    // Wait for post-verification steps in mempool's Downloads
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Note: Buffered services shouldn't be polled without being called.
    //       See `mempool::Request::CheckForVerifiedTransactions` for more details.
    mempool
        .ready()
        .await
        .expect("polling mempool should succeed");

    tokio::time::timeout(Duration::from_secs(10), result_rx)
        .await
        .expect("should not time out")
        .expect("mempool tx verification result channel should not be closed")
        .expect("mocked verification should be successful");

    assert_eq!(
        mempool.storage().transaction_count(),
        1,
        "should have 1 transaction in mempool's verified set"
    );

    assert_eq!(
        mempool.storage().created_output(&outpoint),
        Some(expected_output.clone()),
        "created output should match expected output"
    );

    // Check that the AwaitOutput request has been responded to after the relevant tx was added to the verified set

    let response_fut = tokio::time::timeout(Duration::from_secs(30), await_output_response_fut);
    let response = response_fut
        .await
        .expect("should not time out")
        .expect("should not return RecvError");

    let Response::UnspentOutput(response) = response else {
        panic!("wrong response from mempool to AwaitOutput request");
    };

    assert_eq!(
        response, expected_output,
        "AwaitOutput response should match expected output"
    );

    // Check that the mempool responds to AwaitOutput requests correctly when the outpoint is already in its `created_outputs` collection too.

    let request = Request::AwaitOutput(outpoint);
    let await_output_response_fut = mempool.ready().await.unwrap().call(request);
    let response_fut = tokio::time::timeout(Duration::from_secs(30), await_output_response_fut);
    let response = response_fut
        .await
        .expect("should not time out")
        .expect("should not return RecvError");

    let Response::UnspentOutput(response) = response else {
        panic!("wrong response from mempool to AwaitOutput request");
    };

    assert_eq!(
        response, expected_output,
        "AwaitOutput response should match expected output"
    );

    let mempool_change = timeout(Duration::from_secs(3), mempool_transaction_receiver.recv())
        .await
        .expect("should not timeout")
        .expect("recv should return Ok");

    assert_eq!(
        mempool_change,
        MempoolChange::added([unmined_tx_id].into_iter().collect())
    );

    Ok(())
}

/// Check that verified transactions are rejected if non-standard
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_non_standard() -> Result<(), Report> {
    let network = Network::Mainnet;

    // pick a random transaction from the dummy Zcash blockchain
    let unmined_transactions = network.unmined_transactions_in_blocks(1..=10);
    let transactions = unmined_transactions.collect::<Vec<_>>();
    let mut rng = thread_rng();
    let mut last_transaction = transactions
        .choose(&mut rng)
        .expect("Missing transaction")
        .clone();

    last_transaction.height = Some(Height(100_000));

    // Modify the transaction to make it non-standard.
    // This is done by replacing its outputs with a dust output.
    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(10), // this is below the dust threshold
        lock_script: p2pkh_script([0u8; 20]),
    }];
    last_transaction.transaction.transaction = tx;

    // Set cost limit to the cost of the transaction we will try to insert.
    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    // Enable the mempool
    service.enable(&mut recent_syncs).await;

    // Insert the modified transaction into the mempool storage.
    // Expect insertion to fail for non-standard transaction.
    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(storage::NonStandardTransactionError::IsDust)
    );

    Ok(())
}

/// Check that standard OP_RETURN outputs are accepted when datacarrier is enabled.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_accept_standard_op_return() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(0),
        lock_script: op_return_script(&[0x01]),
    }];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)?;

    Ok(())
}

/// Check that oversized OP_RETURN scripts are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_op_return_too_large() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(0),
        lock_script: op_return_script(&[0x03]),
    }];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();
    // Shrink the OP_RETURN size limit to trigger the oversized rejection path.
    let mempool_config = mempool::Config {
        tx_cost_limit: cost_limit,
        max_datacarrier_bytes: Some(2),
        ..Default::default()
    };

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup_with_mempool_config(&network, mempool_config, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::DataCarrierTooLarge
        )
    );

    Ok(())
}

/// Check that multiple OP_RETURN outputs are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_multi_op_return() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![
        transparent::Output {
            value: Amount::new(0),
            lock_script: op_return_script(&[0x04]),
        },
        transparent::Output {
            value: Amount::new(0),
            lock_script: op_return_script(&[0x05]),
        },
    ];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(storage::NonStandardTransactionError::MultiOpReturn)
    );

    Ok(())
}

/// Check that non-standard scriptPubKeys are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_non_standard_scriptpubkey() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(1000),
        lock_script: transparent::Script::new(&[0x00]),
    }];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::ScriptPubKeyNonStandard
        )
    );

    Ok(())
}

/// Check that bare multisig outputs are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_bare_multisig() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(1000),
        lock_script: multisig_script(1, 1),
    }];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(storage::NonStandardTransactionError::BareMultiSig)
    );

    Ok(())
}

/// Check that oversized bare multisig outputs are rejected as non-standard.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_large_multisig() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    *tx_mut.outputs_mut() = vec![transparent::Output {
        value: Amount::new(1000),
        lock_script: multisig_script(1, 4),
    }];
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::ScriptPubKeyNonStandard
        )
    );

    Ok(())
}

/// Check that oversized scriptSig inputs are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_large_scriptsig() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = pick_transaction_with_prevout(&network);

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    set_first_prevout_unlock_script(tx_mut, transparent::Script::new(&vec![0u8; 1651]));
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::ScriptSigTooLarge
        )
    );

    Ok(())
}

/// Check that non-push-only scriptSig inputs are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_non_push_only_scriptsig() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = pick_transaction_with_prevout(&network);

    last_transaction.height = Some(Height(100_000));

    let mut tx = last_transaction.transaction.transaction.clone();
    let tx_mut = Arc::make_mut(&mut tx);
    set_first_prevout_unlock_script(tx_mut, transparent::Script::new(&[0xac]));
    last_transaction.transaction.transaction = tx;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard tx");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::ScriptSigNotPushOnly
        )
    );

    Ok(())
}

/// Check that transactions with too many sigops are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_too_many_sigops() -> Result<(), Report> {
    let network = Network::Mainnet;

    let mut last_transaction = network
        .unmined_transactions_in_blocks(1..=10)
        .next()
        .expect("missing transaction");

    last_transaction.height = Some(Height(100_000));

    // Set the legacy sigop count above the MAX_STANDARD_TX_SIGOPS limit of 4000.
    last_transaction.legacy_sigop_count = 4001;

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for too many sigops");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(storage::NonStandardTransactionError::TooManySigops)
    );

    Ok(())
}

/// Check that transactions with non-standard inputs (non-standard spent output script)
/// are rejected.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_reject_non_standard_inputs() -> Result<(), Report> {
    let network = Network::Mainnet;

    // Use a transaction that has at least one transparent PrevOut input.
    let mut last_transaction = pick_transaction_with_prevout(&network);

    last_transaction.height = Some(Height(100_000));

    // Provide a non-standard spent output script so are_inputs_standard() returns false.
    // Use a script that doesn't match any known template (OP_1 OP_2 OP_ADD).
    let non_standard_script = transparent::Script::new(&[0x51, 0x52, 0x93]);
    let non_standard_output = transparent::Output {
        value: 0u64.try_into().unwrap(),
        lock_script: non_standard_script,
    };
    // Provide one spent output per transparent input (including coinbase inputs in the count,
    // since are_inputs_standard expects spent_outputs.len() == tx.inputs().len()).
    let input_count = last_transaction.transaction.transaction.inputs().len();
    last_transaction.spent_outputs = std::sync::Arc::new(vec![non_standard_output; input_count]);

    let cost_limit = last_transaction.cost();

    let (
        mut service,
        _peer_set,
        _state_service,
        _chain_tip_change,
        _tx_verifier,
        mut recent_syncs,
        _mempool_transaction_receiver,
    ) = setup(&network, cost_limit, true).await;

    service.enable(&mut recent_syncs).await;

    let insert_err = service
        .storage()
        .insert(last_transaction.clone(), Vec::new(), None)
        .expect_err("expected insert to fail for non-standard inputs");

    assert_eq!(
        insert_err,
        MempoolError::NonStandardTransaction(
            storage::NonStandardTransactionError::NonStandardInputs
        )
    );

    Ok(())
}

fn op_return_script(data: &[u8]) -> transparent::Script {
    // Build a minimal OP_RETURN script using small pushdata (<= 75 bytes).
    assert!(data.len() <= 75, "test helper only supports small pushdata");

    let mut bytes = Vec::with_capacity(2 + data.len());
    bytes.push(0x6a);
    bytes.push(data.len() as u8);
    bytes.extend_from_slice(data);
    transparent::Script::new(&bytes)
}

fn multisig_script(required: u8, key_count: usize) -> transparent::Script {
    // Construct a bare multisig output: OP_M <pubkeys> OP_N OP_CHECKMULTISIG.
    assert!(required >= 1 && required <= key_count as u8);
    assert!(key_count <= 16);

    let mut bytes = Vec::new();
    bytes.push(op_n(required));

    for i in 0..key_count {
        bytes.push(33u8);
        let mut pubkey = vec![0u8; 33];
        pubkey[0] = 0x02;
        pubkey[1] = i as u8;
        bytes.extend_from_slice(&pubkey);
    }

    bytes.push(op_n(key_count as u8));
    bytes.push(0xae);

    transparent::Script::new(&bytes)
}

fn p2pkh_script(pubkey_hash: [u8; 20]) -> transparent::Script {
    let mut bytes = Vec::with_capacity(25);
    bytes.push(0x76);
    bytes.push(0xa9);
    bytes.push(20);
    bytes.extend_from_slice(&pubkey_hash);
    bytes.push(0x88);
    bytes.push(0xac);
    transparent::Script::new(&bytes)
}

fn op_n(n: u8) -> u8 {
    if n == 0 {
        0x00
    } else {
        0x50 + n
    }
}

fn set_first_prevout_unlock_script(tx: &mut Transaction, script: transparent::Script) {
    for input in tx.inputs_mut() {
        if let transparent::Input::PrevOut { unlock_script, .. } = input {
            *unlock_script = script;
            return;
        }
    }

    panic!("missing prevout input");
}

fn pick_transaction_with_prevout(network: &Network) -> VerifiedUnminedTx {
    network
        .unmined_transactions_in_blocks(..)
        .find(|transaction| {
            transaction
                .transaction
                .transaction
                .inputs()
                .iter()
                .any(|input| matches!(input, transparent::Input::PrevOut { .. }))
        })
        .expect("missing non-coinbase transaction")
}

/// Create a new [`Mempool`] instance using mocked services.
async fn setup(
    network: &Network,
    tx_cost_limit: u64,
    should_commit_genesis_block: bool,
) -> (
    Mempool,
    MockPeerSet,
    StateService,
    ChainTipChange,
    MockTxVerifier,
    RecentSyncLengths,
    tokio::sync::broadcast::Receiver<MempoolChange>,
) {
    let mempool_config = mempool::Config {
        tx_cost_limit,
        ..Default::default()
    };

    setup_with_mempool_config(network, mempool_config, should_commit_genesis_block).await
}

async fn setup_with_mempool_config(
    network: &Network,
    mempool_config: mempool::Config,
    should_commit_genesis_block: bool,
) -> (
    Mempool,
    MockPeerSet,
    StateService,
    ChainTipChange,
    MockTxVerifier,
    RecentSyncLengths,
    tokio::sync::broadcast::Receiver<MempoolChange>,
) {
    let peer_set = MockService::build().for_unit_tests();

    // UTXO verification doesn't matter here.
    let state_config = StateConfig::ephemeral();
    let (state, _read_only_state_service, latest_chain_tip, mut chain_tip_change) =
        zebra_state::init(state_config, network, Height::MAX, 0).await;
    let mut state_service = ServiceBuilder::new().buffer(10).service(state);

    let tx_verifier = MockService::build().for_unit_tests();

    let (sync_status, recent_syncs) = SyncStatus::new();
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let (mempool, mempool_transaction_subscriber) = Mempool::new(
        &mempool_config,
        Buffer::new(BoxService::new(peer_set.clone()), 1),
        state_service.clone(),
        Buffer::new(BoxService::new(tx_verifier.clone()), 1),
        sync_status,
        latest_chain_tip,
        chain_tip_change.clone(),
        misbehavior_tx,
    );

    let mut mempool_transaction_receiver = mempool_transaction_subscriber.subscribe();
    tokio::spawn(async move { while mempool_transaction_receiver.recv().await.is_ok() {} });

    if should_commit_genesis_block {
        let genesis_block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
            .zcash_deserialize_into()
            .unwrap();

        // Push the genesis block to the state
        state_service
            .ready()
            .await
            .unwrap()
            .call(zebra_state::Request::CommitCheckpointVerifiedBlock(
                genesis_block.clone().into(),
            ))
            .await
            .unwrap();

        // Wait for the chain tip update without a timeout
        chain_tip_change
            .wait_for_tip_change()
            .await
            .expect("unexpected chain tip update failure");
    }

    (
        mempool,
        peer_set,
        state_service,
        chain_tip_change,
        tx_verifier,
        recent_syncs,
        mempool_transaction_subscriber.subscribe(),
    )
}