tidecoin 0.33.0-beta

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

//! Tidecoin relay and standardness policy helpers.
//!
//! This module exposes policy constants and helpers mirrored from the Tidecoin node. These are not
//! consensus rules and may change as node policy evolves.

use core::cmp;
use core::fmt;

use consensus_core::{
    VERIFY_CHECKLOCKTIMEVERIFY, VERIFY_CHECKSEQUENCEVERIFY, VERIFY_CLEANSTACK,
    VERIFY_CONST_SCRIPTCODE, VERIFY_DISCOURAGE_UPGRADABLE_NOPS,
    VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, VERIFY_MINIMALDATA, VERIFY_MINIMALIF,
    VERIFY_NULLDUMMY, VERIFY_NULLFAIL, VERIFY_P2SH, VERIFY_PQ_STRICT, VERIFY_SHA512,
    VERIFY_WITNESS, VERIFY_WITNESS_V1_512,
};
use encoding::CompactSizeEncoder;

use super::constants::{MAX_BLOCK_SIGOPS_COST, WITNESS_SCALE_FACTOR};
use crate::network::Params;
use crate::script::{
    Instruction, ScriptExt as _, ScriptPubKey, ScriptPubKeyExt as _, ScriptSigExt as _,
};
use crate::transaction::{
    check_transaction_sanity, InputWeightPrediction, OutPoint, Transaction, TransactionExt,
    TransactionSanityError, TxOut, Version,
};
use crate::{Amount, BlockHeight, FeeRate, PqPublicKey, Witness, WitnessVersion};

/// Maximum weight of a transaction for it to be relayed by most nodes on the network.
pub const MAX_STANDARD_TX_WEIGHT: u32 = 800_000;

/// Minimum non-witness size for a standard transaction, set to 65 bytes.
pub const MIN_STANDARD_TX_NONWITNESS_SIZE: u32 = 65;

/// Maximum number of sigops in an IsStandard() P2SH script.
pub const MAX_P2SH_SIGOPS: usize = 15;

/// The maximum number of sigops we're willing to relay/mine in a single tx.
pub const MAX_STANDARD_TX_SIGOPS_COST: u32 = MAX_BLOCK_SIGOPS_COST as u32 / 5;

/// The maximum number of potentially executed legacy signature operations in a single standard tx.
pub const MAX_TX_LEGACY_SIGOPS: usize = 2_500;

/// The minimum incremental *feerate* (despite the name), in sats per virtual kilobyte for RBF.
pub const DEFAULT_INCREMENTAL_RELAY_FEE: u32 = 100;

/// The number of bytes equivalent per signature operation. Affects transaction relay through the
/// virtual size computation.
pub const DEFAULT_BYTES_PER_SIGOP: u32 = 20;

/// Default for `permit_bare_multisig`.
pub const DEFAULT_PERMIT_BAREMULTISIG: bool = false;

/// The maximum number of witness stack items in a standard P2WSH or P2WSH-512 script.
pub const MAX_STANDARD_P2WSH_STACK_ITEMS: usize = 100;

/// The maximum size in bytes of each witness stack item in a standard P2WSH or P2WSH-512 script.
pub const MAX_STANDARD_P2WSH_STACK_ITEM_SIZE: usize = 5_000;

/// The maximum size in bytes of a standard witness script.
pub const MAX_STANDARD_P2WSH_SCRIPT_SIZE: usize = 65_536;

/// The maximum size of a standard scriptSig.
pub const MAX_STANDARD_SCRIPTSIG_SIZE: usize = 8_192;

/// Min feerate for defining dust.
pub const DUST_RELAY_TX_FEE: u32 = 3_000;

/// Default minimum relay fee.
pub const DEFAULT_MIN_RELAY_TX_FEE: u32 = 100;

/// Default transaction version range accepted by node policy.
pub const TX_MIN_STANDARD_VERSION: Version = Version::ONE;
/// Default transaction version range accepted by node policy.
pub const TX_MAX_STANDARD_VERSION: Version = Version::THREE;

/// Tidecoin node TRUC transaction version.
pub const TRUC_VERSION: Version = Version::THREE;
/// Maximum sigop-adjusted virtual size for a stateless TRUC transaction.
pub const TRUC_MAX_VSIZE: i64 = 10_000;
/// Maximum sigop-adjusted virtual size for a TRUC child spending unconfirmed TRUC parents.
///
/// This requires mempool ancestor state and is exposed for higher validation layers.
pub const TRUC_CHILD_MAX_VSIZE: i64 = 4_000;

/// Maximum number of ephemeral dust outputs permitted in a standard transaction.
pub const MAX_DUST_OUTPUTS_PER_TX: usize = 1;

pub(crate) const MAX_OP_RETURN_RELAY: usize =
    MAX_STANDARD_TX_WEIGHT as usize / WITNESS_SCALE_FACTOR;

/// Mandatory script verification flags used by Tidecoin node relay policy.
pub const MANDATORY_SCRIPT_VERIFY_FLAGS: u32 = VERIFY_P2SH
    | VERIFY_NULLDUMMY
    | VERIFY_CHECKLOCKTIMEVERIFY
    | VERIFY_CHECKSEQUENCEVERIFY
    | VERIFY_WITNESS;

/// Standard script verification flags used by Tidecoin node relay policy before AuxPoW PQ flags.
pub const STANDARD_SCRIPT_VERIFY_FLAGS: u32 = MANDATORY_SCRIPT_VERIFY_FLAGS
    | VERIFY_MINIMALDATA
    | VERIFY_DISCOURAGE_UPGRADABLE_NOPS
    | VERIFY_CLEANSTACK
    | VERIFY_MINIMALIF
    | VERIFY_NULLFAIL
    | VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM
    | VERIFY_CONST_SCRIPTCODE;

/// Standard but not mandatory script verification flags used by Tidecoin node relay policy.
pub const STANDARD_NOT_MANDATORY_VERIFY_FLAGS: u32 =
    STANDARD_SCRIPT_VERIFY_FLAGS & !MANDATORY_SCRIPT_VERIFY_FLAGS;

/// Returns the Tidecoin node's standard policy script flags for the next block height.
pub fn standard_policy_script_flags(
    params: impl AsRef<Params>,
    next_block_height: BlockHeight,
) -> u32 {
    let mut flags = STANDARD_SCRIPT_VERIFY_FLAGS;
    if params.as_ref().auxpow_start_height.is_some_and(|height| next_block_height >= height) {
        flags |= VERIFY_PQ_STRICT | VERIFY_WITNESS_V1_512 | VERIFY_SHA512;
    }
    flags
}

/// Standard transaction policy error reasons, mirroring Tidecoin node strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StandardTxError {
    /// Transaction version is outside the standard relay range.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    Version,
    /// Transaction weight exceeds the standard relay limit.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    TxSize,
    /// An input scriptSig is too large.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    ScriptSigSize,
    /// An input scriptSig contains non-push opcodes.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    ScriptSigNotPushOnly,
    /// An output scriptPubKey is not a standard Tidecoin form.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    ScriptPubKey,
    /// Total OP_RETURN payload exceeds the standard data-carrier budget.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    DataCarrier,
    /// Bare multisig output is rejected by policy.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    BareMultisig,
    /// Transaction contains too many dust outputs.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    Dust,
}

/// Standard relay-precheck policy configuration mirrored from Tidecoin node defaults.
///
/// This covers only stateless and caller-supplied-UTXO standard relay prechecks. It does not model
/// dynamic mempool policy such as fee admission, conflicts, package limits, RBF, or package
/// ephemeral-dust spending.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StandardRelayPrecheckPolicy {
    /// Maximum OP_RETURN scriptPubKey bytes allowed across null-data outputs.
    pub max_datacarrier_bytes: Option<usize>,
    /// Whether bare multisig outputs are accepted by relay policy.
    pub permit_bare_multisig: bool,
    /// Dust relay feerate used for dust threshold calculation.
    pub dust_relay_fee: FeeRate,
}

impl StandardRelayPrecheckPolicy {
    /// Tidecoin node default standard relay-precheck policy.
    pub const DEFAULT: Self = Self {
        max_datacarrier_bytes: Some(MAX_OP_RETURN_RELAY),
        permit_bare_multisig: DEFAULT_PERMIT_BAREMULTISIG,
        dust_relay_fee: FeeRate::DUST,
    };
}

