zebra-script 7.0.1

Zebra script verification wrapping zcashd's zcash_script library
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
#![allow(clippy::unwrap_in_result)]

use hex::FromHex;
use std::sync::Arc;
use zebra_chain::{
    block::{self, Height},
    parameters::{Network, NetworkUpgrade},
    serialization::{ZcashDeserialize, ZcashDeserializeInto},
    transaction::{self, HashType, LockTime, SigHasher, Transaction},
    transparent::{self, Output},
};
use zebra_test::prelude::*;

use crate::{p2sh_sigop_count, Sigops};

lazy_static::lazy_static! {
    pub static ref SCRIPT_PUBKEY: Vec<u8> = <Vec<u8>>::from_hex("76a914f47cac1e6fec195c055994e8064ffccce0044dd788ac")
        .unwrap();
    pub static ref SCRIPT_TX: Vec<u8> = <Vec<u8>>::from_hex("0400008085202f8901fcaf44919d4a17f6181a02a7ebe0420be6f7dad1ef86755b81d5a9567456653c010000006a473044022035224ed7276e61affd53315eca059c92876bc2df61d84277cafd7af61d4dbf4002203ed72ea497a9f6b38eb29df08e830d99e32377edb8a574b8a289024f0241d7c40121031f54b095eae066d96b2557c1f99e40e967978a5fd117465dbec0986ca74201a6feffffff020050d6dc0100000017a9141b8a9bda4b62cd0d0582b55455d0778c86f8628f870d03c812030000001976a914e4ff5512ffafe9287992a1cd177ca6e408e0300388ac62070d0095070d000000000000000000000000")
        .expect("Block bytes are in valid hex representation");
}

fn verify_valid_script(nu: NetworkUpgrade, tx: &[u8], amount: u64, pubkey: &[u8]) -> Result<()> {
    let transaction = tx.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(pubkey),
    };
    let input_index = 0;

    let previous_output = Arc::new(vec![output]);
    let verifier = super::CachedFfiTransaction::new(transaction, previous_output, nu)
        .expect("network upgrade should be valid for tx");
    verifier.is_valid(input_index)?;

    Ok(())
}

#[test]
fn verify_valid_script_v4() -> Result<()> {
    let _init_guard = zebra_test::init();

    verify_valid_script(
        NetworkUpgrade::Blossom,
        &SCRIPT_TX,
        212 * u64::pow(10, 8),
        &SCRIPT_PUBKEY,
    )
}

#[test]
fn count_legacy_sigops() -> Result<()> {
    let _init_guard = zebra_test::init();

    let tx = SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;

    assert_eq!(tx.sigops()?, 1);

    Ok(())
}

#[test]
fn fail_invalid_script() -> Result<()> {
    let _init_guard = zebra_test::init();

    let transaction =
        SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;
    let coin = u64::pow(10, 8);
    let amount = 211 * coin;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY.clone()[..]),
    };
    let input_index = 0;
    let verifier = super::CachedFfiTransaction::new(
        transaction,
        Arc::new(vec![output]),
        NetworkUpgrade::Blossom,
    )
    .expect("network upgrade should be valid for tx");
    verifier
        .is_valid(input_index)
        .expect_err("verification should fail");

    Ok(())
}

#[test]
fn reuse_script_verifier_pass_pass() -> Result<()> {
    let _init_guard = zebra_test::init();

    let coin = u64::pow(10, 8);
    let transaction =
        SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;
    let amount = 212 * coin;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY.clone()),
    };

    let verifier = super::CachedFfiTransaction::new(
        transaction,
        Arc::new(vec![output]),
        NetworkUpgrade::Blossom,
    )
    .expect("network upgrade should be valid for tx");

    let input_index = 0;

    verifier.is_valid(input_index)?;
    verifier.is_valid(input_index)?;

    Ok(())
}

#[test]
fn reuse_script_verifier_pass_fail() -> Result<()> {
    let _init_guard = zebra_test::init();

    let coin = u64::pow(10, 8);
    let amount = 212 * coin;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY.clone()),
    };
    let transaction =
        SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;

    let verifier = super::CachedFfiTransaction::new(
        transaction,
        Arc::new(vec![output]),
        NetworkUpgrade::Blossom,
    )
    .expect("network upgrade should be valid for tx");

    let input_index = 0;

    verifier.is_valid(input_index)?;
    verifier
        .is_valid(input_index + 1)
        .expect_err("verification should fail");

    Ok(())
}

#[test]
fn reuse_script_verifier_fail_pass() -> Result<()> {
    let _init_guard = zebra_test::init();

    let coin = u64::pow(10, 8);
    let amount = 212 * coin;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY.clone()),
    };
    let transaction =
        SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;

    let verifier = super::CachedFfiTransaction::new(
        transaction,
        Arc::new(vec![output]),
        NetworkUpgrade::Blossom,
    )
    .expect("network upgrade should be valid for tx");

    let input_index = 0;

    verifier
        .is_valid(input_index + 1)
        .expect_err("verification should fail");
    verifier.is_valid(input_index)?;

    Ok(())
}

#[test]
fn reuse_script_verifier_fail_fail() -> Result<()> {
    let _init_guard = zebra_test::init();

    let coin = u64::pow(10, 8);
    let amount = 212 * coin;
    let output = transparent::Output {
        value: amount.try_into()?,
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY.clone()),
    };
    let transaction =
        SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()?;

    let verifier = super::CachedFfiTransaction::new(
        transaction,
        Arc::new(vec![output]),
        NetworkUpgrade::Blossom,
    )
    .expect("network upgrade should be valid for tx");

    let input_index = 0;

    verifier
        .is_valid(input_index + 1)
        .expect_err("verification should fail");

    verifier
        .is_valid(input_index + 1)
        .expect_err("verification should fail");

    Ok(())
}