impl Default for StandardRelayPrecheckPolicy {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Error returned by [`check_standard_relay_prechecks`].
///
/// These errors mirror the node's standard relay-policy reason strings where this stateless helper
/// overlaps with the node mempool pipeline.
///
/// All variants here are policy or caller-context outcomes rather than proof
/// that the transaction is consensus-invalid.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StandardRelayPrecheckError {
    /// Context-free transaction sanity failed before policy checks.
    ///
    /// This usually indicates malformed or structurally invalid transaction
    /// data before standard relay policy is applied.
    TransactionSanity(TransactionSanityError),
    /// Coinbase transactions are only valid inside blocks, not as loose relay transactions.
    ///
    /// This is a relay/mempool admission rejection.
    Coinbase,
    /// Transaction-local `IsStandardTx` policy failed.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    StandardTx(StandardTxError),
    /// Witness version 1 outputs are not standard before AuxPoW activation.
    ///
    /// This is a relay-policy rejection keyed to activation height, not a
    /// statement that the transaction is otherwise malformed.
    WitnessV1PreAuxpow,
    /// Non-witness serialized transaction size is below the node relay floor.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    TxSizeSmall,
    /// UTXO-aware non-witness input standardness failed.
    ///
    /// This indicates caller-supplied prevout context led to a non-standard
    /// input classification under node relay policy.
    InputsNotStandard,
    /// UTXO-aware witness standardness failed.
    ///
    /// This indicates caller-supplied prevout context led to a non-standard
    /// witness classification under node relay policy.
    WitnessNotStandard,
    /// Standard transaction sigop cost exceeds the node relay limit.
    ///
    /// This is a relay-policy rejection, not a consensus failure.
    TooManySigops {
        /// Computed sigop cost.
        cost: usize,
    },
    /// TRUC transaction sigop-adjusted virtual size exceeds the stateless node limit.
    ///
    /// This is a relay-policy rejection for TRUC rules, not a consensus
    /// failure.
    TrucTxSize {
        /// Computed sigop-adjusted virtual size.
        vsize: i64,
    },
}

impl StandardRelayPrecheckError {
    /// Returns the Tidecoin node-compatible reason string for this policy failure.
    pub const fn reason(&self) -> &'static str {
        match self {
            Self::TransactionSanity(_) => "transaction-sanity",
            Self::Coinbase => "coinbase",
            Self::StandardTx(err) => err.reason(),
            Self::WitnessV1PreAuxpow => "witness-v1-pre-auxpow",
            Self::TxSizeSmall => "tx-size-small",
            Self::InputsNotStandard => "bad-txns-nonstandard-inputs",
            Self::WitnessNotStandard => "bad-witness-nonstandard",
            Self::TooManySigops { .. } => "bad-txns-too-many-sigops",
            Self::TrucTxSize { .. } => "TRUC-violation",
        }
    }
}

impl From<TransactionSanityError> for StandardRelayPrecheckError {
    fn from(err: TransactionSanityError) -> Self {
        Self::TransactionSanity(err)
    }
}

impl From<StandardTxError> for StandardRelayPrecheckError {
    fn from(err: StandardTxError) -> Self {
        Self::StandardTx(err)
    }
}

impl fmt::Display for StandardRelayPrecheckError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TransactionSanity(err) => {
                write!(f, "{}: {err}", self.reason())
            }
            Self::TooManySigops { cost } => {
                write!(f, "{}: {} exceeds {}", self.reason(), cost, MAX_STANDARD_TX_SIGOPS_COST)
            }
            Self::TrucTxSize { vsize } => {
                write!(
                    f,
                    "{}: version=3 tx is too big: {} > {}",
                    self.reason(),
                    vsize,
                    TRUC_MAX_VSIZE
                )
            }
            _ => f.write_str(self.reason()),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StandardRelayPrecheckError {}

impl StandardTxError {
    /// Returns the Tidecoin node-compatible reason string.
    pub const fn reason(self) -> &'static str {
        match self {
            Self::Version => "version",
            Self::TxSize => "tx-size",
            Self::ScriptSigSize => "scriptsig-size",
            Self::ScriptSigNotPushOnly => "scriptsig-not-pushonly",
            Self::ScriptPubKey => "scriptpubkey",
            Self::DataCarrier => "datacarrier",
            Self::BareMultisig => "bare-multisig",
            Self::Dust => "dust",
        }
    }
}