#[test]
fn p2sh() -> Result<()> {
    let _init_guard = zebra_test::init();

    // real tx with txid 51ded0b026f1ff56639447760bcd673b9f4e44a8afbf3af1dbaa6ca1fd241bea
    let serialized_tx = "0400008085202f8901c21354bf2305e474ad695382e68efc06e2f8b83c512496f615d153c2e00e688b00000000fdfd0000483045022100d2ab3e6258fe244fa442cfb38f6cef9ac9a18c54e70b2f508e83fa87e20d040502200eead947521de943831d07a350e45af8e36c2166984a8636f0a8811ff03ed09401473044022013e15d865010c257eef133064ef69a780b4bc7ebe6eda367504e806614f940c3022062fdbc8c2d049f91db2042d6c9771de6f1ef0b3b1fea76c1ab5542e44ed29ed8014c69522103b2cc71d23eb30020a4893982a1e2d352da0d20ee657fa02901c432758909ed8f21029d1e9a9354c0d2aee9ffd0f0cea6c39bbf98c4066cf143115ba2279d0ba7dabe2103e32096b63fd57f3308149d238dcbb24d8d28aad95c0e4e74e3e5e6a11b61bcc453aeffffffff0250954903000000001976a914a5a4e1797dac40e8ce66045d1a44c4a63d12142988acccf41c590000000017a9141c973c68b2acc6d6688eff9c7a9dd122ac1346ab8786c72400000000000000000000000000000000";
    let serialized_output = "4065675c0000000017a914c117756dcbe144a12a7c33a77cfa81aa5aeeb38187";
    let tx =
        Transaction::zcash_deserialize(&hex::decode(serialized_tx).unwrap().to_vec()[..]).unwrap();

    let previous_output =
        Output::zcash_deserialize(&hex::decode(serialized_output).unwrap().to_vec()[..]).unwrap();

    let verifier = super::CachedFfiTransaction::new(
        Arc::new(tx),
        Arc::new(vec![previous_output]),
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for tx");

    verifier.is_valid(0)?;

    Ok(())
}

/// Construct a V5 P2PKH transaction with a given sighash type byte in the signature,
/// then verify it through the full script verification path (CachedFfiTransaction::is_valid).
///
/// This reproduces the regtest experiments from docs/analysis/sighash_consensus_divergence_report.md:
/// - canonical_hash_type: the HashType used to compute the sighash for signing (must be valid)
/// - sig_hash_type_byte: the raw byte appended to the DER signature in the unlock script
///
/// When sig_hash_type_byte differs from the canonical byte but canonicalizes to the same
/// HashType via from_bits(byte, false), Zebra accepts the transaction. zcashd rejects it
/// for v5 transactions because SighashType::parse rejects undefined raw values.
fn build_and_verify_v5_p2pkh(
    canonical_hash_type: HashType,
    sig_hash_type_byte: u8,
) -> std::result::Result<(), crate::Error> {
    use ripemd::{Digest as _, Ripemd160};
    use secp256k1::{Message, Secp256k1, SecretKey};
    use sha2::Sha256;

    let secp = Secp256k1::new();

    // Deterministic keypair (32 bytes, nonzero)
    let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("valid secret key");
    let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
    let pubkey_bytes = public_key.serialize(); // 33 bytes, compressed

    // Derive P2PKH lock script: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
    let sha_hash = Sha256::digest(pubkey_bytes);
    let pub_key_hash: [u8; 20] = Ripemd160::digest(sha_hash).into();
    let mut lock_script_bytes = vec![
        0x76, // OP_DUP
        0xa9, // OP_HASH160
        0x14, // Push 20 bytes
    ];
    lock_script_bytes.extend_from_slice(&pub_key_hash);
    lock_script_bytes.push(0x88); // OP_EQUALVERIFY
    lock_script_bytes.push(0xac); // OP_CHECKSIG
    let lock_script = transparent::Script::new(&lock_script_bytes);

    let previous_output = transparent::Output {
        value: 1_0000_0000u64.try_into().expect("valid amount"),
        lock_script: lock_script.clone(),
    };

    // Build a V5 transaction with a placeholder unlock script.
    // For v5/ZIP-244, the sighash does NOT depend on the unlock script contents,
    // so we can compute the sighash with a placeholder, sign, then rebuild.
    let placeholder_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&[]),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]), // OP_FALSE (burn)
        }],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // Compute the sighash for the canonical hash type
    let all_previous_outputs = Arc::new(vec![previous_output.clone()]);
    let sighasher = SigHasher::new(&placeholder_tx, NetworkUpgrade::Nu5, all_previous_outputs)
        .expect("sighasher creation should succeed");
    let sighash = sighasher.sighash(canonical_hash_type, Some((0, lock_script_bytes.clone())));

    // Sign the sighash with the private key
    let msg = Message::from_digest(*sighash.as_ref());
    let signature = secp.sign_ecdsa(&msg, &secret_key);
    let der_sig = signature.serialize_der();

    // Build the unlock script: <sig_len> <DER_sig || hash_type_byte> <pubkey_len> <pubkey>
    let mut unlock_script_bytes = Vec::new();
    // Push signature + hash_type byte
    let sig_with_hashtype_len = der_sig.len() + 1;
    unlock_script_bytes.push(sig_with_hashtype_len as u8);
    unlock_script_bytes.extend_from_slice(&der_sig);
    unlock_script_bytes.push(sig_hash_type_byte);
    // Push compressed public key (33 bytes)
    unlock_script_bytes.push(pubkey_bytes.len() as u8);
    unlock_script_bytes.extend_from_slice(&pubkey_bytes);

    // Rebuild the V5 transaction with the real unlock script
    let final_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&unlock_script_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let verifier = super::CachedFfiTransaction::new(
        Arc::new(final_tx),
        Arc::new(vec![previous_output]),
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for v5 tx");

    verifier.is_valid(0)
}

/// Baseline: a standard V5 P2PKH spend with SIGHASH_ALL (0x01) passes verification.
/// Both Zebra and zcashd accept this.
#[test]
fn sighash_divergence_v5_p2pkh_canonical_sighash_all() {
    let _init_guard = zebra_test::init();

    build_and_verify_v5_p2pkh(HashType::ALL, 0x01)
        .expect("canonical SIGHASH_ALL (0x01) should be accepted");
}

/// Baseline: a standard V5 P2PKH spend with SIGHASH_ALL|ANYONECANPAY (0x81) passes.
/// Both Zebra and zcashd accept this.
#[test]
fn sighash_divergence_v5_p2pkh_canonical_sighash_all_anyonecanpay() {
    let _init_guard = zebra_test::init();

    build_and_verify_v5_p2pkh(HashType::ALL | HashType::ANYONECANPAY, 0x81)
        .expect("canonical SIGHASH_ALL|ANYONECANPAY (0x81) should be accepted");
}

/// V5 P2PKH spend with malformed hash_type 0x84 is now rejected.
///
/// 0x84 has undefined bits set: 0x84 ∉ {0x01, 0x02, 0x03, 0x81, 0x82, 0x83}.
/// The callback now checks raw_bits() and returns None for v5+ transactions
/// with undefined hash_type values, matching zcashd's SighashType::parse behavior.
///
/// Before the fix, Zebra accepted this (canonicalizing 0x84 → 0x81).
#[test]
fn sighash_divergence_v5_p2pkh_malformed_0x84_rejected() {
    let _init_guard = zebra_test::init();

    let result = build_and_verify_v5_p2pkh(HashType::ALL | HashType::ANYONECANPAY, 0x84);

    assert!(
        result.is_err(),
        "Malformed hash_type 0x84 should be rejected for v5 transactions, \
         matching zcashd behavior"
    );
}

/// V5 P2PKH spend with malformed hash_type 0x50 is now rejected.
///
/// 0x50 has undefined bits set: 0x50 ∉ {0x01, 0x02, 0x03, 0x81, 0x82, 0x83}.
/// The callback now checks raw_bits() and returns None for v5+ transactions
/// with undefined hash_type values, matching zcashd's SighashType::parse behavior.
///
/// Before the fix, Zebra accepted this (canonicalizing 0x50 → 0x01).
#[test]
fn sighash_divergence_v5_p2pkh_malformed_0x50_rejected() {
    let _init_guard = zebra_test::init();

    let result = build_and_verify_v5_p2pkh(HashType::ALL, 0x50);

    assert!(
        result.is_err(),
        "Malformed hash_type 0x50 should be rejected for v5 transactions, \
         matching zcashd behavior"
    );
}

/// Negative test: V5 P2PKH spend with malformed hash_type 0x84 but signed with
/// the WRONG canonical type (ALL instead of ALL|ANYONECANPAY).
///
/// This produces a sighash mismatch: the signature was created over ALL's sighash,
/// but Zebra canonicalizes 0x84 to ALL|ANYONECANPAY and computes that sighash.
/// The signature doesn't verify → both Zebra and zcashd reject.
///
/// This confirms the issue is specifically about canonicalization mapping to the
/// correct sighash, not a generic signature bypass.
#[test]
fn sighash_divergence_v5_p2pkh_malformed_0x84_wrong_canonical_type_rejected() {
    let _init_guard = zebra_test::init();

    // Sign with ALL (0x01), but put 0x84 which canonicalizes to ALL|ANYONECANPAY (0x81).
    // The sighash mismatch causes verification failure.
    let result = build_and_verify_v5_p2pkh(HashType::ALL, 0x84);

    assert!(
        result.is_err(),
        "Malformed hash_type 0x84 signed with wrong canonical type should be rejected \
         by both Zebra and zcashd (sighash mismatch)"
    );
}

/// Build a V5 transaction with two transparent inputs and one transparent output,
/// sign the input at `signed_input_index` with SIGHASH_SINGLE (or
/// SIGHASH_SINGLE|ANYONECANPAY when `anyone_can_pay` is set) using whatever
/// digest Zebra computes for that input, and run that input through the script
/// verifier.
///
/// This reproduces the ZIP-244 §S.2a "no corresponding output" scenario from
/// GHSA-cwfq-rfcr-8hmp: the transaction has fewer transparent outputs than
/// inputs, so for `signed_input_index >= 1` there is no `vout[k]` for the input
/// being signed. `zcashd` rejects this at script verification; before the fix,
/// Zebra accepted it because librustzcash returned a digest computed from an
/// empty output list instead of failing.
fn build_and_verify_v5_p2pkh_single_with_missing_output(
    signed_input_index: usize,
    anyone_can_pay: bool,
) -> std::result::Result<(), crate::Error> {
    use ripemd::{Digest as _, Ripemd160};
    use secp256k1::{Message, Secp256k1, SecretKey};
    use sha2::Sha256;

    assert!(signed_input_index < 2, "test fixture only has two inputs");

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("valid secret key");
    let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
    let pubkey_bytes = public_key.serialize();

    // Standard P2PKH lock script reused for every prevout.
    let sha_hash = Sha256::digest(pubkey_bytes);
    let pub_key_hash: [u8; 20] = Ripemd160::digest(sha_hash).into();
    let mut lock_script_bytes = vec![0x76, 0xa9, 0x14];
    lock_script_bytes.extend_from_slice(&pub_key_hash);
    lock_script_bytes.push(0x88);
    lock_script_bytes.push(0xac);
    let lock_script = transparent::Script::new(&lock_script_bytes);

    let prevout = || transparent::Output {
        value: 1_0000_0000u64.try_into().expect("valid amount"),
        lock_script: lock_script.clone(),
    };
    let all_previous_outputs = Arc::new(vec![prevout(), prevout()]);

    // Two inputs, one output: any input at index >= 1 has no corresponding
    // output for SIGHASH_SINGLE.
    let make_tx = |unlock_scripts: [Vec<u8>; 2]| Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        inputs: vec![
            transparent::Input::PrevOut {
                outpoint: transparent::OutPoint {
                    hash: transaction::Hash([0u8; 32]),
                    index: 0,
                },
                unlock_script: transparent::Script::new(&unlock_scripts[0]),
                sequence: u32::MAX,
            },
            transparent::Input::PrevOut {
                outpoint: transparent::OutPoint {
                    hash: transaction::Hash([1u8; 32]),
                    index: 0,
                },
                unlock_script: transparent::Script::new(&unlock_scripts[1]),
                sequence: u32::MAX,
            },
        ],
        outputs: vec![transparent::Output {
            value: 1_5000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let placeholder_tx = make_tx([Vec::new(), Vec::new()]);

    let canonical_hash_type = if anyone_can_pay {
        HashType::SINGLE | HashType::ANYONECANPAY
    } else {
        HashType::SINGLE
    };
    let raw_hash_type_byte = if anyone_can_pay { 0x83u8 } else { 0x03u8 };

    let sighasher = SigHasher::new(
        &placeholder_tx,
        NetworkUpgrade::Nu5,
        all_previous_outputs.clone(),
    )
    .expect("sighasher creation should succeed");
    let sighash = sighasher.sighash(
        canonical_hash_type,
        Some((signed_input_index, lock_script_bytes.clone())),
    );

    let msg = Message::from_digest(*sighash.as_ref());
    let signature = secp.sign_ecdsa(&msg, &secret_key);
    let der_sig = signature.serialize_der();

    let mut signed_unlock = Vec::new();
    signed_unlock.push((der_sig.len() + 1) as u8);
    signed_unlock.extend_from_slice(&der_sig);
    signed_unlock.push(raw_hash_type_byte);
    signed_unlock.push(pubkey_bytes.len() as u8);
    signed_unlock.extend_from_slice(&pubkey_bytes);

    // Other input is left empty; it isn't being verified by this call.
    let mut unlock_scripts: [Vec<u8>; 2] = [Vec::new(), Vec::new()];
    unlock_scripts[signed_input_index] = signed_unlock;

    let final_tx = make_tx(unlock_scripts);

    let verifier = super::CachedFfiTransaction::new(
        Arc::new(final_tx),
        all_previous_outputs,
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for v5 tx");
    verifier.is_valid(signed_input_index)
}

/// V5 SIGHASH_SINGLE on input 1 of a 2-in/1-out transaction must be rejected:
/// there is no `vout[1]` to commit to.
///
/// Before the fix, Zebra accepted this because librustzcash returns a digest
/// computed from an empty output list when the input index is past the output
/// vector. ZIP-244 §S.2a requires consensus-level rejection; zcashd enforces it.
#[test]
fn sighash_divergence_v5_sighash_single_no_corresponding_output_rejected() {
    let _init_guard = zebra_test::init();

    let result = build_and_verify_v5_p2pkh_single_with_missing_output(1, false);

    assert!(
        result.is_err(),
        "V5 SIGHASH_SINGLE with no corresponding output must fail script verification, \
         matching zcashd (ZIP-244 §S.2a)"
    );
}

/// Same as above with SIGHASH_SINGLE|ANYONECANPAY (0x83). The
/// corresponding-output rule applies regardless of the ANYONECANPAY flag.
#[test]
fn sighash_divergence_v5_sighash_single_anyonecanpay_no_corresponding_output_rejected() {
    let _init_guard = zebra_test::init();

    let result = build_and_verify_v5_p2pkh_single_with_missing_output(1, true);

    assert!(
        result.is_err(),
        "V5 SIGHASH_SINGLE|ANYONECANPAY with no corresponding output must fail script \
         verification, matching zcashd (ZIP-244 §S.2a)"
    );
}

/// Positive control: SIGHASH_SINGLE on input 0 of a 2-in/1-out transaction is
/// valid because `vout[0]` exists. This guards against the new check rejecting
/// legitimate SIGHASH_SINGLE spends.
#[test]
fn sighash_divergence_v5_sighash_single_with_corresponding_output_accepted() {
    let _init_guard = zebra_test::init();

    build_and_verify_v5_p2pkh_single_with_missing_output(0, false)
        .expect("V5 SIGHASH_SINGLE on an input with a corresponding output should be accepted");
}

/// Build a V4 P2PKH transparent spend, sign it under the supplied raw `hash_type`
/// byte using the V4 raw-byte sighash semantics, and run it through the script
/// verifier.
///
/// `zcashd` serializes the full raw `hash_type` byte into the V4 sighash
/// preimage (only masking with 0x1f for selection logic). Before the V4 fix,
/// Zebra canonicalized the byte before computing the sighash, so a tx using
/// e.g. `0x41` would be accepted by `zcashd` but rejected by Zebra (digest
/// mismatch). With the V4 fix, both implementations compute the same digest
/// and Zebra accepts.
fn build_and_verify_v4_p2pkh(sig_hash_type_byte: u8) -> std::result::Result<(), crate::Error> {
    use ripemd::{Digest as _, Ripemd160};
    use secp256k1::{Message, Secp256k1, SecretKey};
    use sha2::Sha256;

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("valid secret key");
    let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
    let pubkey_bytes = public_key.serialize();

    let sha_hash = Sha256::digest(pubkey_bytes);
    let pub_key_hash: [u8; 20] = Ripemd160::digest(sha_hash).into();
    let mut lock_script_bytes = vec![0x76, 0xa9, 0x14];
    lock_script_bytes.extend_from_slice(&pub_key_hash);
    lock_script_bytes.push(0x88);
    lock_script_bytes.push(0xac);
    let lock_script = transparent::Script::new(&lock_script_bytes);

    let previous_output = transparent::Output {
        value: 1_0000_0000u64.try_into().expect("valid amount"),
        lock_script: lock_script.clone(),
    };

    let placeholder_tx = Transaction::V4 {
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&[]),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let all_previous_outputs = Arc::new(vec![previous_output.clone()]);
    let sighasher = SigHasher::new(
        &placeholder_tx,
        NetworkUpgrade::Canopy,
        all_previous_outputs,
    )
    .expect("sighasher creation should succeed");

    // V4: use the raw byte to match zcashd's preimage semantics.
    let sighash =
        sighasher.sighash_v4_raw(sig_hash_type_byte, Some((0, lock_script_bytes.clone())));

    let msg = Message::from_digest(*sighash.as_ref());
    let signature = secp.sign_ecdsa(&msg, &secret_key);
    let der_sig = signature.serialize_der();

    let mut unlock_script_bytes = Vec::new();
    let sig_with_hashtype_len = der_sig.len() + 1;
    unlock_script_bytes.push(sig_with_hashtype_len as u8);
    unlock_script_bytes.extend_from_slice(&der_sig);
    unlock_script_bytes.push(sig_hash_type_byte);
    unlock_script_bytes.push(pubkey_bytes.len() as u8);
    unlock_script_bytes.extend_from_slice(&pubkey_bytes);

    let final_tx = Transaction::V4 {
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&unlock_script_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let verifier = super::CachedFfiTransaction::new(
        Arc::new(final_tx),
        Arc::new(vec![previous_output]),
        NetworkUpgrade::Canopy,
    )
    .expect("network upgrade should be valid for v4 tx");

    verifier.is_valid(0)
}

/// Variant A regression: V4 P2PKH spend with non-canonical hash_type 0x41 is accepted.
///
/// `zcashd` serializes the raw 0x41 byte into the V4 sighash preimage. Before the
/// V4 fix, Zebra canonicalized 0x41 → ALL (0x01) before computing the sighash,
/// producing a different digest than the one signed and rejecting the tx — a
/// consensus split where `zcashd` accepted what Zebra rejected.
///
/// With the V4 fix, the callback routes V4 transactions through `sighash_v4_raw`
/// using the raw byte, so the digests match and Zebra accepts.
#[test]
fn sighash_divergence_v4_p2pkh_extra_bits_0x41_accepted() {
    let _init_guard = zebra_test::init();

    build_and_verify_v4_p2pkh(0x41)
        .expect("V4 spend with non-canonical hash_type 0x41 should be accepted, matching zcashd");
}

/// Unit-level: for canonical bytes, `sighash_v4_raw` produces the same digest
/// as the typed `sighash` API. This guards against regressions in the new V4
/// raw-byte path on canonical inputs.
#[test]
fn sighash_divergence_v4_raw_canonical_matches_typed() {
    let _init_guard = zebra_test::init();

    let lock_script = transparent::Script::new(&[
        0x76, 0xa9, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0xac,
    ]);
    let previous_output = transparent::Output {
        value: 1_0000_0000u64.try_into().expect("valid amount"),
        lock_script: lock_script.clone(),
    };

    let tx = Transaction::V4 {
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&[]),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let sighasher = SigHasher::new(&tx, NetworkUpgrade::Canopy, Arc::new(vec![previous_output]))
        .expect("sighasher creation should succeed");

    let script_code = lock_script.as_raw_bytes().to_vec();

    let canonical_pairs: &[(HashType, u8)] = &[
        (HashType::ALL, 0x01),
        (HashType::NONE, 0x02),
        (HashType::SINGLE, 0x03),
        (HashType::ALL_ANYONECANPAY, 0x81),
        (HashType::NONE_ANYONECANPAY, 0x82),
        (HashType::SINGLE_ANYONECANPAY, 0x83),
    ];

    for &(typed, raw) in canonical_pairs {
        let typed_digest = sighasher.sighash(typed, Some((0, script_code.clone())));
        let raw_digest = sighasher.sighash_v4_raw(raw, Some((0, script_code.clone())));
        let typed_bytes: [u8; 32] = typed_digest.into();
        let raw_bytes: [u8; 32] = raw_digest.into();
        assert_eq!(
            typed_bytes, raw_bytes,
            "sighash_v4_raw({raw:#x}) should equal typed sighash for canonical input"
        );
    }
}

/// Test that `HashType::from_bits` with `is_strict=false` canonicalizes undefined raw hash_type
/// bytes instead of rejecting them. This is the root cause of the sighash consensus divergence:
///
/// - zcashd rejects undefined raw hash_type values for v5 transactions in `SighashType::parse`
/// - Zebra receives a canonicalized `HashType` through the FFI callback (which uses
///   `from_bits(hash_type, false)`) and computes a sighash for the canonical type
///
/// See docs/analysis/sighash_consensus_divergence_report.md for full details.
#[test]
fn sighash_divergence_from_bits_canonicalization() {
    let _init_guard = zebra_test::init();

    // These raw hash_type bytes are NOT valid for v5 transactions.
    // zcashd rejects them in SighashType::parse (transaction_ffi.rs:267-273).
    // Valid v5 values are: {0x01, 0x02, 0x03, 0x81, 0x82, 0x83}.
    let invalid_raw_bytes: &[(i32, &str)] = &[
        (
            0x84,
            "0x84: undefined bits set, canonicalizes to ALL|ANYONECANPAY (0x81)",
        ),
        (
            0x50,
            "0x50: undefined bits set, canonicalizes to ALL (0x01)",
        ),
        (
            0x00,
            "0x00: no signed_outputs bits set, canonicalizes to ALL (0x01)",
        ),
        (
            0x04,
            "0x04: undefined lower bits, canonicalizes to ALL (0x01)",
        ),
        (
            0xFF,
            "0xFF: all bits set, canonicalizes to SINGLE|ANYONECANPAY (0x83)",
        ),
        (
            0x85,
            "0x85: undefined bits set, canonicalizes to ALL|ANYONECANPAY (0x81)",
        ),
    ];

    for &(raw_byte, description) in invalid_raw_bytes {
        // Non-strict mode (what libzcash_script uses in the callback): SUCCEEDS
        // This is the lossy conversion that causes the divergence.
        let non_strict_result = zcash_script::signature::HashType::from_bits(raw_byte, false);
        assert!(
            non_strict_result.is_ok(),
            "from_bits({raw_byte:#x}, false) should succeed (canonicalize) but failed: {description}"
        );

        // Strict mode: REJECTS (matching zcashd v5 behavior)
        let strict_result = zcash_script::signature::HashType::from_bits(raw_byte, true);
        assert!(
            strict_result.is_err(),
            "from_bits({raw_byte:#x}, true) should reject undefined bits but succeeded: {description}"
        );
    }

    // Verify that all six valid canonical values pass both strict and non-strict.
    let valid_raw_bytes: &[i32] = &[0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
    for &raw_byte in valid_raw_bytes {
        assert!(
            zcash_script::signature::HashType::from_bits(raw_byte, false).is_ok(),
            "valid byte {raw_byte:#x} should pass non-strict"
        );
        assert!(
            zcash_script::signature::HashType::from_bits(raw_byte, true).is_ok(),
            "valid byte {raw_byte:#x} should pass strict"
        );
    }
}

/// Regression test for [GHSA-jv4h-j224-23cc] (Trigger A, "Coinbase Hidden Legacy Sigops").
///
/// zcashd's `GetLegacySigOpCount()` counts sigops in the coinbase input's `scriptSig`. Zebra
/// previously skipped the coinbase input entirely, so a miner could hide up to ~98 sigops (the
/// coinbase script length limit is 100 bytes) inside the coinbase `scriptSig` and avoid them being
/// charged against `MAX_BLOCK_SIGOPS`.
///
/// This test builds a v5 coinbase transaction whose `miner_data` consists entirely of `OP_CHECKSIG`
/// (`0xac`) bytes and asserts that `tx.sigops()` now returns the expected count covering every
/// `OP_CHECKSIG`.
///
/// [GHSA-jv4h-j224-23cc]: https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-jv4h-j224-23cc
#[test]
fn count_coinbase_legacy_sigops_includes_coinbase_script() -> Result<()> {
    let _init_guard = zebra_test::init();

    // 80 bytes of OP_CHECKSIG fits within the 100-byte coinbase script limit
    // even after the height prefix.
    const OP_CHECKSIG: u8 = 0xac;
    let miner_data = vec![OP_CHECKSIG; 80];

    let dummy_output_script = transparent::Script::new(&[0x51]); // OP_TRUE
    let output_amount = zebra_chain::amount::Amount::try_from(1_000_000)?;

    // Use a height after NU5 activation on Mainnet so v5 is the effective version.
    let network = Network::Mainnet;
    let height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("NU5 has a Mainnet activation height");

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::Coinbase {
            height,
            data: miner_data,
            sequence: 0xffff_ffff,
        }],
        outputs: vec![transparent::Output {
            value: output_amount,
            lock_script: dummy_output_script,
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    let _ = network;

    // Before the fix, Zebra's `Sigops` impl skipped the coinbase input and returned 0 for a
    // coinbase with no OP_CHECKSIG in its outputs. After the fix, every OP_CHECKSIG in the coinbase
    // `scriptSig` must be counted.
    let sigops = tx.sigops().expect("sigop count is finite");
    assert_eq!(
        sigops, 80,
        "coinbase scriptSig OP_CHECKSIG bytes must be counted against \
         MAX_BLOCK_SIGOPS (zcashd parity, GHSA-jv4h-j224-23cc)"
    );

    Ok(())
}

/// Regression test for [GHSA-jv4h-j224-23cc] (Trigger B, "Aggregate P2SH Sigops").
///
/// zcashd's `GetP2SHSigOpCount()` parses the redeem script (the last push in each P2SH input's
/// `scriptSig`) with `accurate=true` and sums the sigops across all inputs. Previously Zebra only
/// did this in the mempool policy, so a block containing P2SH inputs whose aggregate redeem-script
/// sigops exceeded `MAX_BLOCK_SIGOPS` could be accepted by Zebra but rejected by zcashd as
/// `bad-blk-sigops`.
///
/// This test exercises the free function `zebra_script::p2sh_sigop_count` directly on a synthetic
/// transaction with one P2SH input whose redeem script is 15 x OP_CHECKSIG.
///
/// [GHSA-jv4h-j224-23cc]: https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-jv4h-j224-23cc
#[test]
fn p2sh_sigop_count_counts_redeem_script() -> Result<()> {
    let _init_guard = zebra_test::init();

    const OP_CHECKSIG: u8 = 0xac;
    const OP_HASH160: u8 = 0xa9;
    const OP_EQUAL: u8 = 0x87;

    // Redeem script: 15 x OP_CHECKSIG. Each OP_CHECKSIG counts as 1.
    let redeem_script = vec![OP_CHECKSIG; 15];

    // scriptSig consists solely of a direct push of the redeem script. For a 15-byte payload we can
    // use the literal-length push opcode (0x01..=0x4b), which is just the length byte followed by
    // the data.
    let mut unlock_bytes = Vec::new();
    unlock_bytes.push(redeem_script.len() as u8);
    unlock_bytes.extend_from_slice(&redeem_script);
    let unlock_script = transparent::Script::new(&unlock_bytes);

    // scriptPubKey: OP_HASH160 <20 bytes> OP_EQUAL. The 20-byte payload value is irrelevant here:
    // `is_pay_to_script_hash()` only checks the length (23) and the surrounding opcodes.
    let mut lock_bytes = Vec::with_capacity(23);
    lock_bytes.push(OP_HASH160);
    lock_bytes.push(0x14);
    lock_bytes.extend_from_slice(&[0u8; 20]);
    lock_bytes.push(OP_EQUAL);
    let lock_script = transparent::Script::new(&lock_bytes);

    // Build a minimal non-coinbase transaction with a single P2SH input.
    let input = transparent::Input::PrevOut {
        outpoint: transparent::OutPoint {
            hash: zebra_chain::transaction::Hash([0u8; 32]),
            index: 0,
        },
        unlock_script,
        sequence: u32::MAX,
    };

    let spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script,
    };

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![input],
        outputs: vec![spent_output.clone()],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    assert_eq!(
        p2sh_sigop_count(&tx, std::slice::from_ref(&spent_output)),
        15,
        "P2SH redeem-script sigops must be counted against block-path \
         MAX_BLOCK_SIGOPS (zcashd parity, GHSA-jv4h-j224-23cc)"
    );

    // The `CachedFfiTransaction::p2sh_sigops()` method must delegate to the same counter, so the
    // block-verifier path yields the same count.
    let cached = super::CachedFfiTransaction::new(
        Arc::new(tx),
        Arc::new(vec![spent_output]),
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for tx");
    assert_eq!(cached.p2sh_sigops(), 15);

    Ok(())
}

/// Regression test: `p2sh_sigop_count` must agree with zcashd's
/// `GetP2SHSigOpCount()` when the redeem script contains a "disabled" opcode such as
/// `OP_CODESEPARATOR` (0xab).
#[test]
fn p2sh_sigop_count_matches_zcashd_when_redeem_script_contains_disabled_opcode() -> Result<()> {
    let _init_guard = zebra_test::init();

    const OP_HASH160: u8 = 0xa9;
    const OP_EQUAL: u8 = 0x87;
    const OP_CODESEPARATOR: u8 = 0xab; // "disabled" in the Rust parser; valid byte in zcashd's GetOp2
    const OP_CHECKMULTISIG: u8 = 0xae;

    // Redeem script: OP_CODESEPARATOR followed by 50 x OP_CHECKMULTISIG.
    // zcashd's GetSigOpCount(true): lastOpcode is OP_INVALIDOPCODE before the first
    // CHECKMULTISIG (and OP_CODESEPARATOR after it), so the `fAccurate && lastOpcode in
    // OP_1..=OP_16` branch never fires; every CHECKMULTISIG contributes the fallback
    // count of 20. Total: 50 * 20 = 1000.
    let mut redeem_script = vec![OP_CODESEPARATOR];
    redeem_script.extend(std::iter::repeat_n(OP_CHECKMULTISIG, 50));
    assert_eq!(redeem_script.len(), 51);

    // scriptSig: a single direct push of the 51-byte redeem script. 51 <= 0x4b, so the
    // literal-length push opcode is just the length byte followed by the payload.
    let mut unlock_bytes = Vec::with_capacity(1 + redeem_script.len());
    unlock_bytes.push(redeem_script.len() as u8);
    unlock_bytes.extend_from_slice(&redeem_script);
    let unlock_script = transparent::Script::new(&unlock_bytes);

    // scriptPubKey: OP_HASH160 <20 bytes> OP_EQUAL. The hash value is irrelevant: only
    // the shape (23 bytes, surrounding opcodes) is checked by `is_pay_to_script_hash`.
    let mut lock_bytes = Vec::with_capacity(23);
    lock_bytes.push(OP_HASH160);
    lock_bytes.push(0x14);
    lock_bytes.extend_from_slice(&[0u8; 20]);
    lock_bytes.push(OP_EQUAL);
    let lock_script = transparent::Script::new(&lock_bytes);

    let input = transparent::Input::PrevOut {
        outpoint: transparent::OutPoint {
            hash: zebra_chain::transaction::Hash([0u8; 32]),
            index: 0,
        },
        unlock_script,
        sequence: u32::MAX,
    };

    let spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script,
    };

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![input],
        outputs: vec![spent_output.clone()],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // zcashd's GetP2SHSigOpCount() returns 1000 here; Zebra's pure-Rust counter
    // short-circuits at the leading 0xab and returns 0. Failing this assertion is the
    // consensus-split bug.
    assert_eq!(
        p2sh_sigop_count(&tx, std::slice::from_ref(&spent_output)),
        1000,
        "P2SH redeem scripts containing a disabled opcode (e.g. OP_CODESEPARATOR) must \
         agree with zcashd's GetP2SHSigOpCount; the pure-Rust parser short-circuits on \
         disabled bytes, undercounting sigops and opening a chain split against zcashd"
    );

    // Same expectation through the block-verifier entry point.
    let cached = super::CachedFfiTransaction::new(
        Arc::new(tx),
        Arc::new(vec![spent_output]),
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for tx");
    assert_eq!(
        cached.p2sh_sigops(),
        1000,
        "CachedFfiTransaction::p2sh_sigops must agree with zcashd on redeem scripts \
         containing disabled opcodes"
    );

    Ok(())
}

/// Non-P2SH inputs, and coinbase inputs, must contribute zero P2SH sigops regardless of what bytes
/// appear in their `scriptSig`. zcashd skips the coinbase input in [`GetP2SHSigOpCount()`].
///
/// [`GetP2SHSigOpCount()`]: https://github.com/zcash/zcash/blob/bad7f7eadbbb3466bebe3354266c7f69f607fcfd/src/main.cpp#L770-L772
#[test]
fn p2sh_sigop_count_is_zero_for_non_p2sh_and_coinbase() -> Result<()> {
    let _init_guard = zebra_test::init();

    const OP_CHECKSIG: u8 = 0xac;

    // Build a coinbase tx with OP_CHECKSIG-filled `miner_data`: legacy counting sees these (Trigger
    // A), but P2SH counting must not.
    let network = Network::Mainnet;
    let nu5_height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("NU5 has a Mainnet activation height");
    let dummy_output_script = transparent::Script::new(&[0x51]);
    let output_amount = zebra_chain::amount::Amount::try_from(1_000_000)?;
    let coinbase_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::Coinbase {
            height: nu5_height,
            data: vec![OP_CHECKSIG; 80],
            sequence: 0xffff_ffff,
        }],
        outputs: vec![transparent::Output {
            value: output_amount,
            lock_script: dummy_output_script.clone(),
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    let _ = &network;

    // Coinbase inputs have no spent output; zcashd passes an empty vector.
    assert_eq!(p2sh_sigop_count(&coinbase_tx, &[]), 0);

    // A non-P2SH (p2pkh-shaped) lock script must also yield 0 P2SH sigops, even if the scriptSig's
    // last push happens to contain OP_CHECKSIG.
    let p2pkh_lock = transparent::Script::new(&hex::decode(
        "76a914f47cac1e6fec195c055994e8064ffccce0044dd788ac",
    )?);
    let mut unlock_bytes = vec![0x01_u8]; // single-byte push
    unlock_bytes.push(OP_CHECKSIG);
    let input = transparent::Input::PrevOut {
        outpoint: transparent::OutPoint {
            hash: zebra_chain::transaction::Hash([0u8; 32]),
            index: 0,
        },
        unlock_script: transparent::Script::new(&unlock_bytes),
        sequence: u32::MAX,
    };
    let spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script: p2pkh_lock,
    };
    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![input],
        outputs: vec![],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    assert_eq!(p2sh_sigop_count(&tx, &[spent_output]), 0);

    Ok(())
}

/// End-to-end regression test for [GHSA-jv4h-j224-23cc].
///
/// Reproduces the consensus-split condition: a block whose true `zcashd` transparent sigop total
/// (legacy + P2SH, including coinbase legacy) exceeds `MAX_BLOCK_SIGOPS = 20000`. Before the fix,
/// Zebra computed a reduced total that fit under the limit and accepted such a block.
///
/// This test exercises the same accumulation the block verifier performs in
/// `zebra_consensus::block::verify_block` (`block.rs` `sigops += response.sigops()`), where each
/// transaction's contribution is `tx.sigops() + cached.p2sh_sigops()` (set in
/// `zebra_consensus::transaction.rs`'s `Block`-path response).
///
/// Asserts:
/// - the legacy-only total (Zebra's pre-fix accounting) is below the limit;
/// - the legacy + P2SH total (Zebra's post-fix, zcashd-equivalent accounting) exceeds the limit,
///   demonstrating the consensus split is now visible to the block verifier.
///
/// [GHSA-jv4h-j224-23cc]: https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-jv4h-j224-23cc
#[test]
fn block_sigop_total_includes_coinbase_and_p2sh() -> Result<()> {
    let _init_guard = zebra_test::init();

    /// Matches `zebra_consensus::MAX_BLOCK_SIGOPS`. Hard-coded to avoid a reverse dependency on
    /// `zebra-consensus`.
    const MAX_BLOCK_SIGOPS: u32 = 20_000;
    const OP_CHECKSIG: u8 = 0xac;
    const OP_HASH160: u8 = 0xa9;
    const OP_EQUAL: u8 = 0x87;

    // Surface A: 80 OP_CHECKSIG bytes hidden in the coinbase scriptSig
    // (the coinbase script length limit is 100 bytes, including the height prefix).
    let network = Network::Mainnet;
    let nu5_height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("NU5 has a Mainnet activation height");
    let dummy_output_script = transparent::Script::new(&[0x51]); // OP_TRUE
    let output_amount = zebra_chain::amount::Amount::try_from(1_000_000)?;
    let coinbase_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::Coinbase {
            height: nu5_height,
            data: vec![OP_CHECKSIG; 80],
            sequence: 0xffff_ffff,
        }],
        outputs: vec![transparent::Output {
            value: output_amount,
            lock_script: dummy_output_script,
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    let _ = &network;

    // Surface B: each non-coinbase transaction has one P2SH input whose
    // 15-byte redeem script is 15 x OP_CHECKSIG, contributing 15 P2SH
    // sigops (the maximum standard P2SH redeem-script sigop count).
    let redeem_script = vec![OP_CHECKSIG; 15];
    let mut unlock_bytes = vec![redeem_script.len() as u8];
    unlock_bytes.extend_from_slice(&redeem_script);
    let unlock_script = transparent::Script::new(&unlock_bytes);

    let mut lock_bytes = Vec::with_capacity(23);
    lock_bytes.push(OP_HASH160);
    lock_bytes.push(0x14);
    lock_bytes.extend_from_slice(&[0u8; 20]);
    lock_bytes.push(OP_EQUAL);
    let lock_script = transparent::Script::new(&lock_bytes);

    let p2sh_input = transparent::Input::PrevOut {
        outpoint: transparent::OutPoint {
            hash: zebra_chain::transaction::Hash([0u8; 32]),
            index: 0,
        },
        unlock_script,
        sequence: u32::MAX,
    };
    let p2sh_spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script,
    };
    let p2sh_tx_template = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![p2sh_input],
        outputs: vec![],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // 1334 P2SH spends * 15 sigops = 20010 P2SH sigops.
    // Plus 80 coinbase legacy sigops = 20090 total, > MAX_BLOCK_SIGOPS.
    // The legacy-only total Zebra used to compute is 0 (pre-fix coinbase)
    // or 80 (post-fix coinbase), both well under the limit.
    const N_P2SH_TXS: u32 = 1334;
    let spent_outputs = std::slice::from_ref(&p2sh_spent_output);

    let coinbase_legacy = coinbase_tx.sigops().expect("sigop count is finite");
    let p2sh_legacy = p2sh_tx_template.sigops().expect("sigop count is finite");
    let p2sh_per_tx = p2sh_sigop_count(&p2sh_tx_template, spent_outputs);
    assert_eq!(coinbase_legacy, 80, "coinbase legacy sigops (Surface A)");
    assert_eq!(p2sh_per_tx, 15, "per-tx P2SH sigops (Surface B)");

    // Post-fix accounting matches what the block verifier accumulates in
    // `zebra_consensus::block::verify_block` via `response.sigops()`, where the response is built
    // in `zebra_consensus::transaction.rs`'s `Block`-path arm as `tx.sigops() +
    // cached.p2sh_sigops()`.
    //
    // Non-coinbase txs contribute legacy sigops from their inputs and outputs; here `p2sh_legacy`
    // is 0 (the redeem script bytes inside the scriptSig are NOT executed at the legacy level for a
    // literal push-only scriptSig).
    let post_fix_total = coinbase_legacy
        .saturating_add(N_P2SH_TXS.saturating_mul(p2sh_legacy.saturating_add(p2sh_per_tx)));

    assert!(
        post_fix_total > MAX_BLOCK_SIGOPS,
        "post-fix accounting must exceed MAX_BLOCK_SIGOPS to demonstrate \
         the consensus split is now visible: got {post_fix_total}"
    );

    Ok(())
}

/// Calling `is_valid` when `all_previous_outputs.len()` differs from `transaction.inputs().len()`
/// must return `Error::TxIndex`, even when the requested `input_index` is in range for
/// `all_previous_outputs`. This guards against verifying a script against a misaligned
/// previous output.
#[test]
fn is_valid_rejects_mismatched_previous_outputs_length() {
    let _init_guard = zebra_test::init();

    let transaction = SCRIPT_TX
        .zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()
        .expect("test fixture deserializes");

    // SCRIPT_TX has exactly one input. Pass two previous outputs so `.get(0)` succeeds
    // but the lengths disagree.
    let output = Output {
        value: (212 * u64::pow(10, 8)).try_into().expect("valid amount"),
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY),
    };
    let mismatched_outputs = Arc::new(vec![output.clone(), output]);

    let verifier =
        super::CachedFfiTransaction::new(transaction, mismatched_outputs, NetworkUpgrade::Blossom)
            .expect("constructor accepts mismatched-length outputs");

    let err = verifier
        .is_valid(0)
        .expect_err("mismatched length must be rejected by is_valid");
    assert_eq!(err, super::Error::TxIndex);
}

/// Calling `is_valid` with an `input_index` past the end of `all_previous_outputs` must
/// return `Error::TxIndex` instead of panicking.
#[test]
fn is_valid_rejects_out_of_range_input_index() {
    let _init_guard = zebra_test::init();

    let transaction = SCRIPT_TX
        .zcash_deserialize_into::<Arc<zebra_chain::transaction::Transaction>>()
        .expect("test fixture deserializes");
    let output = Output {
        value: (212 * u64::pow(10, 8)).try_into().expect("valid amount"),
        lock_script: transparent::Script::new(&SCRIPT_PUBKEY),
    };
    let previous_outputs = Arc::new(vec![output]);

    let verifier =
        super::CachedFfiTransaction::new(transaction, previous_outputs, NetworkUpgrade::Blossom)
            .expect("matched-length construction succeeds");

    // SCRIPT_TX has one input at index 0; index 1 is out of range.
    let err = verifier
        .is_valid(1)
        .expect_err("out-of-range input_index must error, not panic");
    assert_eq!(err, super::Error::TxIndex);
}

/// Regression test for the libzcash_script stale-sighash-buffer bypass.
///
/// Construct a V5 transaction whose scriptPubKey is:
///
/// ```text
/// <pubkey> OP_CHECKSIGVERIFY <pubkey> OP_CHECKSIG
/// ```
///
/// and whose scriptSig pushes two signatures over the same canonical
/// `SIGHASH_ALL` (0x01) digest, the first tagged with an *invalid* V5
/// hash-type byte (0x50) and the second tagged with the canonical 0x01:
///
/// ```text
/// <der_sig || 0x50>   (pushed first → bottom of stack)
/// <der_sig || 0x01>   (pushed second → top of stack)
/// ```
///
/// Script evaluation then:
///
/// 1. Consumes `<der_sig || 0x01>` via `OP_CHECKSIGVERIFY`. Zebra's callback
///    returns the canonical SIGHASH_ALL digest, the C++ verifier fills its
///    stack-local `sighashArray` with that digest, and the signature passes.
/// 2. Consumes `<der_sig || 0x50>` via `OP_CHECKSIG`. Zebra's callback sees
///    an invalid V5 hash-type byte. Prior to this fix the callback returned
///    `None`, libzcash_script silently wrote nothing to the C++ buffer, and
///    the C++ `CheckSig` verified the signature against the stale
///    SIGHASH_ALL digest from step 1 — accepting a spend that `zcashd`
///    rejects and splitting Zebra nodes from `zcashd` nodes.
///
/// With the defense-in-depth fix in `zebra-script::calculate_sighash`, the
/// callback now returns a per-call CSPRNG-derived sighash when the hash
/// type would have been rejected, so the second signature fails to verify
/// and `is_valid` returns an error — matching `zcashd`.
///
/// The bypass requires release-grade C++ optimizations in `libzcash_script`
/// (so the stack buffer is not zero-initialized and the prior digest
/// lingers between callbacks). The workspace `Cargo.toml` forces
/// `[profile.dev.package.libzcash_script]` to `opt-level = 3` in all
/// profiles so that `cargo test` exercises the vulnerable code path and
/// this regression test catches any re-introduction of the bug in both
/// dev and release builds.
#[test]
fn stale_sighash_buffer_v5_two_checksig_rejected() {
    use secp256k1::{Message, Secp256k1, SecretKey};

    let _init_guard = zebra_test::init();

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("valid secret key");
    let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
    let pubkey_bytes = public_key.serialize();

    // scriptPubKey: <0x21> <pubkey 33 bytes> OP_CHECKSIGVERIFY
    //               <0x21> <pubkey 33 bytes> OP_CHECKSIG
    // OP_CHECKSIGVERIFY = 0xad, OP_CHECKSIG = 0xac
    let mut lock_script_bytes = Vec::with_capacity(1 + 33 + 1 + 1 + 33 + 1);
    lock_script_bytes.push(0x21);
    lock_script_bytes.extend_from_slice(&pubkey_bytes);
    lock_script_bytes.push(0xad);
    lock_script_bytes.push(0x21);
    lock_script_bytes.extend_from_slice(&pubkey_bytes);
    lock_script_bytes.push(0xac);
    let lock_script = transparent::Script::new(&lock_script_bytes);

    let previous_output = transparent::Output {
        value: 1_0000_0000u64.try_into().expect("valid amount"),
        lock_script: lock_script.clone(),
    };

    // Placeholder V5 tx used to compute the sighash; the V5 (ZIP 244) sighash
    // does not depend on the unlock script contents, so we can sign, then
    // rebuild the transaction with the real unlock script.
    let placeholder_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&[]),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let all_previous_outputs = Arc::new(vec![previous_output.clone()]);
    let sighasher = SigHasher::new(&placeholder_tx, NetworkUpgrade::Nu5, all_previous_outputs)
        .expect("sighasher creation should succeed");

    // Canonical SIGHASH_ALL digest — this is the digest the attacker needs
    // the stale C++ buffer to still hold when the second CHECKSIG runs.
    let sighash = sighasher.sighash(HashType::ALL, Some((0, lock_script_bytes.clone())));
    let msg = Message::from_digest(*sighash.as_ref());
    let signature = secp.sign_ecdsa(&msg, &secret_key);
    let der_sig = signature.serialize_der();

    // scriptSig pushes:
    //   1. <der_sig || 0x50>  (bottom)
    //   2. <der_sig || 0x01>  (top, consumed by OP_CHECKSIGVERIFY first)
    let mut unlock_script_bytes = Vec::new();
    let sig_with_hashtype_len = (der_sig.len() + 1) as u8;

    unlock_script_bytes.push(sig_with_hashtype_len);
    unlock_script_bytes.extend_from_slice(&der_sig);
    unlock_script_bytes.push(0x50);

    unlock_script_bytes.push(sig_with_hashtype_len);
    unlock_script_bytes.extend_from_slice(&der_sig);
    unlock_script_bytes.push(0x01);

    let final_tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        lock_time: LockTime::unlocked(),
        expiry_height: block::Height(0),
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&unlock_script_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: 9000_0000u64.try_into().expect("valid amount"),
            lock_script: transparent::Script::new(&[0x00]),
        }],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let verifier = super::CachedFfiTransaction::new(
        Arc::new(final_tx),
        Arc::new(vec![previous_output]),
        NetworkUpgrade::Nu5,
    )
    .expect("network upgrade should be valid for v5 tx");

    assert!(
        verifier.is_valid(0).is_err(),
        "V5 tx exploiting the stale libzcash_script sighash buffer via \
         OP_CHECKSIGVERIFY + OP_CHECKSIG with an invalid second hash-type \
         byte (0x50) must be rejected, matching zcashd"
    );
}

#[test]
fn p2sh_sigop_count_uses_accurate_multisig_mode() -> Result<()> {
    let _init_guard = zebra_test::init();

    // P2SH redeem script: OP_1 <33-byte pubkey> OP_1 OP_CHECKMULTISIG (a 1-of-1 multisig).
    // zcashd's GetP2SHSigOpCount counts the redeem script with GetSigOpCount(true), so an
    // OP_N-prefixed CHECKMULTISIG counts as N (here 1). The legacy mode counts it as 20;
    // over-counting here lets a zcashd-valid block exceed Zebra's MAX_BLOCK_SIGOPS and splits
    // Zebra off the chain. This guards the accurate-mode P2SH counter.
    let mut redeem = vec![0x51u8, 0x21u8];
    redeem.extend_from_slice(&[0x02u8; 33]);
    redeem.extend_from_slice(&[0x51u8, 0xaeu8]);

    let mut unlock = vec![redeem.len() as u8];
    unlock.extend_from_slice(&redeem);

    let mut lock = vec![0xa9u8, 0x14u8];
    lock.extend_from_slice(&[0u8; 20]);
    lock.push(0x87u8);

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: transaction::Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(&unlock),
            sequence: u32::MAX,
        }],
        outputs: vec![transparent::Output {
            value: zebra_chain::amount::Amount::try_from(1_000_000)?,
            lock_script: transparent::Script::new(&[0x51]),
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    let spent = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script: transparent::Script::new(&lock),
    };

    // Accurate mode: 1. (Legacy mode would return 20.)
    assert_eq!(p2sh_sigop_count(&tx, std::slice::from_ref(&spent)), 1);
    Ok(())
}

fn poc_p2sh_1_of_1_multisig_scripts() -> (transparent::Script, transparent::Script) {
    const OP_1: u8 = 0x51;
    const OP_HASH160: u8 = 0xa9;
    const OP_EQUAL: u8 = 0x87;
    const OP_CHECKMULTISIG: u8 = 0xae;

    // Redeem script:
    //   OP_1 <33-byte compressed pubkey> OP_1 OP_CHECKMULTISIG
    //
    // zcashd's P2SH path calls GetSigOpCount(true), so this counts as 1 sigop.
    // Zebra's vulnerable path calls legacy_sigop_count_script -> GetSigOpCount(false),
    // so this counts as 20 sigops.
    let pubkey = [0x02u8; 33];

    let mut redeem_script = Vec::with_capacity(37);
    redeem_script.push(OP_1);
    redeem_script.push(0x21); // push 33-byte pubkey
    redeem_script.extend_from_slice(&pubkey);
    redeem_script.push(OP_1);
    redeem_script.push(OP_CHECKMULTISIG);
    assert_eq!(redeem_script.len(), 37);

    // scriptSig: push redeem_script as the final push.
    // The actual HASH160 match/signature validity is irrelevant for this accounting PoC;
    // p2sh_sigop_count only checks the spent output is P2SH-shaped and extracts the last push.
    let mut unlock_bytes = Vec::with_capacity(1 + redeem_script.len());
    unlock_bytes.push(redeem_script.len() as u8);
    unlock_bytes.extend_from_slice(&redeem_script);
    let unlock_script = transparent::Script::new(&unlock_bytes);

    // P2SH scriptPubKey shape:
    //   OP_HASH160 <20-byte hash> OP_EQUAL
    //
    // The hash value is intentionally dummy. p2sh_sigop_count only needs IsPayToScriptHash shape.
    let mut lock_bytes = Vec::with_capacity(23);
    lock_bytes.push(OP_HASH160);
    lock_bytes.push(0x14);
    lock_bytes.extend_from_slice(&[0u8; 20]);
    lock_bytes.push(OP_EQUAL);
    let lock_script = transparent::Script::new(&lock_bytes);

    (unlock_script, lock_script)
}

#[test]
fn poc_p2sh_accurate_multisig_should_count_one_not_twenty() -> Result<()> {
    let _init_guard = zebra_test::init();

    let (unlock_script, lock_script) = poc_p2sh_1_of_1_multisig_scripts();

    let input = transparent::Input::PrevOut {
        outpoint: transparent::OutPoint {
            hash: zebra_chain::transaction::Hash([0u8; 32]),
            index: 0,
        },
        unlock_script,
        sequence: u32::MAX,
    };

    let spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script,
    };

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![input],
        outputs: vec![transparent::Output {
            value: zebra_chain::amount::Amount::try_from(1_000_000)?,
            lock_script: transparent::Script::new(&[0x51]), // OP_TRUE dummy output
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let zebra_count = p2sh_sigop_count(&tx, std::slice::from_ref(&spent_output));

    assert_eq!(
        zebra_count, 1,
        "P2SH OP_1 <pubkey> OP_1 OP_CHECKMULTISIG must use accurate sigop mode"
    );

    Ok(())
}

#[test]
fn poc_p2sh_1001_accurate_multisigs_should_stay_below_block_sigop_limit() -> Result<()> {
    let _init_guard = zebra_test::init();

    const SPENDS: usize = 1_001;

    let (unlock_script, lock_script) = poc_p2sh_1_of_1_multisig_scripts();

    let inputs: Vec<_> = (0..SPENDS)
        .map(|i| {
            let mut hash = [0u8; 32];
            hash[..8].copy_from_slice(&(i as u64).to_le_bytes());

            transparent::Input::PrevOut {
                outpoint: transparent::OutPoint {
                    hash: zebra_chain::transaction::Hash(hash),
                    index: 0,
                },
                unlock_script: unlock_script.clone(),
                sequence: u32::MAX,
            }
        })
        .collect();

    let spent_output = transparent::Output {
        value: zebra_chain::amount::Amount::try_from(1_000_000)?,
        lock_script,
    };

    let spent_outputs = vec![spent_output; SPENDS];

    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs,
        outputs: vec![transparent::Output {
            value: zebra_chain::amount::Amount::try_from(1_000_000)?,
            lock_script: transparent::Script::new(&[0x51]), // OP_TRUE dummy output
        }],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let zebra_count = p2sh_sigop_count(&tx, &spent_outputs);
    let zcashd_accurate_count = SPENDS as u32;

    assert_eq!(
        zebra_count, zcashd_accurate_count,
        "Zebra should count each accurate 1-of-1 P2SH multisig spend as 1 sigop, not 20"
    );

    assert!(
        zebra_count <= 20_000,
        "A zcashd-valid block-level sigop total should not cross Zebra's MAX_BLOCK_SIGOPS"
    );

    Ok(())
}