impl fmt::Display for StandardTxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.reason())
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StandardTxError {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StandardScriptType {
    NullData,
    Multisig,
    Standard,
}

pub(crate) fn dust_threshold(
    script_pubkey: &ScriptPubKey,
    dust_relay_fee: FeeRate,
) -> Option<Amount> {
    if script_pubkey.is_op_return() {
        return Amount::from_sat(0).ok();
    }

    let mut size = 8usize
        .checked_add(CompactSizeEncoder::encoded_size(script_pubkey.len()))?
        .checked_add(script_pubkey.len())?;

    if script_pubkey.is_witness_program() {
        let witness_cost = if script_pubkey.is_p2wpkh() {
            InputWeightPrediction::MAX_KNOWN_PQ_P2WPKH.witness_stack_size() / WITNESS_SCALE_FACTOR
        } else {
            InputWeightPrediction::MAX_KNOWN_PQ_WITNESS_SCRIPT_KEY_SPEND.witness_stack_size()
                / WITNESS_SCALE_FACTOR
        };
        size = size.checked_add(32 + 4 + 1 + witness_cost + 4)?;
    } else {
        let script_sig_size = InputWeightPrediction::MAX_KNOWN_PQ_NON_WITNESS_DUST_SCRIPT_SIG_SIZE;
        size = size.checked_add(32 + 4 + script_sig_size + 4)?;
    }

    Amount::from_sat((dust_relay_fee.to_sat_per_kvb_ceil()).checked_mul(size as u64)? / 1000).ok()
}

fn classify_multisig(script_pubkey: &ScriptPubKey) -> Option<(u8, u8)> {
    let mut instructions = script_pubkey.instructions();
    let required_sigs = match instructions.next()? {
        Ok(Instruction::Op(op)) => op.decode_pushnum()?,
        _ => return None,
    };

    let mut num_pubkeys = 0u8;
    loop {
        match instructions.next()? {
            Ok(Instruction::PushBytes(pubkey))
                if PqPublicKey::from_prefixed_slice(pubkey.as_bytes()).is_ok() =>
            {
                num_pubkeys = num_pubkeys.saturating_add(1);
            }
            Ok(Instruction::PushBytes(_)) => return None,
            Ok(Instruction::Op(op)) => {
                if op.decode_pushnum()? != num_pubkeys {
                    return None;
                }
                break;
            }
            Err(_) => return None,
        }
    }

    match instructions.next() {
        Some(Ok(Instruction::Op(op))) if op == crate::opcodes::all::OP_CHECKMULTISIG => {}
        _ => return None,
    }

    instructions.next().is_none().then_some((required_sigs, num_pubkeys))
}

fn is_p2pk(script_pubkey: &ScriptPubKey) -> bool {
    let mut instructions = script_pubkey.instructions();
    matches!(
        (instructions.next(), instructions.next(), instructions.next()),
        (Some(Ok(Instruction::PushBytes(pubkey))), Some(Ok(Instruction::Op(op))), None)
            if op == crate::opcodes::all::OP_CHECKSIG
                && PqPublicKey::from_prefixed_slice(pubkey.as_bytes()).is_ok()
    )
}

fn is_standard_null_data(script_pubkey: &ScriptPubKey) -> bool {
    if !script_pubkey.is_op_return() {
        return false;
    }

    let mut instructions = script_pubkey.instructions();
    match instructions.next() {
        Some(Ok(Instruction::Op(op))) if op == crate::opcodes::all::OP_RETURN => {}
        _ => return false,
    }

    instructions.all(|instruction| matches!(instruction, Ok(Instruction::PushBytes(_))))
}

fn classify_standard_script(script_pubkey: &ScriptPubKey) -> Option<StandardScriptType> {
    if script_pubkey.is_p2pkh()
        || script_pubkey.is_p2sh()
        || is_p2pk(script_pubkey)
        || script_pubkey.is_p2wpkh()
        || script_pubkey.is_p2wsh()
        || script_pubkey.is_p2wsh512()
    {
        return Some(StandardScriptType::Standard);
    }

    if let Some((m, n)) = classify_multisig(script_pubkey) {
        if (1..=3).contains(&n) && (1..=n).contains(&m) {
            return Some(StandardScriptType::Multisig);
        }
        return None;
    }

    if is_standard_null_data(script_pubkey) {
        return Some(StandardScriptType::NullData);
    }

    None
}

fn count_legacy_sigops_for_input(
    prevout: &TxOut,
    txin_script_sig: &crate::script::ScriptSig,
) -> usize {
    if prevout.script_pubkey.is_p2sh() {
        txin_script_sig.redeem_script().map(|redeem| redeem.count_sigops()).unwrap_or(0)
    } else {
        prevout.script_pubkey.count_sigops()
    }
}

/// Returns whether all outputs in the transaction are standard under Tidecoin policy.
pub fn is_standard_tx(
    tx: &Transaction,
    max_datacarrier_bytes: Option<usize>,
    permit_bare_multisig: bool,
    dust_relay_fee: FeeRate,
) -> Result<(), StandardTxError> {
    if tx.version.to_u32() < TX_MIN_STANDARD_VERSION.to_u32()
        || tx.version.to_u32() > TX_MAX_STANDARD_VERSION.to_u32()
    {
        return Err(StandardTxError::Version);
    }

    if tx.weight().to_wu() > MAX_STANDARD_TX_WEIGHT as u64 {
        return Err(StandardTxError::TxSize);
    }

    for txin in &tx.inputs {
        if txin.script_sig.len() > MAX_STANDARD_SCRIPTSIG_SIZE {
            return Err(StandardTxError::ScriptSigSize);
        }
        if !txin.script_sig.is_push_only() {
            return Err(StandardTxError::ScriptSigNotPushOnly);
        }
    }

    let mut datacarrier_bytes_left = max_datacarrier_bytes.unwrap_or(0);
    for txout in &tx.outputs {
        match classify_standard_script(&txout.script_pubkey) {
            Some(StandardScriptType::Standard) => {}
            Some(StandardScriptType::NullData) => {
                let size = txout.script_pubkey.len();
                if size > datacarrier_bytes_left {
                    return Err(StandardTxError::DataCarrier);
                }
                datacarrier_bytes_left -= size;
            }
            Some(StandardScriptType::Multisig) => {
                if !permit_bare_multisig {
                    return Err(StandardTxError::BareMultisig);
                }
            }
            None => return Err(StandardTxError::ScriptPubKey),
        }
    }

    let dust_outputs = tx
        .outputs
        .iter()
        .filter(|txout| {
            txout
                .script_pubkey
                .minimal_non_dust_custom(dust_relay_fee)
                .is_some_and(|min| txout.amount < min)
        })
        .count();
    if dust_outputs > MAX_DUST_OUTPUTS_PER_TX {
        return Err(StandardTxError::Dust);
    }

    Ok(())
}

/// Checks the standard-relay precheck subset of the Tidecoin node mempool path.
///
/// This deliberately mirrors the part of `MemPoolAccept::PreChecks` that can be evaluated from a
/// transaction, chain parameters, the next block height, and supplied spent outputs:
///
/// - context-free transaction sanity and loose-transaction coinbase rejection,
/// - `IsStandardTx`,
/// - pre-AuxPoW witness-v1 output policy,
/// - minimum non-witness transaction size,
/// - `AreInputsStandard`,
/// - `IsWitnessStandard`,
/// - standard transaction sigop-cost limit.
/// - stateless TRUC transaction virtual-size limit.
///
/// It does **not** perform full mempool acceptance. Fee admission, conflicts, RBF, ancestor and
/// descendant limits, package ephemeral-dust spending, input existence, coinbase maturity, and
/// `CheckTxInputs`-style value checks require mempool/UTXO state and belong to a higher validation
/// layer.
pub fn check_standard_relay_prechecks<S>(
    tx: &Transaction,
    params: impl AsRef<Params>,
    next_block_height: BlockHeight,
    spent: S,
    policy: StandardRelayPrecheckPolicy,
) -> Result<(), StandardRelayPrecheckError>
where
    S: FnMut(&OutPoint) -> Option<TxOut>,
{
    check_transaction_sanity(tx)?;

    if tx.is_coinbase() {
        return Err(StandardRelayPrecheckError::Coinbase);
    }

    is_standard_tx(
        tx,
        policy.max_datacarrier_bytes,
        policy.permit_bare_multisig,
        policy.dust_relay_fee,
    )?;

    let params = params.as_ref();
    let witness_v1_allowed =
        params.auxpow_start_height.is_some_and(|height| next_block_height >= height);
    if !witness_v1_allowed
        && tx
            .outputs
            .iter()
            .any(|txout| txout.script_pubkey.witness_version() == Some(WitnessVersion::V1))
    {
        return Err(StandardRelayPrecheckError::WitnessV1PreAuxpow);
    }

    if tx.base_size() < MIN_STANDARD_TX_NONWITNESS_SIZE as usize {
        return Err(StandardRelayPrecheckError::TxSizeSmall);
    }

    let mut spent = spent;
    if !are_inputs_standard(tx, &mut spent) {
        return Err(StandardRelayPrecheckError::InputsNotStandard);
    }

    if tx.inputs.iter().any(|input| !input.witness.is_empty())
        && !is_witness_standard(tx, &mut spent)
    {
        return Err(StandardRelayPrecheckError::WitnessNotStandard);
    }

    let sigop_cost = tx.total_sigop_cost(&mut spent);
    if sigop_cost > MAX_STANDARD_TX_SIGOPS_COST as usize {
        return Err(StandardRelayPrecheckError::TooManySigops { cost: sigop_cost });
    }

    if tx.version == TRUC_VERSION {
        let vsize = get_virtual_tx_size(tx.weight().to_wu() as i64, sigop_cost as i64);
        if vsize > TRUC_MAX_VSIZE {
            return Err(StandardRelayPrecheckError::TrucTxSize { vsize });
        }
    }

    Ok(())
}

/// Checks whether all non-witness inputs are standard under Tidecoin policy.
pub fn are_inputs_standard<S>(tx: &Transaction, mut spent: S) -> bool
where
    S: FnMut(&OutPoint) -> Option<TxOut>,
{
    if tx.is_coinbase() {
        return true;
    }

    let mut sigops = 0usize;
    for txin in &tx.inputs {
        let Some(prevout) = spent(&txin.previous_output) else {
            return false;
        };
        sigops = sigops.saturating_add(txin.script_sig.count_sigops());
        sigops = sigops.saturating_add(count_legacy_sigops_for_input(&prevout, &txin.script_sig));
        if sigops > MAX_TX_LEGACY_SIGOPS {
            return false;
        }

        if classify_standard_script(&prevout.script_pubkey).is_none() {
            return false;
        }

        if prevout.script_pubkey.is_p2sh() {
            let Some(redeem_script) = txin.script_sig.redeem_script() else {
                return false;
            };
            if redeem_script.count_sigops() > MAX_P2SH_SIGOPS {
                return false;
            }
        }
    }

    true
}

/// Checks whether all witness inputs obey Tidecoin node standardness limits.
pub fn is_witness_standard<S>(tx: &Transaction, mut spent: S) -> bool
where
    S: FnMut(&OutPoint) -> Option<TxOut>,
{
    if tx.is_coinbase() {
        return true;
    }

    for txin in &tx.inputs {
        if txin.witness.is_empty() {
            continue;
        }

        let Some(prevout) = spent(&txin.previous_output) else {
            return false;
        };

        let witness_ok = if prevout.script_pubkey.is_p2sh() {
            let Some(redeem_script) = txin.script_sig.redeem_script() else {
                return false;
            };
            witness_standard_for_program(redeem_script, &txin.witness)
        } else {
            witness_standard_for_program(&prevout.script_pubkey, &txin.witness)
        };

        if !witness_ok {
            return false;
        }
    }

    true
}

/// Returns whether the transaction spends any non-anchor witness program.
pub fn spends_non_anchor_witness_program<S>(tx: &Transaction, mut spent: S) -> bool
where
    S: FnMut(&OutPoint) -> Option<TxOut>,
{
    if tx.is_coinbase() {
        return false;
    }

    for txin in &tx.inputs {
        let Some(prevout) = spent(&txin.previous_output) else {
            continue;
        };

        if prevout.script_pubkey.witness_version() == Some(WitnessVersion::V0) {
            return true;
        }

        if prevout.script_pubkey.is_p2sh()
            && txin.script_sig.redeem_script().and_then(|redeem| redeem.witness_version())
                == Some(WitnessVersion::V0)
        {
            return true;
        }
    }

    false
}

/// The virtual transaction size, as computed by the Tidecoin node.
pub fn get_virtual_tx_size(weight: i64, n_sigops: i64) -> i64 {
    (cmp::max(weight, n_sigops * DEFAULT_BYTES_PER_SIGOP as i64) + WITNESS_SCALE_FACTOR as i64 - 1)
        / WITNESS_SCALE_FACTOR as i64
}

/// Returns the virtual size of a native PQ P2WPKH input for the provided signature and pubkey sizes.
pub fn pq_p2wpkh_input_vsize(sig_len: usize, pubkey_len: usize) -> i64 {
    let prediction = InputWeightPrediction::pq_p2wpkh_with_sizes(sig_len, pubkey_len);
    get_virtual_tx_size(prediction.total_weight().to_wu() as i64, 0)
}

/// Returns the virtual size of a P2SH-wrapped PQ P2WPKH input for the provided signature and pubkey sizes.
pub fn pq_p2sh_p2wpkh_input_vsize(sig_len: usize, pubkey_len: usize) -> i64 {
    let prediction = InputWeightPrediction::pq_nested_p2wpkh_with_sizes(sig_len, pubkey_len);
    get_virtual_tx_size(prediction.total_weight().to_wu() as i64, 0)
}

fn witness_standard_for_program<T: crate::script::ScriptHashableTag>(
    script: &crate::script::Script<T>,
    witness: &Witness,
) -> bool {
    if script.witness_version().is_none() {
        return false;
    }
    if script.is_p2wpkh() {
        return true;
    }
    if script.is_p2wsh() || script.is_p2wsh512() {
        let Some(witness_script) = witness.last() else {
            return false;
        };
        if witness_script.len() > MAX_STANDARD_P2WSH_SCRIPT_SIZE {
            return false;
        }
        let stack_items = witness.len().saturating_sub(1);
        if stack_items > MAX_STANDARD_P2WSH_STACK_ITEMS {
            return false;
        }
        if witness
            .iter()
            .take(stack_items)
            .any(|item| item.len() > MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
        {
            return false;
        }
        return true;
    }
    false
}

#[cfg(test)]
mod tests {
    use hashes::{sha256, sha512};

    use super::*;
    use crate::blockdata::script::{Builder, PushBytesBuf, ScriptBufExt as _};
    use crate::crypto::pq::{PqScheme, PqSchemeCryptoExt as _};
    use crate::prelude::Vec;
    use crate::script::{RedeemScriptBuf, ScriptPubKeyBuf, ScriptSigBuf, WitnessScriptBuf};
    use crate::transaction::{Transaction, TxIn, TxOut, Txid};
    use crate::witness::Witness;
    use crate::{absolute, Address, Network, PubkeyHash, Sequence};

    fn prevout(script_pubkey: ScriptPubKeyBuf, amount_sat: u64) -> TxOut {
        TxOut { amount: Amount::from_sat(amount_sat).unwrap(), script_pubkey }
    }

    fn tx_with_single_input(script_sig: ScriptSigBuf, outputs: Vec<TxOut>) -> Transaction {
        Transaction {
            version: Version::ONE,
            lock_time: absolute::LockTime::ZERO,
            inputs: vec![TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([1; 32]), vout: 0 },
                script_sig,
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }],
            outputs,
        }
    }

    fn witness_from_items(items: Vec<Vec<u8>>) -> Witness {
        Witness::from_slice(&items)
    }

    fn p2wsh_script_pubkey(witness_script: &WitnessScriptBuf) -> ScriptPubKeyBuf {
        ScriptPubKeyBuf::builder()
            .push_int_unchecked(0)
            .push_slice(sha256::Hash::hash(witness_script.as_bytes()).to_byte_array())
            .into_script()
    }

    fn p2wsh512_script_pubkey(witness_script: &WitnessScriptBuf) -> ScriptPubKeyBuf {
        ScriptPubKeyBuf::builder()
            .push_int_unchecked(1)
            .push_slice(sha512::Hash::hash(witness_script.as_bytes()).to_byte_array())
            .into_script()
    }

    fn p2sh_wrapped_witness_program_script_sig(witness_program: &ScriptPubKeyBuf) -> ScriptSigBuf {
        Builder::new()
            .push_slice(PushBytesBuf::try_from(witness_program.as_bytes().to_vec()).unwrap())
            .into_script()
    }

    fn tx_with_witness(script_sig: ScriptSigBuf, witness: Witness) -> Transaction {
        let mut tx =
            tx_with_single_input(script_sig, vec![prevout(ScriptPubKeyBuf::new(), 30_000)]);
        tx.inputs[0].witness = witness;
        tx
    }

    fn node_sized_witness_script(drop_count: usize) -> WitnessScriptBuf {
        let mut builder = Builder::new();
        for _ in 0..13 {
            builder = builder.push_slice(vec![1u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE]);
        }
        builder = builder.push_slice(vec![1u8; 479]);
        for _ in 0..drop_count {
            builder = builder.push_opcode(crate::opcodes::all::OP_DROP);
        }
        builder.into_script()
    }

    fn assert_witness_standard_for_native_and_wrapped(
        witness_program: ScriptPubKeyBuf,
        witness: Witness,
        expected: bool,
    ) {
        let native_tx = tx_with_witness(ScriptSigBuf::new(), witness.clone());
        assert_eq!(
            is_witness_standard(&native_tx, |_| Some(prevout(witness_program.clone(), 1))),
            expected,
            "native witness program standardness mismatch"
        );

        let wrapped_tx =
            tx_with_witness(p2sh_wrapped_witness_program_script_sig(&witness_program), witness);
        assert_eq!(
            is_witness_standard(&wrapped_tx, |_| Some(prevout(
                witness_program.to_p2sh().unwrap(),
                1
            ))),
            expected,
            "P2SH-wrapped witness program standardness mismatch"
        );
    }

    fn deterministic_pubkey(scheme: PqScheme, tag: u8) -> crate::crypto::pq::PqPublicKey {
        let seed: Vec<u8> = (0..scheme.deterministic_seed_len())
            .map(|i| tag ^ (i as u8).wrapping_mul(131))
            .collect();
        scheme.generate_keypair_from_seed(&seed).unwrap().0
    }

    fn pq_p2pk_script() -> ScriptPubKeyBuf {
        let pubkey = deterministic_pubkey(PqScheme::MlDsa87, 0x87);
        ScriptPubKeyBuf::builder()
            .push_slice(PushBytesBuf::try_from(pubkey.to_prefixed_bytes()).unwrap())
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script()
    }

    fn pq_bare_multisig_script(
        required_sigs: i32,
        pubkeys: &[crate::crypto::pq::PqPublicKey],
    ) -> ScriptPubKeyBuf {
        let mut builder = ScriptPubKeyBuf::builder().push_int(required_sigs).unwrap();
        for pubkey in pubkeys {
            builder =
                builder.push_slice(PushBytesBuf::try_from(pubkey.to_prefixed_bytes()).unwrap());
        }
        builder
            .push_int(pubkeys.len() as i32)
            .unwrap()
            .push_opcode(crate::opcodes::all::OP_CHECKMULTISIG)
            .into_script()
    }

    #[test]
    fn dust_thresholds_match_tidecoin_node_pq_proxies() {
        let p2pk = pq_p2pk_script();
        let p2pkh = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_DUP)
            .push_opcode(crate::opcodes::all::OP_HASH160)
            .push_slice([42u8; 20])
            .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let p2sh = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_HASH160)
            .push_slice([43u8; 20])
            .push_opcode(crate::opcodes::all::OP_EQUAL)
            .into_script();
        let p2wpkh =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([44u8; 20]).into_script();
        let p2wsh =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([45u8; 32]).into_script();
        let p2wsh512 =
            ScriptPubKeyBuf::builder().push_int_unchecked(1).push_slice([46u8; 64]).into_script();

        assert_eq!(p2pk.minimal_non_dust(), Amount::from_sat(29_628).unwrap());
        assert_eq!(p2pkh.minimal_non_dust(), Amount::from_sat(21_906).unwrap());
        assert_eq!(p2sh.minimal_non_dust(), Amount::from_sat(21_900).unwrap());
        assert_eq!(p2wpkh.minimal_non_dust(), Amount::from_sat(5_637).unwrap());
        assert_eq!(p2wsh.minimal_non_dust(), Amount::from_sat(5_676).unwrap());
        assert_eq!(p2wsh512.minimal_non_dust(), Amount::from_sat(5_772).unwrap());
    }

    #[test]
    fn dust_threshold_boundaries_match_node_rounding_policy() {
        let script_pubkey = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_DUP)
            .push_opcode(crate::opcodes::all::OP_HASH160)
            .push_slice([0x5a; 20])
            .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let dust_relay_fee = FeeRate::from_sat_per_kvb(3_702);
        let threshold = script_pubkey.minimal_non_dust_custom(dust_relay_fee).unwrap();
        let mut tx = tx_with_single_input(
            ScriptSigBuf::new(),
            vec![TxOut { amount: threshold, script_pubkey: script_pubkey.clone() }],
        );

        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                dust_relay_fee
            ),
            Ok(())
        );

        tx.outputs[0].amount = threshold.checked_sub(Amount::from_sat(1).unwrap()).unwrap();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                dust_relay_fee
            ),
            Ok(())
        );

        tx.outputs.push(TxOut {
            amount: threshold.checked_sub(Amount::from_sat(1).unwrap()).unwrap(),
            script_pubkey,
        });
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                dust_relay_fee
            ),
            Err(StandardTxError::Dust)
        );
    }

    #[test]
    fn is_standard_tx_datacarrier_budget_and_count_match_node_units() {
        let op_return_payload = |len: usize| {
            ScriptPubKeyBuf::builder()
                .push_opcode(crate::opcodes::all::OP_RETURN)
                .push_slice(PushBytesBuf::try_from(vec![0x42; len]).unwrap())
                .into_script()
        };
        let mut tx = tx_with_single_input(
            ScriptSigBuf::new(),
            vec![prevout(op_return_payload(80), 0), prevout(op_return_payload(80), 0)],
        );
        let budget = tx.outputs[0].script_pubkey.len() + tx.outputs[1].script_pubkey.len();

        assert_eq!(
            is_standard_tx(&tx, Some(budget), DEFAULT_PERMIT_BAREMULTISIG, FeeRate::DUST),
            Ok(())
        );
        assert_eq!(
            is_standard_tx(&tx, Some(budget - 1), DEFAULT_PERMIT_BAREMULTISIG, FeeRate::DUST),
            Err(StandardTxError::DataCarrier)
        );

        tx.outputs[0].script_pubkey = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .into_script();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::ScriptPubKey)
        );
    }

    #[test]
    fn bare_multisig_standardness_matrix_matches_node_limits() {
        let keys = [
            deterministic_pubkey(PqScheme::Falcon512, 0x71),
            deterministic_pubkey(PqScheme::Falcon512, 0x72),
            deterministic_pubkey(PqScheme::Falcon512, 0x73),
            deterministic_pubkey(PqScheme::Falcon512, 0x74),
        ];
        let cases = [
            ("one-of-one", pq_bare_multisig_script(1, &keys[..1]), true),
            ("one-of-three", pq_bare_multisig_script(1, &keys[..3]), true),
            ("three-of-three", pq_bare_multisig_script(3, &keys[..3]), true),
            ("zero-of-one", pq_bare_multisig_script(0, &keys[..1]), false),
            ("two-of-one", pq_bare_multisig_script(2, &keys[..1]), false),
            ("one-of-four", pq_bare_multisig_script(1, &keys), false),
        ];

        for (label, script_pubkey, standard_with_bare_multisig) in cases {
            let tx =
                tx_with_single_input(ScriptSigBuf::new(), vec![prevout(script_pubkey, 30_000)]);
            let expected_with_bare = if standard_with_bare_multisig {
                Ok(())
            } else {
                Err(StandardTxError::ScriptPubKey)
            };
            assert_eq!(
                is_standard_tx(&tx, Some(MAX_OP_RETURN_RELAY), true, FeeRate::DUST),
                expected_with_bare,
                "{label}: permit_bare_multisig=true"
            );
            assert_eq!(
                is_standard_tx(
                    &tx,
                    Some(MAX_OP_RETURN_RELAY),
                    DEFAULT_PERMIT_BAREMULTISIG,
                    FeeRate::DUST
                ),
                if standard_with_bare_multisig {
                    Err(StandardTxError::BareMultisig)
                } else {
                    Err(StandardTxError::ScriptPubKey)
                },
                "{label}: permit_bare_multisig=false"
            );
        }
    }

    #[test]
    fn is_standard_tx_matches_node_p2pk_classification() {
        let p2pk = pq_p2pk_script();
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(p2pk, 30_000)]);
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Ok(())
        );

        let invalid_p2pk = ScriptPubKeyBuf::builder()
            .push_slice([0x42u8; 33])
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(invalid_p2pk, 30_000)]);
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::ScriptPubKey)
        );
    }

    #[test]
    fn is_standard_tx_matches_node_multisig_pubkey_validation() {
        let keys = [
            deterministic_pubkey(PqScheme::Falcon512, 0x41),
            deterministic_pubkey(PqScheme::Falcon512, 0x42),
        ];
        let valid_multisig = pq_bare_multisig_script(2, &keys);
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(valid_multisig, 30_000)]);
        assert_eq!(is_standard_tx(&tx, Some(MAX_OP_RETURN_RELAY), true, FeeRate::DUST), Ok(()));
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::BareMultisig)
        );

        let invalid_multisig = ScriptPubKeyBuf::builder()
            .push_int(1)
            .unwrap()
            .push_slice([0x43u8; 33])
            .push_int(1)
            .unwrap()
            .push_opcode(crate::opcodes::all::OP_CHECKMULTISIG)
            .into_script();
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(invalid_multisig, 30_000)]);
        assert_eq!(
            is_standard_tx(&tx, Some(MAX_OP_RETURN_RELAY), true, FeeRate::DUST),
            Err(StandardTxError::ScriptPubKey)
        );
    }

    #[test]
    fn is_standard_tx_reasons_match_node_policy() {
        let output = prevout(
            ScriptPubKeyBuf::builder()
                .push_opcode(crate::opcodes::all::OP_DUP)
                .push_opcode(crate::opcodes::all::OP_HASH160)
                .push_slice([1u8; 20])
                .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
                .push_opcode(crate::opcodes::all::OP_CHECKSIG)
                .into_script(),
            30_000,
        );
        let mut tx = tx_with_single_input(ScriptSigBuf::new(), vec![output]);

        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Ok(())
        );

        tx.version = Version::maybe_non_standard(0);
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::Version)
        );

        tx.version = Version::ONE;
        tx.inputs[0].script_sig =
            Builder::new().push_opcode(crate::opcodes::all::OP_VERIFY).into_script();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::ScriptSigNotPushOnly)
        );

        tx.inputs[0].script_sig = ScriptSigBuf::new();
        tx.outputs[0].amount = Amount::from_sat(1).unwrap();
        tx.outputs.push(prevout(tx.outputs[0].script_pubkey.clone(), 1));
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::Dust)
        );

        tx.outputs.truncate(1);
        let pubkey = deterministic_pubkey(PqScheme::Falcon512, 0x31);
        tx.outputs[0].script_pubkey = pq_bare_multisig_script(1, &[pubkey]);
        tx.outputs[0].amount = Amount::from_sat(30_000).unwrap();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::BareMultisig)
        );
    }

    #[test]
    fn spends_non_anchor_witness_program_matches_node_policy() {
        let prev_script =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([42u8; 20]).into_script();
        let tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(ScriptPubKeyBuf::new(), 0)]);
        assert!(spends_non_anchor_witness_program(&tx, |_| Some(prevout(prev_script.clone(), 1))));

        let prev_script_v1 =
            ScriptPubKeyBuf::builder().push_int_unchecked(1).push_slice([43u8; 64]).into_script();
        assert!(!spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            prev_script_v1.clone(),
            1
        ))));
    }

    #[test]
    fn spends_non_anchor_witness_program_covers_node_output_types() {
        let pubkey = deterministic_pubkey(PqScheme::Falcon512, 0x51);
        let p2pk = ScriptPubKeyBuf::builder()
            .push_slice(PushBytesBuf::try_from(pubkey.to_prefixed_bytes()).unwrap())
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let p2pkh = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_DUP)
            .push_opcode(crate::opcodes::all::OP_HASH160)
            .push_slice(pubkey.key_id().to_byte_array())
            .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let native_p2wsh =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x11; 32]).into_script();
        let native_p2wpkh =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x22; 20]).into_script();
        let wrapped_p2wsh = native_p2wsh.to_p2sh().unwrap();
        let wrapped_p2wpkh = native_p2wpkh.to_p2sh().unwrap();

        let mut tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(ScriptPubKeyBuf::new(), 0)]);

        assert!(!spends_non_anchor_witness_program(&tx, |_| Some(prevout(p2pk.clone(), 1))));
        assert!(!spends_non_anchor_witness_program(&tx, |_| Some(prevout(p2pkh.clone(), 1))));

        let redeem_script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(native_p2wsh.as_bytes().to_vec()).unwrap())
            .into_script();
        tx.inputs[0].script_sig = redeem_script_sig;
        assert!(spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            wrapped_p2wsh.clone(),
            1
        ))));
        tx.inputs[0].script_sig = ScriptSigBuf::new();
        assert!(!spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            wrapped_p2wsh.clone(),
            1
        ))));

        assert!(spends_non_anchor_witness_program(&tx, |_| Some(prevout(native_p2wsh.clone(), 1))));
        assert!(spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            native_p2wpkh.clone(),
            1
        ))));

        let redeem_script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(native_p2wpkh.as_bytes().to_vec()).unwrap())
            .into_script();
        tx.inputs[0].script_sig = redeem_script_sig;
        assert!(spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            wrapped_p2wpkh.clone(),
            1
        ))));
        tx.inputs[0].script_sig = ScriptSigBuf::new();
        assert!(!spends_non_anchor_witness_program(&tx, |_| Some(prevout(
            wrapped_p2wpkh.clone(),
            1
        ))));
    }

    #[test]
    fn are_inputs_standard_enforces_p2sh_sigop_limit() {
        let redeem_script: RedeemScriptBuf = Builder::new()
            .push_slice([0u8; 0])
            .push_slice([2u8; 33])
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_NOT)
            .into_script();
        let p2sh_prevout = prevout(redeem_script.to_p2sh().unwrap(), 1);
        let script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(redeem_script.as_bytes().to_vec()).unwrap())
            .into_script();

        let tx = Transaction {
            version: Version::ONE,
            lock_time: absolute::LockTime::ZERO,
            inputs: vec![TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([7; 32]), vout: 0 },
                script_sig,
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }],
            outputs: vec![prevout(ScriptPubKeyBuf::new(), 0)],
        };

        assert!(are_inputs_standard(&tx, |_| Some(p2sh_prevout.clone())));

        let too_many_sigops: RedeemScriptBuf = Builder::new()
            .push_slice([0u8; 0])
            .push_slice([2u8; 33])
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_2DUP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_DROP)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_NOT)
            .into_script();
        let script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(too_many_sigops.as_bytes().to_vec()).unwrap())
            .into_script();
        let tx = Transaction {
            version: Version::ONE,
            lock_time: absolute::LockTime::ZERO,
            inputs: vec![TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([8; 32]), vout: 0 },
                script_sig,
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }],
            outputs: vec![prevout(ScriptPubKeyBuf::new(), 0)],
        };
        assert!(!are_inputs_standard(&tx, |_| Some(prevout(
            too_many_sigops.to_p2sh().unwrap(),
            1
        ))));
    }

    #[test]
    fn are_inputs_standard_allows_exact_max_legacy_sigops_and_rejects_one_more() {
        let fake_pubkey = [2u8; 33];
        let mut builder = Builder::new().push_slice([0u8; 0]).push_slice(fake_pubkey);
        for _ in 0..(MAX_P2SH_SIGOPS - 1) {
            builder = builder
                .push_opcode(crate::opcodes::all::OP_2DUP)
                .push_opcode(crate::opcodes::all::OP_CHECKSIG)
                .push_opcode(crate::opcodes::all::OP_DROP);
        }
        let redeem_script: RedeemScriptBuf = builder
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .push_opcode(crate::opcodes::all::OP_NOT)
            .into_script();
        assert_eq!(redeem_script.count_sigops(), MAX_P2SH_SIGOPS);
        let redeem_script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(redeem_script.as_bytes().to_vec()).unwrap())
            .into_script();
        let p2sh_prevout = prevout(redeem_script.to_p2sh().unwrap(), 1);

        let p2pkh_prevout = prevout(
            Address::p2pkh(PubkeyHash::from_byte_array([0x22; 20]), Network::Tidecoin)
                .script_pubkey(),
            1,
        );

        let mut tx = Transaction {
            version: Version::ONE,
            lock_time: absolute::LockTime::ZERO,
            inputs: Vec::new(),
            outputs: vec![prevout(ScriptPubKeyBuf::new(), 0)],
        };

        for vout in 0..166u32 {
            tx.inputs.push(TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([0x55; 32]), vout },
                script_sig: redeem_script_sig.clone(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            });
        }
        for vout in 166u32..176u32 {
            tx.inputs.push(TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([0x66; 32]), vout },
                script_sig: ScriptSigBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            });
        }

        let spent = |outpoint: &OutPoint| {
            if outpoint.txid == Txid::from_byte_array([0x55; 32]) {
                Some(p2sh_prevout.clone())
            } else if outpoint.txid == Txid::from_byte_array([0x66; 32]) {
                Some(p2pkh_prevout.clone())
            } else {
                None
            }
        };
        assert!(are_inputs_standard(&tx, spent));

        tx.inputs.push(TxIn {
            previous_output: OutPoint { txid: Txid::from_byte_array([0x66; 32]), vout: 176 },
            script_sig: ScriptSigBuf::new(),
            sequence: Sequence::MAX,
            witness: Witness::new(),
        });
        assert!(!are_inputs_standard(&tx, spent));
    }

    #[test]
    fn is_witness_standard_accepts_v1_512_and_rejects_oversized_items() {
        let witness_script: WitnessScriptBuf =
            Builder::new().push_opcode(crate::opcodes::all::OP_TRUE).into_script();
        let prev_script =
            ScriptPubKeyBuf::builder().push_int_unchecked(1).push_slice([9u8; 64]).into_script();
        let mut tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(ScriptPubKeyBuf::new(), 0)]);
        tx.inputs[0].witness.push(&[1u8][..]);
        tx.inputs[0].witness.push(witness_script.as_bytes());

        assert!(is_witness_standard(&tx, |_| Some(prevout(prev_script.clone(), 1))));

        tx.inputs[0].witness.clear();
        tx.inputs[0].witness.push(vec![0u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE + 1]);
        tx.inputs[0].witness.push(witness_script.as_bytes());
        assert!(!is_witness_standard(&tx, |_| Some(prevout(prev_script.clone(), 1))));
    }

    #[test]
    fn is_witness_standard_rejects_oversized_witness_script() {
        let prev_script =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x33; 32]).into_script();
        let mut tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(ScriptPubKeyBuf::new(), 0)]);
        tx.inputs[0].witness.push(&[1u8][..]);
        tx.inputs[0].witness.push(vec![0x51; MAX_STANDARD_P2WSH_SCRIPT_SIZE + 1]);

        assert!(!is_witness_standard(&tx, |_| Some(prevout(prev_script.clone(), 1))));
    }

    #[test]
    fn is_witness_standard_matches_node_native_and_wrapped_p2wsh_boundaries() {
        let simple_script: WitnessScriptBuf =
            Builder::new().push_opcode(crate::opcodes::all::OP_TRUE).into_script();
        let p2wsh = p2wsh_script_pubkey(&simple_script);

        let mut limit_items = vec![vec![1u8]; MAX_STANDARD_P2WSH_STACK_ITEMS];
        limit_items.push(simple_script.as_bytes().to_vec());
        assert_witness_standard_for_native_and_wrapped(
            p2wsh.clone(),
            witness_from_items(limit_items),
            true,
        );

        let mut too_many_items = vec![vec![1u8]; MAX_STANDARD_P2WSH_STACK_ITEMS + 1];
        too_many_items.push(simple_script.as_bytes().to_vec());
        assert_witness_standard_for_native_and_wrapped(
            p2wsh,
            witness_from_items(too_many_items),
            false,
        );

        let item_limit_script: WitnessScriptBuf =
            Builder::new().push_opcode(crate::opcodes::all::OP_DROP).into_script();
        let item_limit_spk = p2wsh_script_pubkey(&item_limit_script);
        assert_witness_standard_for_native_and_wrapped(
            item_limit_spk.clone(),
            witness_from_items(vec![
                vec![1u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE],
                item_limit_script.as_bytes().to_vec(),
            ]),
            true,
        );
        assert_witness_standard_for_native_and_wrapped(
            item_limit_spk,
            witness_from_items(vec![
                vec![1u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE + 1],
                item_limit_script.as_bytes().to_vec(),
            ]),
            false,
        );

        let max_script = node_sized_witness_script(15);
        assert_eq!(max_script.len(), MAX_STANDARD_P2WSH_SCRIPT_SIZE);
        assert_witness_standard_for_native_and_wrapped(
            p2wsh_script_pubkey(&max_script),
            witness_from_items(vec![vec![1u8], vec![1u8], max_script.as_bytes().to_vec()]),
            true,
        );

        let oversized_script = node_sized_witness_script(16);
        assert_eq!(oversized_script.len(), MAX_STANDARD_P2WSH_SCRIPT_SIZE + 1);
        assert_witness_standard_for_native_and_wrapped(
            p2wsh_script_pubkey(&oversized_script),
            witness_from_items(vec![
                vec![1u8],
                vec![1u8],
                vec![1u8],
                oversized_script.as_bytes().to_vec(),
            ]),
            false,
        );
    }

    #[test]
    fn is_witness_standard_matches_node_p2wsh512_boundaries() {
        let simple_script: WitnessScriptBuf =
            Builder::new().push_opcode(crate::opcodes::all::OP_TRUE).into_script();
        let p2wsh512 = p2wsh512_script_pubkey(&simple_script);

        let mut limit_items = vec![vec![1u8]; MAX_STANDARD_P2WSH_STACK_ITEMS];
        limit_items.push(simple_script.as_bytes().to_vec());
        assert_witness_standard_for_native_and_wrapped(
            p2wsh512.clone(),
            witness_from_items(limit_items),
            true,
        );

        let mut too_many_items = vec![vec![1u8]; MAX_STANDARD_P2WSH_STACK_ITEMS + 1];
        too_many_items.push(simple_script.as_bytes().to_vec());
        assert_witness_standard_for_native_and_wrapped(
            p2wsh512,
            witness_from_items(too_many_items),
            false,
        );

        let item_limit_script: WitnessScriptBuf =
            Builder::new().push_opcode(crate::opcodes::all::OP_DROP).into_script();
        let item_limit_spk = p2wsh512_script_pubkey(&item_limit_script);
        assert_witness_standard_for_native_and_wrapped(
            item_limit_spk.clone(),
            witness_from_items(vec![
                vec![1u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE],
                item_limit_script.as_bytes().to_vec(),
            ]),
            true,
        );
        assert_witness_standard_for_native_and_wrapped(
            item_limit_spk,
            witness_from_items(vec![
                vec![1u8; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE + 1],
                item_limit_script.as_bytes().to_vec(),
            ]),
            false,
        );

        let max_script = node_sized_witness_script(15);
        assert_witness_standard_for_native_and_wrapped(
            p2wsh512_script_pubkey(&max_script),
            witness_from_items(vec![vec![1u8], vec![1u8], max_script.as_bytes().to_vec()]),
            true,
        );

        let oversized_script = node_sized_witness_script(16);
        assert_witness_standard_for_native_and_wrapped(
            p2wsh512_script_pubkey(&oversized_script),
            witness_from_items(vec![
                vec![1u8],
                vec![1u8],
                vec![1u8],
                oversized_script.as_bytes().to_vec(),
            ]),
            false,
        );
    }

    #[test]
    fn pq_witness_item_policy_boundary_is_stricter_than_consensus_push_boundary() {
        let scheme = PqScheme::MlDsa87;
        let pubkey = deterministic_pubkey(scheme, 0x87);
        let witness_script: WitnessScriptBuf = Builder::new()
            .push_slice(PushBytesBuf::try_from(pubkey.to_prefixed_bytes()).unwrap())
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let prev_script = p2wsh_script_pubkey(&witness_script);

        let policy_limit_tx = tx_with_witness(
            ScriptSigBuf::new(),
            witness_from_items(vec![
                vec![0x42; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE],
                witness_script.as_bytes().to_vec(),
            ]),
        );
        assert!(is_witness_standard(&policy_limit_tx, |_| Some(prevout(prev_script.clone(), 1))));

        let policy_reject_tx = tx_with_witness(
            ScriptSigBuf::new(),
            witness_from_items(vec![
                vec![0x42; MAX_STANDARD_P2WSH_STACK_ITEM_SIZE + 1],
                witness_script.as_bytes().to_vec(),
            ]),
        );
        assert!(!is_witness_standard(&policy_reject_tx, |_| Some(prevout(prev_script.clone(), 1))));

        let consensus_push_limit_tx = tx_with_witness(
            ScriptSigBuf::new(),
            witness_from_items(vec![vec![0x42; 8192], witness_script.as_bytes().to_vec()]),
        );
        assert!(!is_witness_standard(&consensus_push_limit_tx, |_| Some(prevout(
            prev_script.clone(),
            1
        ))));
    }

    #[test]
    fn is_standard_tx_covers_additional_node_cases() {
        let output_script = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_DUP)
            .push_opcode(crate::opcodes::all::OP_HASH160)
            .push_slice([1u8; 20])
            .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
            .push_opcode(crate::opcodes::all::OP_CHECKSIG)
            .into_script();
        let mut tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(output_script, 30_000)]);

        tx.inputs[0].script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(vec![0u8; MAX_STANDARD_SCRIPTSIG_SIZE - 3]).unwrap())
            .into_script();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Ok(())
        );

        tx.inputs[0].script_sig = Builder::new()
            .push_slice(PushBytesBuf::try_from(vec![0u8; MAX_STANDARD_SCRIPTSIG_SIZE - 2]).unwrap())
            .into_script();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::ScriptSigSize)
        );

        tx.inputs[0].script_sig = ScriptSigBuf::new();
        tx.outputs[0].script_pubkey = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .push_slice(PushBytesBuf::try_from(vec![0u8; 81]).unwrap())
            .into_script();
        assert_eq!(
            is_standard_tx(&tx, Some(84), DEFAULT_PERMIT_BAREMULTISIG, FeeRate::DUST),
            Ok(())
        );
        assert_eq!(
            is_standard_tx(&tx, Some(83), DEFAULT_PERMIT_BAREMULTISIG, FeeRate::DUST),
            Err(StandardTxError::DataCarrier)
        );

        tx.outputs[0].script_pubkey = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .into_script();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::ScriptPubKey)
        );

        let pubkey = deterministic_pubkey(PqScheme::Falcon512, 0x32);
        tx.outputs[0].script_pubkey = pq_bare_multisig_script(1, &[pubkey]);
        assert_eq!(is_standard_tx(&tx, Some(MAX_OP_RETURN_RELAY), true, FeeRate::DUST), Ok(()));

        tx.outputs[0].script_pubkey = ScriptPubKeyBuf::builder()
            .push_opcode(crate::opcodes::all::OP_RETURN)
            .push_slice([0u8; 19])
            .into_script();
        tx.inputs = (0..20_000u32)
            .map(|vout| TxIn {
                previous_output: OutPoint { txid: Txid::from_byte_array([0x77; 32]), vout },
                script_sig: ScriptSigBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            })
            .collect();
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::TxSize)
        );
    }

    #[test]
    fn standard_relay_prechecks_reject_small_non_witness_transaction_after_is_standard_tx() {
        let mut tx = tx_with_single_input(
            ScriptSigBuf::new(),
            vec![prevout(
                ScriptPubKeyBuf::builder()
                    .push_opcode(crate::opcodes::all::OP_RETURN)
                    .into_script(),
                0,
            )],
        );
        tx.inputs[0].previous_output =
            OutPoint { txid: Txid::from_byte_array([0x91; 32]), vout: 0 };

        assert!(tx.base_size() < MIN_STANDARD_TX_NONWITNESS_SIZE as usize);
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Ok(())
        );
        assert_eq!(
            check_standard_relay_prechecks(
                &tx,
                Params::REGTEST,
                BlockHeight::from_u32(0),
                |_| Some(prevout(ScriptPubKeyBuf::new(), 1)),
                StandardRelayPrecheckPolicy::default(),
            ),
            Err(StandardRelayPrecheckError::TxSizeSmall)
        );
    }

    #[test]
    fn standard_relay_prechecks_reject_witness_v1_outputs_before_auxpow() {
        let script_pubkey =
            ScriptPubKeyBuf::builder().push_int_unchecked(1).push_slice([0x61; 64]).into_script();
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(script_pubkey, 10_000)]);
        let input_prevout = prevout(
            Address::p2pkh(PubkeyHash::from_byte_array([0x62; 20]), Network::Testnet)
                .script_pubkey(),
            10_000,
        );
        let spent = |_: &OutPoint| Some(input_prevout.clone());

        assert_eq!(
            check_standard_relay_prechecks(
                &tx,
                Params::TESTNET,
                BlockHeight::from_u32(999),
                spent,
                StandardRelayPrecheckPolicy::default(),
            ),
            Err(StandardRelayPrecheckError::WitnessV1PreAuxpow)
        );
        assert_eq!(
            check_standard_relay_prechecks(
                &tx,
                Params::TESTNET,
                BlockHeight::from_u32(1000),
                |_| Some(input_prevout.clone()),
                StandardRelayPrecheckPolicy::default(),
            ),
            Ok(())
        );
    }

    #[test]
    fn standard_policy_script_flags_match_node_auxpow_activation() {
        let base = STANDARD_SCRIPT_VERIFY_FLAGS;
        assert_eq!(standard_policy_script_flags(Params::TESTNET, BlockHeight::from_u32(999)), base);
        assert_eq!(
            standard_policy_script_flags(Params::TESTNET, BlockHeight::from_u32(1000)),
            base | VERIFY_PQ_STRICT | VERIFY_WITNESS_V1_512 | VERIFY_SHA512
        );
        assert_eq!(
            standard_policy_script_flags(Params::MAINNET, BlockHeight::from_u32(u32::MAX)),
            base
        );
    }

    #[test]
    fn standard_relay_prechecks_enforce_stateless_truc_vsize_limit() {
        let mut tx = tx_with_single_input(
            ScriptSigBuf::new(),
            vec![prevout(
                ScriptPubKeyBuf::builder()
                    .push_opcode(crate::opcodes::all::OP_DUP)
                    .push_opcode(crate::opcodes::all::OP_HASH160)
                    .push_slice([0x71; 20])
                    .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
                    .push_opcode(crate::opcodes::all::OP_CHECKSIG)
                    .into_script(),
                30_000,
            )],
        );
        tx.version = TRUC_VERSION;
        tx.inputs[0].witness.push(vec![0x42; (TRUC_MAX_VSIZE as usize * 4) + 1]);

        let input_prevout = prevout(
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x72; 20]).into_script(),
            30_000,
        );
        let Err(StandardRelayPrecheckError::TrucTxSize { vsize }) = check_standard_relay_prechecks(
            &tx,
            Params::REGTEST,
            BlockHeight::from_u32(0),
            |_| Some(input_prevout.clone()),
            StandardRelayPrecheckPolicy::default(),
        ) else {
            panic!("oversized TRUC transaction should fail stateless relay prechecks");
        };
        assert!(vsize > TRUC_MAX_VSIZE);
    }

    #[test]
    fn standard_relay_prechecks_truc_vsize_exact_boundary() {
        fn tx_with_witness_payload(payload_len: usize) -> Transaction {
            let mut tx = tx_with_single_input(
                ScriptSigBuf::new(),
                vec![prevout(
                    ScriptPubKeyBuf::builder()
                        .push_opcode(crate::opcodes::all::OP_DUP)
                        .push_opcode(crate::opcodes::all::OP_HASH160)
                        .push_slice([0x81; 20])
                        .push_opcode(crate::opcodes::all::OP_EQUALVERIFY)
                        .push_opcode(crate::opcodes::all::OP_CHECKSIG)
                        .into_script(),
                    30_000,
                )],
            );
            tx.version = TRUC_VERSION;
            tx.inputs[0].witness.push(vec![0x42; payload_len]);
            tx
        }

        let input_prevout = prevout(
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x82; 20]).into_script(),
            30_000,
        );
        let spent = |_: &OutPoint| Some(input_prevout.clone());
        let mut exact_payload = None;
        let mut too_large_payload = None;

        for payload_len in 0..=TRUC_MAX_VSIZE as usize * 4 {
            let tx = tx_with_witness_payload(payload_len);
            let vsize = get_virtual_tx_size(tx.weight().to_wu() as i64, 0);
            if vsize == TRUC_MAX_VSIZE {
                exact_payload = Some(payload_len);
            } else if vsize == TRUC_MAX_VSIZE + 1 {
                too_large_payload = Some(payload_len);
                break;
            }
        }

        let exact_tx =
            tx_with_witness_payload(exact_payload.expect("synthetic TRUC exact boundary exists"));
        assert_eq!(
            check_standard_relay_prechecks(
                &exact_tx,
                Params::REGTEST,
                BlockHeight::from_u32(0),
                spent,
                StandardRelayPrecheckPolicy::default(),
            ),
            Ok(())
        );

        let too_large_tx = tx_with_witness_payload(
            too_large_payload.expect("synthetic TRUC reject boundary exists"),
        );
        assert_eq!(
            check_standard_relay_prechecks(
                &too_large_tx,
                Params::REGTEST,
                BlockHeight::from_u32(0),
                |_| Some(input_prevout.clone()),
                StandardRelayPrecheckPolicy::default(),
            ),
            Err(StandardRelayPrecheckError::TrucTxSize { vsize: TRUC_MAX_VSIZE + 1 })
        );
    }

    #[test]
    fn standard_relay_prechecks_enforce_standard_sigop_cost_limit() {
        let pubkey = deterministic_pubkey(PqScheme::Falcon512, 0x63);
        let bare_multisig = pq_bare_multisig_script(1, &[pubkey]);
        let outputs = (0..=MAX_STANDARD_TX_SIGOPS_COST / 80)
            .map(|_| prevout(bare_multisig.clone(), 30_000))
            .collect();
        let tx = tx_with_single_input(ScriptSigBuf::new(), outputs);
        let input_prevout = prevout(
            Address::p2pkh(PubkeyHash::from_byte_array([0x64; 20]), Network::Regtest)
                .script_pubkey(),
            10_000,
        );
        let policy = StandardRelayPrecheckPolicy {
            permit_bare_multisig: true,
            ..StandardRelayPrecheckPolicy::default()
        };

        let Err(StandardRelayPrecheckError::TooManySigops { cost }) =
            check_standard_relay_prechecks(
                &tx,
                Params::REGTEST,
                BlockHeight::from_u32(0),
                |_| Some(input_prevout.clone()),
                policy,
            )
        else {
            panic!("too many standard sigops should be rejected");
        };
        assert!(cost > MAX_STANDARD_TX_SIGOPS_COST as usize);
    }

    #[test]
    fn pq_input_vsize_matches_node_formulas_all_schemes() {
        for scheme in PqScheme::KNOWN {
            let sig_len = scheme.max_sig_len_in_script();
            let pubkey_len = scheme.prefixed_pubkey_len();

            let witness_bytes = CompactSizeEncoder::encoded_size(2)
                + CompactSizeEncoder::encoded_size(sig_len)
                + sig_len
                + CompactSizeEncoder::encoded_size(pubkey_len)
                + pubkey_len;
            let native_weight = (41 * WITNESS_SCALE_FACTOR + witness_bytes) as i64;
            let nested_weight = (64 * WITNESS_SCALE_FACTOR + witness_bytes) as i64;

            assert_eq!(pq_p2wpkh_input_vsize(sig_len, pubkey_len), (native_weight + 3) / 4);
            assert_eq!(pq_p2sh_p2wpkh_input_vsize(sig_len, pubkey_len), (nested_weight + 3) / 4);
        }
    }

    #[test]
    #[cfg(feature = "tidecoin-node-validation")]
    fn pq_input_vsize_matches_tidecoin_node_bridge_all_schemes() {
        let harness = match node_parity::TidecoinNodeHarness::from_env() {
            Ok(harness) => harness,
            Err(err) => {
                std::eprintln!("skipping Tidecoin node-backed txsize test: {err}");
                return;
            }
        };

        for scheme in PqScheme::KNOWN {
            let sig_len = scheme.max_sig_len_in_script();
            let pubkey_len = scheme.prefixed_pubkey_len();

            assert_eq!(
                pq_p2wpkh_input_vsize(sig_len, pubkey_len),
                harness.pq_p2wpkh_input_vsize(sig_len, pubkey_len).unwrap()
            );
            assert_eq!(
                pq_p2sh_p2wpkh_input_vsize(sig_len, pubkey_len),
                harness.pq_p2sh_p2wpkh_input_vsize(sig_len, pubkey_len).unwrap()
            );
        }
    }

    #[test]
    fn pq_bare_multisig_is_non_standard() {
        let keys: Vec<_> = (0..2)
            .map(|idx| {
                PqScheme::Falcon512
                    .generate_keypair_from_seed(&vec![
                        idx as u8 + 1;
                        PqScheme::Falcon512.deterministic_seed_len()
                    ])
                    .unwrap()
                    .0
            })
            .collect();
        let script_pubkey = pq_bare_multisig_script(2, &keys);
        let tx = tx_with_single_input(ScriptSigBuf::new(), vec![prevout(script_pubkey, 30_000)]);

        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Err(StandardTxError::BareMultisig)
        );
    }

    #[test]
    fn pq_mldsa87_20_of_20_weight_stays_standard() {
        let scheme = PqScheme::MlDsa87;
        let pubkeys: Vec<_> = (0..20)
            .map(|idx| {
                let seed = vec![0x55 ^ idx as u8; scheme.deterministic_seed_len()];
                scheme.generate_keypair_from_seed(&seed).unwrap().0
            })
            .collect();
        let mut witness_builder = Builder::new().push_int(20).unwrap();
        for pubkey in &pubkeys {
            witness_builder = witness_builder
                .push_slice(PushBytesBuf::try_from(pubkey.to_prefixed_bytes()).unwrap());
        }
        let witness_script: WitnessScriptBuf = witness_builder
            .push_int(20)
            .unwrap()
            .push_opcode(crate::opcodes::all::OP_CHECKMULTISIG)
            .into_script();
        let prev_script = ScriptPubKeyBuf::builder()
            .push_int_unchecked(0)
            .push_slice(sha256::Hash::hash(witness_script.as_bytes()).to_byte_array())
            .into_script();
        let output_script =
            ScriptPubKeyBuf::builder().push_int_unchecked(0).push_slice([0x44; 20]).into_script();
        let mut tx =
            tx_with_single_input(ScriptSigBuf::new(), vec![prevout(output_script, 30_000)]);
        tx.inputs[0].witness.push(Vec::<u8>::new());
        for _ in 0..20 {
            tx.inputs[0].witness.push(vec![0x30; scheme.max_sig_len_in_script()]);
        }
        tx.inputs[0].witness.push(witness_script.as_bytes());

        assert!(tx.weight().to_wu() <= MAX_STANDARD_TX_WEIGHT as u64);
        assert_eq!(
            is_standard_tx(
                &tx,
                Some(MAX_OP_RETURN_RELAY),
                DEFAULT_PERMIT_BAREMULTISIG,
                FeeRate::DUST
            ),
            Ok(())
        );
        assert!(is_witness_standard(&tx, |_| Some(prevout(prev_script.clone(), 1))));
    }
}