blvm-consensus 0.1.10

Bitcoin Commons BLVM: Direct mathematical implementation of Bitcoin consensus rules from the Orange Paper
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
//! Transaction validation functions from Orange Paper Section 5.1
//!
//! Performance optimizations:
//! - Early-exit fast-path checks for obviously invalid transactions

use crate::constants::*;
use crate::error::{ConsensusError, Result};
use crate::types::*;
use crate::utxo_overlay::UtxoLookup;
use blvm_spec_lock::spec_locked;
use std::borrow::Cow;

// Cold error construction helpers - these paths are rarely taken
#[cold]
fn make_output_sum_overflow_error() -> ConsensusError {
    ConsensusError::TransactionValidation("Output value sum overflow".into())
}

#[cold]
fn make_fee_calculation_underflow_error() -> ConsensusError {
    ConsensusError::TransactionValidation("Fee calculation underflow".into())
}

/// Fast-path early-exit checks for transaction validation
///
/// Performs quick checks before expensive validation operations.
/// Returns Some(ValidationResult) if fast-path can determine validity, None if full validation needed.
#[inline(always)]
#[cfg(feature = "production")]
fn check_transaction_fast_path(tx: &Transaction) -> Option<ValidationResult> {
    // Quick reject: empty inputs or outputs (most common invalid case)
    if tx.inputs.is_empty() || tx.outputs.is_empty() {
        return Some(ValidationResult::Invalid("Empty inputs or outputs".into()));
    }

    // Quick reject: obviously too many inputs/outputs (before expensive size calculation)
    if tx.inputs.len() > MAX_INPUTS {
        return Some(ValidationResult::Invalid(format!(
            "Too many inputs: {}",
            tx.inputs.len()
        )));
    }
    if tx.outputs.len() > MAX_OUTPUTS {
        return Some(ValidationResult::Invalid(format!(
            "Too many outputs: {}",
            tx.outputs.len()
        )));
    }

    // Quick reject: obviously invalid value ranges (before expensive validation)
    // Check if any output value is negative or exceeds MAX_MONEY
    // Optimization: Use precomputed constant for u64 comparisons
    #[cfg(feature = "production")]
    {
        use crate::optimizations::precomputed_constants::MAX_MONEY_U64;
        for output in &tx.outputs {
            let value_u64 = output.value as u64;
            if output.value < 0 || value_u64 > MAX_MONEY_U64 {
                return Some(ValidationResult::Invalid(format!(
                    "Invalid output value: {}",
                    output.value
                )));
            }
        }
    }

    #[cfg(not(feature = "production"))]
    for output in &tx.outputs {
        if output.value < 0 || output.value > MAX_MONEY {
            return Some(ValidationResult::Invalid(format!(
                "Invalid output value: {}",
                output.value
            )));
        }
    }

    // Quick reject: coinbase with invalid scriptSig length
    // Optimization: Use constant folding for zero hash check
    #[cfg(feature = "production")]
    let is_coinbase_hash = {
        use crate::optimizations::constant_folding::is_zero_hash;
        is_zero_hash(&tx.inputs[0].prevout.hash)
    };

    #[cfg(not(feature = "production"))]
    let is_coinbase_hash = tx.inputs[0].prevout.hash == [0u8; 32];

    if tx.inputs.len() == 1 && is_coinbase_hash && tx.inputs[0].prevout.index == 0xffffffff {
        let script_sig_len = tx.inputs[0].script_sig.len();
        if !(2..=100).contains(&script_sig_len) {
            return Some(ValidationResult::Invalid(format!(
                "Coinbase scriptSig length {script_sig_len} must be between 2 and 100 bytes"
            )));
        }
    }

    // Fast-path can't validate everything, needs full validation
    None
}

/// CheckTransaction: 𝒯𝒳 → {valid, invalid}
///
/// A transaction tx = (v, ins, outs, lt) is valid if and only if:
/// 1. |ins| > 0 ∧ |outs| > 0
/// 2. ∀o ∈ outs: 0 ≤ o.value ≤ M_max
/// 3. ∑_{o ∈ outs} o.value ≤ M_max (total output sum)
/// 4. |ins| ≤ M_max_inputs
/// 5. |outs| ≤ M_max_outputs
/// 6. |tx| ≤ M_max_tx_size
/// 7. ∀i,j ∈ ins: i ≠ j ⟹ i.prevout ≠ j.prevout (no duplicate inputs)
/// 8. If tx is coinbase: 2 ≤ |ins[0].scriptSig| ≤ 100
///
/// Uses fast-path checks before full validation.
#[spec_locked("5.1")]
#[track_caller] // Better error messages showing caller location
#[cfg_attr(feature = "production", inline(always))]
#[cfg_attr(not(feature = "production"), inline)]
pub fn check_transaction(tx: &Transaction) -> Result<ValidationResult> {
    // Precondition checks: Validate function inputs
    // Note: We check these conditions and return Invalid rather than asserting,
    // to allow tests to verify the validation logic properly
    if tx.inputs.len() > MAX_INPUTS {
        return Ok(ValidationResult::Invalid(format!(
            "Input count {} exceeds maximum {}",
            tx.inputs.len(),
            MAX_INPUTS
        )));
    }
    if tx.outputs.len() > MAX_OUTPUTS {
        return Ok(ValidationResult::Invalid(format!(
            "Output count {} exceeds maximum {}",
            tx.outputs.len(),
            MAX_OUTPUTS
        )));
    }

    // Fast-path early exit for obviously invalid transactions
    #[cfg(feature = "production")]
    if let Some(result) = check_transaction_fast_path(tx) {
        return Ok(result);
    }

    // 1. Check inputs and outputs are not empty (redundant if fast-path worked, but safe fallback)
    // Note: We check this condition and return Invalid rather than asserting, to allow tests
    // to verify the validation logic properly
    if tx.inputs.is_empty() {
        // Coinbase transactions have exactly 1 input, so empty inputs means non-coinbase
        return Ok(ValidationResult::Invalid(
            "Transaction must have inputs unless it's a coinbase".to_string(),
        ));
    }
    if tx.outputs.is_empty() {
        return Ok(ValidationResult::Invalid(
            "Transaction must have at least one output".to_string(),
        ));
    }

    // 2. Check output values are valid and calculate total sum in one pass (Orange Paper Section 5.1, rules 2 & 3)
    // ∀o ∈ outs: 0 ≤ o.value ≤ M_max ∧ ∑_{o ∈ outs} o.value ≤ M_max
    // Use proven bounds for output access in hot path
    let mut total_output_value = 0i64;
    // Invariant assertion: Total output value must start at zero
    assert!(
        total_output_value == 0,
        "Total output value must start at zero"
    );
    #[cfg(feature = "production")]
    {
        use crate::optimizations::optimized_access::get_proven_by_;
        use crate::optimizations::precomputed_constants::MAX_MONEY_U64;
        for i in 0..tx.outputs.len() {
            if let Some(output) = get_proven_by_(&tx.outputs, i) {
                let value_u64 = output.value as u64;
                if output.value < 0 || value_u64 > MAX_MONEY_U64 {
                    return Ok(ValidationResult::Invalid(format!(
                        "Invalid output value {} at index {}",
                        output.value, i
                    )));
                }
                // Accumulate sum with overflow check
                // Invariant assertion: Output value must be non-negative before addition
                assert!(
                    output.value >= 0,
                    "Output value {} must be non-negative at index {}",
                    output.value,
                    i
                );
                total_output_value = total_output_value
                    .checked_add(output.value)
                    .ok_or_else(make_output_sum_overflow_error)?;
                // Invariant assertion: Total output value must remain non-negative after addition
                assert!(
                    total_output_value >= 0,
                    "Total output value {total_output_value} must be non-negative after output {i}"
                );
            }
        }
    }

    #[cfg(not(feature = "production"))]
    {
        for (i, output) in tx.outputs.iter().enumerate() {
            // Bounds checking assertion: Output index must be valid
            assert!(i < tx.outputs.len(), "Output index {i} out of bounds");
            // Check output value is valid (non-negative and within MAX_MONEY)
            // Note: We check this condition and return Invalid rather than asserting,
            // to allow tests to verify the validation logic properly
            if output.value < 0 || output.value > MAX_MONEY {
                return Ok(ValidationResult::Invalid(format!(
                    "Invalid output value {} at index {}",
                    output.value, i
                )));
            }
            // Accumulate sum with overflow check
            total_output_value = total_output_value
                .checked_add(output.value)
                .ok_or_else(make_output_sum_overflow_error)?;
            // Invariant assertion: Total output value must remain non-negative after addition
            assert!(
                total_output_value >= 0,
                "Total output value {total_output_value} must be non-negative after output {i}"
            );
        }
    }

    // 2b. Check total output sum is in valid range (MoneyRange)
    // MoneyRange(n) = (n >= 0 && n <= MAX_MONEY)
    // Optimization: Use precomputed constant for comparison
    // Invariant assertion: Total output value must be non-negative
    assert!(
        total_output_value >= 0,
        "Total output value {total_output_value} must be non-negative"
    );

    #[cfg(feature = "production")]
    {
        use crate::optimizations::precomputed_constants::MAX_MONEY_U64;
        let total_u64 = total_output_value as u64;
        // Check for invalid total output value and return error (before assert)
        if total_output_value < 0 || total_u64 > MAX_MONEY_U64 {
            return Ok(ValidationResult::Invalid(format!(
                "Total output value {total_output_value} is out of valid range [0, {MAX_MONEY}]"
            )));
        }
        // Invariant assertion: Total output value must not exceed MAX_MONEY
        // (This should never fail if the check above is correct)
        assert!(
            total_u64 <= MAX_MONEY_U64,
            "Total output value {total_output_value} must not exceed MAX_MONEY"
        );
    }

    #[cfg(not(feature = "production"))]
    {
        // Check for invalid total output value and return error (before assert)
        if !(0..=MAX_MONEY).contains(&total_output_value) {
            return Ok(ValidationResult::Invalid(format!(
                "Total output value {total_output_value} is out of valid range [0, {MAX_MONEY}]"
            )));
        }
        // Invariant assertion: Total output value must not exceed MAX_MONEY
        // (This should never fail if the check above is correct)
        assert!(
            total_output_value <= MAX_MONEY,
            "Total output value {total_output_value} must not exceed MAX_MONEY"
        );
    }

    // 3. Check input count limit (redundant if fast-path worked)
    if tx.inputs.len() > MAX_INPUTS {
        return Ok(ValidationResult::Invalid(format!(
            "Too many inputs: {}",
            tx.inputs.len()
        )));
    }

    // 4. Check output count limit (redundant if fast-path worked)
    if tx.outputs.len() > MAX_OUTPUTS {
        return Ok(ValidationResult::Invalid(format!(
            "Too many outputs: {}",
            tx.outputs.len()
        )));
    }

    // 5. Check transaction size limit (consensus CheckTransaction)
    // GetSerializeSize(TX_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT
    // This checks: stripped_size * 4 > 4,000,000, i.e., stripped_size > 1,000,000
    // calculate_transaction_size returns stripped size (no witness), matching TX_NO_WITNESS
    use crate::constants::MAX_BLOCK_WEIGHT;
    const WITNESS_SCALE_FACTOR: usize = 4;
    let tx_stripped_size = calculate_transaction_size(tx); // This is TX_NO_WITNESS size
    if tx_stripped_size * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT {
        return Ok(ValidationResult::Invalid(format!(
            "Transaction too large: stripped size {} bytes (weight {} > {})",
            tx_stripped_size,
            tx_stripped_size * WITNESS_SCALE_FACTOR,
            MAX_BLOCK_WEIGHT
        )));
    }

    // 7. Check for duplicate inputs (Orange Paper Section 5.1, rule 4)
    // ∀i,j ∈ ins: i ≠ j ⟹ i.prevout ≠ j.prevout
    // Optimization: Use HashSet for O(n) duplicate detection instead of O(n²) nested loop
    use std::collections::HashSet;
    let mut seen_prevouts = HashSet::with_capacity(tx.inputs.len());
    for (i, input) in tx.inputs.iter().enumerate() {
        // Bounds checking assertion: Input index must be valid
        assert!(i < tx.inputs.len(), "Input index {i} out of bounds");
        if !seen_prevouts.insert(&input.prevout) {
            return Ok(ValidationResult::Invalid(format!(
                "Duplicate input prevout at index {i}"
            )));
        }
    }

    // 8. Check coinbase scriptSig length (Orange Paper Section 5.1, rule 5)
    // If tx is coinbase: 2 ≤ |ins[0].scriptSig| ≤ 100
    if is_coinbase(tx) {
        debug_assert!(
            !tx.inputs.is_empty(),
            "Coinbase transaction must have at least one input"
        );
        let script_sig_len = tx.inputs[0].script_sig.len();
        if !(2..=100).contains(&script_sig_len) {
            return Ok(ValidationResult::Invalid(format!(
                "Coinbase scriptSig length {script_sig_len} must be between 2 and 100 bytes"
            )));
        }
    }

    // Postcondition assertion: Validation result must be Valid or Invalid
    // Note: This assertion documents the expected return type
    // The result is always Valid at this point (we would have returned Invalid earlier)

    Ok(ValidationResult::Valid)
}

/// CheckTxInputs: 𝒯𝒳 × 𝒰𝒮 × ℕ → {valid, invalid} × ℤ
///
/// For transaction tx with UTXO set us at height h:
/// 1. If tx is coinbase: return (valid, 0)
/// 2. If tx is not coinbase: ∀i ∈ ins: ¬i.prevout.IsNull() (Orange Paper Section 5.1, rule 6)
/// 3. Let total_in = Σᵢ us(i.prevout).value
/// 4. Let total_out = Σₒ o.value
/// 5. If total_in < total_out: return (invalid, 0)
/// 6. Return (valid, total_in - total_out)
#[spec_locked("5.1")]
#[cfg_attr(feature = "production", inline(always))]
#[cfg_attr(not(feature = "production"), inline)]
#[allow(clippy::overly_complex_bool_expr)] // Intentional tautological assertions for formal verification
pub fn check_tx_inputs<U: UtxoLookup>(
    tx: &Transaction,
    utxo_set: &U,
    height: Natural,
) -> Result<(ValidationResult, Integer)> {
    check_tx_inputs_with_utxos(tx, utxo_set, height, None)
}

/// Optimized version that accepts pre-collected UTXOs to avoid redundant lookups
pub fn check_tx_inputs_with_utxos<U: UtxoLookup>(
    tx: &Transaction,
    utxo_set: &U,
    height: Natural,
    pre_collected_utxos: Option<&[Option<&UTXO>]>,
) -> Result<(ValidationResult, Integer)> {
    // Precondition checks: Validate function inputs
    // Note: We check this condition and return Invalid rather than asserting,
    // to allow tests to verify the validation logic properly
    if tx.inputs.is_empty() && !is_coinbase(tx) {
        return Ok((
            ValidationResult::Invalid(
                "Transaction must have inputs unless it's a coinbase".to_string(),
            ),
            0,
        ));
    }
    assert!(
        height <= i64::MAX as u64,
        "Block height {height} must fit in i64"
    );
    assert!(
        utxo_set.len() <= u32::MAX as usize,
        "UTXO set size {} exceeds maximum",
        utxo_set.len()
    );

    // Check if this is a coinbase transaction
    if is_coinbase(tx) {
        // Postcondition assertion: Coinbase fee must be zero
        #[allow(clippy::eq_op)]
        {
            // Coinbase fee must be zero (tautology for formal verification)
        }
        return Ok((ValidationResult::Valid, 0));
    }

    // Check that non-coinbase inputs don't have null prevouts (Orange Paper Section 5.1, rule 6)
    // ∀i ∈ ins: ¬i.prevout.IsNull()
    // Use proven bounds for input access in hot path
    #[cfg(feature = "production")]
    {
        use crate::optimizations::constant_folding::is_zero_hash;
        use crate::optimizations::optimized_access::get_proven_by_;
        for i in 0..tx.inputs.len() {
            if let Some(input) = get_proven_by_(&tx.inputs, i) {
                if is_zero_hash(&input.prevout.hash) && input.prevout.index == 0xffffffff {
                    return Ok((
                        ValidationResult::Invalid(format!(
                            "Non-coinbase input {i} has null prevout"
                        )),
                        0,
                    ));
                }
            }
        }
    }

    #[cfg(not(feature = "production"))]
    {
        for (i, input) in tx.inputs.iter().enumerate() {
            if input.prevout.hash == [0u8; 32] && input.prevout.index == 0xffffffff {
                return Ok((
                    ValidationResult::Invalid(format!("Non-coinbase input {i} has null prevout")),
                    0,
                ));
            }
        }
    }

    // Optimization: Batch UTXO lookups - collect all prevouts first, then lookup
    // This improves cache locality and reduces HashMap traversal overhead
    // Optimization: Pre-allocate with known size
    #[cfg(feature = "production")]
    {
        use crate::optimizations::prefetch;
        // Prefetch ahead for sequential UTXO lookups
        for i in 0..tx.inputs.len().min(8) {
            if i + 4 < tx.inputs.len() {
                prefetch::prefetch_ahead(&tx.inputs, i, 4);
            }
        }
    }

    // OPTIMIZATION: Use pre-collected UTXOs if provided, otherwise collect them
    let input_utxos: Vec<(usize, Option<&UTXO>)> = if let Some(pre_utxos) = pre_collected_utxos {
        // Pre-collected UTXOs provided - use them directly (no redundant lookups)
        pre_utxos
            .iter()
            .enumerate()
            .map(|(i, opt_utxo)| (i, *opt_utxo))
            .collect()
    } else {
        // No pre-collected UTXOs - collect them now
        let mut result = Vec::with_capacity(tx.inputs.len());
        for (i, input) in tx.inputs.iter().enumerate() {
            result.push((i, utxo_set.get(&input.prevout)));
        }
        result
    };

    let mut total_input_value = 0i64;
    // Invariant assertion: Total input value must start at zero
    assert!(
        total_input_value == 0,
        "Total input value must start at zero"
    );

    for (i, opt_utxo) in input_utxos {
        // Bounds checking assertion: Input index must be valid
        assert!(i < tx.inputs.len(), "Input index {i} out of bounds");

        // Check if input exists in UTXO set
        if let Some(utxo) = opt_utxo {
            // Invariant assertion: UTXO value must be non-negative and within MAX_MONEY
            assert!(
                utxo.value >= 0,
                "UTXO value {} must be non-negative at input {}",
                utxo.value,
                i
            );
            assert!(
                utxo.value <= MAX_MONEY,
                "UTXO value {} must not exceed MAX_MONEY at input {}",
                utxo.value,
                i
            );

            // Check coinbase maturity: coinbase outputs cannot be spent until COINBASE_MATURITY blocks deep
            // Consensus: coinbase outputs require COINBASE_MATURITY confirmations
            // We check: if utxo.is_coinbase && height < utxo.height + COINBASE_MATURITY
            if utxo.is_coinbase {
                use crate::constants::COINBASE_MATURITY;
                let required_height = utxo.height.saturating_add(COINBASE_MATURITY);
                // Invariant assertion: Height must be sufficient for coinbase maturity
                assert!(
                    height >= utxo.height,
                    "Current height {} must be >= UTXO creation height {}",
                    height,
                    utxo.height
                );
                if height < required_height {
                    return Ok((
                        ValidationResult::Invalid(format!(
                            "Premature spend of coinbase output: input {i} created at height {} cannot be spent until height {} (current: {})",
                            utxo.height, required_height, height
                        )),
                        0,
                    ));
                }
            }

            // Use checked arithmetic to prevent overflow
            // Invariant assertion: UTXO value must be non-negative before addition
            assert!(
                utxo.value >= 0,
                "UTXO value {} must be non-negative before addition",
                utxo.value
            );
            total_input_value = total_input_value.checked_add(utxo.value).ok_or_else(|| {
                ConsensusError::TransactionValidation(
                    format!("Input value overflow at input {i}").into(),
                )
            })?;
            // Invariant assertion: Total input value must remain non-negative after addition
            assert!(
                total_input_value >= 0,
                "Total input value {total_input_value} must be non-negative after input {i}"
            );
        } else {
            #[cfg(debug_assertions)]
            {
                let hash_str: String = tx.inputs[i]
                    .prevout
                    .hash
                    .iter()
                    .map(|b| format!("{b:02x}"))
                    .collect();
                eprintln!(
                    "   ❌ UTXO NOT FOUND: Input {} prevout {}:{}",
                    i, hash_str, tx.inputs[i].prevout.index
                );
                eprintln!("      UTXO set size: {}", utxo_set.len());
            }
            return Ok((
                ValidationResult::Invalid(format!("Input {i} not found in UTXO set")),
                0,
            ));
        }
    }

    // Use checked sum to prevent overflow when summing outputs
    let total_output_value: i64 = tx
        .outputs
        .iter()
        .try_fold(0i64, |acc, output| {
            // Invariant assertion: Output value must be non-negative
            assert!(
                output.value >= 0,
                "Output value {} must be non-negative",
                output.value
            );
            acc.checked_add(output.value).ok_or_else(|| {
                ConsensusError::TransactionValidation("Output value overflow".into())
            })
        })
        .map_err(|e| ConsensusError::TransactionValidation(Cow::Owned(e.to_string())))?;

    // Invariant assertion: Total output value must be non-negative
    assert!(
        total_output_value >= 0,
        "Total output value {total_output_value} must be non-negative"
    );
    // Check that output total doesn't exceed MAX_MONEY
    assert!(
        total_output_value <= MAX_MONEY,
        "Total output value {total_output_value} must not exceed MAX_MONEY"
    );
    if total_output_value > MAX_MONEY {
        return Ok((
            ValidationResult::Invalid(format!(
                "Total output value {total_output_value} exceeds maximum money supply"
            )),
            0,
        ));
    }

    // Invariant assertion: Total input must be >= total output for valid transaction
    if total_input_value < total_output_value {
        return Ok((
            ValidationResult::Invalid("Insufficient input value".to_string()),
            0,
        ));
    }

    // Use checked subtraction to prevent underflow (shouldn't happen due to check above, but be safe)
    let fee = total_input_value
        .checked_sub(total_output_value)
        .ok_or_else(make_fee_calculation_underflow_error)?;

    // Postcondition assertions: Validate fee calculation result
    assert!(fee >= 0, "Fee {fee} must be non-negative");
    assert!(
        fee <= total_input_value,
        "Fee {fee} cannot exceed total input {total_input_value}"
    );
    assert!(
        total_input_value == total_output_value + fee,
        "Conservation of value: input {total_input_value} must equal output {total_output_value} + fee {fee}"
    );

    Ok((ValidationResult::Valid, fee))
}

/// Hot-path: validate inputs using pre-copied UTXO data (value, is_coinbase, height).
/// Avoids holding overlay refs; enables buffer reuse in block validation.
pub fn check_tx_inputs_with_owned_data(
    tx: &Transaction,
    height: Natural,
    utxo_data: &[Option<(i64, bool, u64)>],
) -> Result<(ValidationResult, Integer)> {
    if tx.inputs.is_empty() && !is_coinbase(tx) {
        return Ok((
            ValidationResult::Invalid(
                "Transaction must have inputs unless it's a coinbase".to_string(),
            ),
            0,
        ));
    }
    if is_coinbase(tx) {
        return Ok((ValidationResult::Valid, 0));
    }
    if utxo_data.len() != tx.inputs.len() {
        return Ok((
            ValidationResult::Invalid("UTXO data length mismatch".to_string()),
            0,
        ));
    }
    let mut total_input_value = 0i64;
    for (i, opt) in utxo_data.iter().enumerate() {
        if let Some((value, is_coinbase, utxo_height)) = opt {
            if *value < 0 || *value > MAX_MONEY {
                return Ok((
                    ValidationResult::Invalid(format!(
                        "UTXO value {value} out of bounds at input {i}"
                    )),
                    0,
                ));
            }
            if *is_coinbase {
                use crate::constants::COINBASE_MATURITY;
                let required_height = utxo_height.saturating_add(COINBASE_MATURITY);
                if height < required_height {
                    return Ok((
                        ValidationResult::Invalid(format!(
                            "Premature spend of coinbase output at input {i}"
                        )),
                        0,
                    ));
                }
            }
            total_input_value = total_input_value.checked_add(*value).ok_or_else(|| {
                ConsensusError::TransactionValidation(
                    format!("Input value overflow at input {i}").into(),
                )
            })?;
        } else {
            return Ok((
                ValidationResult::Invalid(format!("Input {i} not found in UTXO set")),
                0,
            ));
        }
    }
    let total_output_value: i64 = tx
        .outputs
        .iter()
        .try_fold(0i64, |acc, output| {
            acc.checked_add(output.value).ok_or_else(|| {
                ConsensusError::TransactionValidation("Output value overflow".into())
            })
        })
        .map_err(|e| ConsensusError::TransactionValidation(Cow::Owned(e.to_string())))?;
    if total_output_value > MAX_MONEY {
        return Ok((
            ValidationResult::Invalid(format!(
                "Total output value {total_output_value} exceeds maximum"
            )),
            0,
        ));
    }
    if total_input_value < total_output_value {
        return Ok((
            ValidationResult::Invalid("Insufficient input value".to_string()),
            0,
        ));
    }
    let fee = total_input_value
        .checked_sub(total_output_value)
        .ok_or_else(make_fee_calculation_underflow_error)?;
    Ok((ValidationResult::Valid, fee))
}

/// Check if transaction is coinbase
///
/// Hot-path function called frequently during validation.
/// Always inline for maximum performance.
#[inline(always)]
#[spec_locked("6.4")]
pub fn is_coinbase(tx: &Transaction) -> bool {
    // Optimization: Use constant folding for zero hash check
    #[cfg(feature = "production")]
    {
        use crate::optimizations::constant_folding::is_zero_hash;
        tx.inputs.len() == 1
            && is_zero_hash(&tx.inputs[0].prevout.hash)
            && tx.inputs[0].prevout.index == 0xffffffff
    }

    #[cfg(not(feature = "production"))]
    {
        tx.inputs.len() == 1
            && tx.inputs[0].prevout.hash == [0u8; 32]
            && tx.inputs[0].prevout.index == 0xffffffff
    }
}

/// Calculate transaction size (non-witness serialization)
///
/// Hot-path function called frequently during validation.
/// Always inline for maximum performance.
#[inline(always)]
///
/// This function calculates the size of a transaction when serialized
/// without witness data (base serialization size).
///
/// CRITICAL: This must match the actual serialized size exactly to ensure
/// consensus compatibility.
#[spec_locked("5.1")]
pub fn calculate_transaction_size(tx: &Transaction) -> usize {
    // Use actual serialization for consensus compatibility
    // This replaces the simplified calculation that didn't account for varint encoding
    use crate::serialization::transaction::serialize_transaction;
    serialize_transaction(tx).len()
}

// ============================================================================
// FORMAL VERIFICATION
// ============================================================================

/// Mathematical Specification for Transaction Validation (Orange Paper Section 5.1):
/// ∀ tx ∈ 𝒯𝒳: CheckTransaction(tx) = valid ⟺
///   (|tx.inputs| > 0 ∧ |tx.outputs| > 0 ∧
///    ∀o ∈ tx.outputs: 0 ≤ o.value ≤ M_max ∧
///    ∑_{o ∈ tx.outputs} o.value ≤ M_max ∧
///    |tx.inputs| ≤ M_max_inputs ∧ |tx.outputs| ≤ M_max_outputs ∧
///    |tx| ≤ M_max_tx_size ∧
///    ∀i,j ∈ tx.inputs: i ≠ j ⟹ i.prevout ≠ j.prevout ∧
///    (IsCoinbase(tx) ⟹ 2 ≤ |tx.inputs[0].scriptSig| ≤ 100))
///
/// Invariants:
/// - Valid transactions have non-empty inputs and outputs
/// - Output values are bounded [0, MAX_MONEY] individually (rule 2)
/// - Total output sum doesn't exceed MAX_MONEY (rule 3)
/// - Input/output counts respect limits
/// - Transaction size respects limits
/// - No duplicate prevouts in inputs (rule 4)
/// - Coinbase transactions have scriptSig length [2, 100] bytes (rule 5)
/// - Non-coinbase inputs must not have null prevouts (rule 6, checked in check_tx_inputs)

/// Proptest strategies for transaction-shaped values (no `Arbitrary` impl — orphan rules).
#[cfg(test)]
pub(crate) mod transaction_proptest {
    use super::*;
    use proptest::prelude::*;

    pub fn arb_transaction() -> BoxedStrategy<Transaction> {
        (
            any::<u64>(),
            prop::collection::vec(
                (
                    any::<[u8; 32]>(),
                    any::<u64>(),
                    prop::collection::vec(any::<u8>(), 0..100),
                    any::<u64>(),
                ),
                0..10,
            ),
            prop::collection::vec(
                (any::<i64>(), prop::collection::vec(any::<u8>(), 0..100)),
                0..10,
            ),
            any::<u64>(),
        )
            .prop_map(|(version, inputs, outputs, lock_time)| {
                let inputs: Vec<TransactionInput> = inputs
                    .into_iter()
                    .map(|(hash, index, script_sig, sequence)| TransactionInput {
                        prevout: OutPoint {
                            hash,
                            index: index as u32,
                        },
                        script_sig,
                        sequence,
                    })
                    .collect();
                let outputs: Vec<TransactionOutput> = outputs
                    .into_iter()
                    .map(|(value, script_pubkey)| TransactionOutput {
                        value,
                        script_pubkey,
                    })
                    .collect();
                Transaction {
                    version,
                    #[cfg(feature = "production")]
                    inputs: inputs.into(),
                    #[cfg(not(feature = "production"))]
                    inputs,
                    #[cfg(feature = "production")]
                    outputs: outputs.into(),
                    #[cfg(not(feature = "production"))]
                    outputs,
                    lock_time,
                }
            })
            .boxed()
    }

    pub fn arb_outpoint() -> impl Strategy<Value = OutPoint> {
        (any::<[u8; 32]>(), any::<u32>()).prop_map(|(hash, index)| OutPoint { hash, index })
    }

    pub fn arb_utxo() -> impl Strategy<Value = UTXO> {
        (
            any::<i64>(),
            prop::collection::vec(any::<u8>(), 0..40),
            any::<u64>(),
            any::<bool>(),
        )
            .prop_map(|(value, script_pubkey, height, is_coinbase)| UTXO {
                value,
                script_pubkey: script_pubkey.into(),
                height,
                is_coinbase,
            })
    }
}

#[cfg(test)]
#[allow(unused_doc_comments)]
mod property_tests {
    use super::transaction_proptest::{arb_outpoint, arb_transaction, arb_utxo};
    use super::*;
    use proptest::prelude::*;

    /// Property test: check_transaction validates structure correctly
    proptest! {
        #[test]
        fn prop_check_transaction_structure(
            tx in arb_transaction()
        ) {
            // Bound for tractability
            let mut bounded_tx = tx;
            if bounded_tx.inputs.len() > 10 {
                bounded_tx.inputs.truncate(10);
            }
            if bounded_tx.outputs.len() > 10 {
                bounded_tx.outputs.truncate(10);
            }

            let result = check_transaction(&bounded_tx).unwrap_or_else(|_| ValidationResult::Invalid("Error".to_string()));

            // Structure properties
            match result {
                ValidationResult::Valid => {
                    // Valid transactions must have non-empty inputs and outputs
                    prop_assert!(!bounded_tx.inputs.is_empty(), "Valid transaction must have inputs");
                    prop_assert!(!bounded_tx.outputs.is_empty(), "Valid transaction must have outputs");

                    // Valid transactions must respect limits
                    prop_assert!(bounded_tx.inputs.len() <= MAX_INPUTS, "Valid transaction must respect input limit");
                    prop_assert!(bounded_tx.outputs.len() <= MAX_OUTPUTS, "Valid transaction must respect output limit");

                    // Valid transactions must have valid output values
                    for output in &bounded_tx.outputs {
                        prop_assert!(output.value >= 0, "Valid transaction outputs must be non-negative");
                        prop_assert!(output.value <= MAX_MONEY, "Valid transaction outputs must not exceed max money");
                    }
                },
                ValidationResult::Invalid(_) => {
                    // Invalid transactions may violate any rule
                    // This is acceptable - we're testing the validation logic
                }
            }
        }
    }

    /// Property test: check_tx_inputs handles coinbase correctly
    proptest! {
        #[test]
        fn prop_check_tx_inputs_coinbase(
            tx in arb_transaction(),
            utxo_set in prop::collection::vec((arb_outpoint(), arb_utxo()), 0..50).prop_map(|v| v.into_iter().map(|(op, u)| (op, std::sync::Arc::new(u))).collect::<UtxoSet>()),
            height in 0u64..1000u64
        ) {
            // Bound for tractability
            let mut bounded_tx = tx;
            if bounded_tx.inputs.len() > 5 {
                bounded_tx.inputs.truncate(5);
            }
            if bounded_tx.outputs.len() > 5 {
                bounded_tx.outputs.truncate(5);
            }

            let result = check_tx_inputs(&bounded_tx, &utxo_set, height).unwrap_or((ValidationResult::Invalid("Error".to_string()), 0));

            // Coinbase property
            if is_coinbase(&bounded_tx) {
                prop_assert!(matches!(result.0, ValidationResult::Valid), "Coinbase transactions must be valid");
                prop_assert_eq!(result.1, 0, "Coinbase transactions must have zero fee");
            }
        }
    }

    /// Property test: is_coinbase correctly identifies coinbase transactions
    proptest! {
        #[test]
        fn prop_is_coinbase_correct(
            tx in arb_transaction()
        ) {
            let is_cb = is_coinbase(&tx);

            // Coinbase identification property
            if is_cb {
                prop_assert_eq!(tx.inputs.len(), 1, "Coinbase must have exactly one input");
                prop_assert_eq!(tx.inputs[0].prevout.hash, [0u8; 32], "Coinbase input must have zero hash");
                prop_assert_eq!(tx.inputs[0].prevout.index, 0xffffffffu32, "Coinbase input must have max index");
            }
        }
    }

    /// Property test: calculate_transaction_size is consistent
    proptest! {
        #[test]
        fn prop_calculate_transaction_size_consistent(
            tx in arb_transaction()
        ) {
            // Bound for tractability
            let mut bounded_tx = tx;
            if bounded_tx.inputs.len() > 10 {
                bounded_tx.inputs.truncate(10);
            }
            if bounded_tx.outputs.len() > 10 {
                bounded_tx.outputs.truncate(10);
            }

            let size = calculate_transaction_size(&bounded_tx);

            // Size calculation properties
            // Minimum: version(4) + input_count_varint(1) + output_count_varint(1) + lock_time(4) = 10 bytes
            // (Even with 0 inputs/outputs, we need varints for counts)
            prop_assert!(size >= 10, "Transaction size must be at least 10 bytes (version + varints + lock_time)");

            // Maximum: Use MAX_TX_SIZE as the upper bound (actual serialization can be larger than simplified calculation)
            // The simplified calculation was: 4 + 10*41 + 10*9 + 4 = 508
            // But actual serialization with varints and real script sizes can be larger
            prop_assert!(size <= MAX_TX_SIZE, "Transaction size must not exceed MAX_TX_SIZE ({})", MAX_TX_SIZE);

            // Size should be deterministic
            let size2 = calculate_transaction_size(&bounded_tx);
            prop_assert_eq!(size, size2, "Transaction size calculation must be deterministic");
        }
    }

    /// Property test: output value bounds are respected
    proptest! {
        #[test]
        fn prop_output_value_bounds(
            value in 0i64..(MAX_MONEY + 1000)
        ) {
            let tx = Transaction {
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [0; 32].into(), index: 0 },
                    script_sig: vec![],
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value,
                    script_pubkey: vec![],
                }].into(),
                lock_time: 0,
            };

            let result = check_transaction(&tx).unwrap_or(ValidationResult::Invalid("Error".to_string()));

            // Value bounds property
            if !(0..=MAX_MONEY).contains(&value) {
                prop_assert!(matches!(result, ValidationResult::Invalid(_)),
                    "Transactions with invalid output values must be invalid");
            } else {
                // Valid values should pass other checks too
                if !tx.inputs.is_empty() && !tx.outputs.is_empty() {
                    prop_assert!(matches!(result, ValidationResult::Valid),
                        "Transactions with valid output values should be valid");
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_check_transaction_valid() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert_eq!(check_transaction(&tx).unwrap(), ValidationResult::Valid);
    }

    #[test]
    fn test_check_transaction_empty_inputs() {
        let tx = Transaction {
            version: 1,
            inputs: vec![].into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_tx_inputs_coinbase() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0xffffffff,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 5000000000, // 50 BTC
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        let utxo_set = UtxoSet::default();
        let (result, fee) = check_tx_inputs(&tx, &utxo_set, 0).unwrap();

        assert_eq!(result, ValidationResult::Valid);
        assert_eq!(fee, 0);
    }

    // ============================================================================
    // COMPREHENSIVE TRANSACTION TESTS
    // ============================================================================

    #[test]
    fn test_check_transaction_empty_outputs() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_transaction_invalid_output_value_negative() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: -1, // Invalid negative value
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_transaction_invalid_output_value_too_large() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: MAX_MONEY + 1, // Invalid value exceeding max
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_transaction_max_output_value() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: MAX_MONEY, // Valid max value
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert_eq!(check_transaction(&tx).unwrap(), ValidationResult::Valid);
    }

    #[test]
    fn test_check_transaction_too_many_inputs() {
        let mut inputs = Vec::new();
        for i in 0..=MAX_INPUTS {
            inputs.push(TransactionInput {
                prevout: OutPoint {
                    hash: [i as u8; 32],
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            });
        }

        let tx = Transaction {
            version: 1,
            inputs: inputs.into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_transaction_max_inputs() {
        // Use a reasonable number of inputs that fits within the block weight limit.
        // Each input ≈ 41 bytes stripped. Weight limit = 4,000,000. Max stripped = 1,000,000.
        // Max inputs ≈ 1,000,000 / 41 ≈ 24,390. Use 20,000 to stay safe.
        let num_inputs = 20_000;
        let mut inputs = Vec::new();
        for i in 0..num_inputs {
            let mut hash = [0u8; 32];
            // Use unique hash for each input to avoid duplicates
            hash[0] = (i & 0xff) as u8;
            hash[1] = ((i >> 8) & 0xff) as u8;
            hash[2] = ((i >> 16) & 0xff) as u8;
            hash[3] = ((i >> 24) & 0xff) as u8;
            inputs.push(TransactionInput {
                prevout: OutPoint {
                    hash,
                    index: i as u32,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            });
        }

        let tx = Transaction {
            version: 1,
            inputs: inputs.into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert_eq!(check_transaction(&tx).unwrap(), ValidationResult::Valid);
    }

    #[test]
    fn test_check_transaction_too_many_outputs() {
        let mut outputs = Vec::new();
        for _ in 0..=MAX_OUTPUTS {
            outputs.push(TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            });
        }

        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: outputs.into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_transaction_max_outputs() {
        let mut outputs = Vec::new();
        for _ in 0..MAX_OUTPUTS {
            outputs.push(TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            });
        }

        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: outputs.into(),
            lock_time: 0,
        };

        assert_eq!(check_transaction(&tx).unwrap(), ValidationResult::Valid);
    }

    #[test]
    fn test_check_transaction_too_large() {
        // Create a transaction that will exceed MAX_BLOCK_WEIGHT / WITNESS_SCALE_FACTOR
        // MAX_BLOCK_WEIGHT is 4,000,000, so MAX_TX_SIZE is effectively 1,000,000 bytes
        // calculate_transaction_size now uses actual serialization, so we need to create
        // a transaction with large scripts to exceed the size limit while staying within input limits
        use crate::constants::MAX_INPUTS;
        let mut inputs = Vec::new();
        // Use MAX_INPUTS inputs with large scripts to exceed size limit
        // Each input: 32 (hash) + 4 (index) + varint(script_len) + script + 4 (sequence)
        // With 1000 inputs and ~1000 byte scripts each, we get ~1MB+ transaction
        for i in 0..MAX_INPUTS {
            inputs.push(TransactionInput {
                prevout: OutPoint {
                    hash: [i as u8; 32],
                    index: 0,
                },
                script_sig: vec![0u8; 1000], // Large script to increase size (1000 bytes each)
                sequence: 0xffffffff,
            });
        }

        let tx = Transaction {
            version: 1,
            inputs: inputs.into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        assert!(matches!(
            check_transaction(&tx).unwrap(),
            ValidationResult::Invalid(_)
        ));
    }

    #[test]
    fn test_check_tx_inputs_regular_transaction() {
        let mut utxo_set = UtxoSet::default();

        // Add UTXO to the set
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000000000, // 10 BTC
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };
        utxo_set.insert(outpoint, std::sync::Arc::new(utxo));

        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [1; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 900000000, // 9 BTC output
                script_pubkey: vec![],
            }]
            .into(),
            lock_time: 0,
        };

        let (result, fee) = check_tx_inputs(&tx, &utxo_set, 0).unwrap();

        assert_eq!(result, ValidationResult::Valid);
        assert_eq!(fee, 100000000); // 1 BTC fee
    }

    #[test]
    fn test_check_tx_inputs_missing_utxo() {
        let utxo_set = UtxoSet::default(); // Empty UTXO set

        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [1; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 100000000,
                script_pubkey: vec![],
            }]
            .into(),
            lock_time: 0,
        };

        let (result, fee) = check_tx_inputs(&tx, &utxo_set, 0).unwrap();

        assert!(matches!(result, ValidationResult::Invalid(_)));
        assert_eq!(fee, 0);
    }

    #[test]
    fn test_check_tx_inputs_insufficient_funds() {
        let mut utxo_set = UtxoSet::default();

        // Add UTXO with insufficient value
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 100000000, // 1 BTC
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };
        utxo_set.insert(outpoint, std::sync::Arc::new(utxo));

        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [1; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 200000000, // 2 BTC output (more than input)
                script_pubkey: vec![],
            }]
            .into(),
            lock_time: 0,
        };

        let (result, fee) = check_tx_inputs(&tx, &utxo_set, 0).unwrap();

        assert!(matches!(result, ValidationResult::Invalid(_)));
        assert_eq!(fee, 0);
    }

    #[test]
    fn test_check_tx_inputs_multiple_inputs() {
        let mut utxo_set = UtxoSet::default();

        // Add two UTXOs
        let outpoint1 = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo1 = UTXO {
            value: 500000000, // 5 BTC
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };
        utxo_set.insert(outpoint1, std::sync::Arc::new(utxo1));

        let outpoint2 = OutPoint {
            hash: [2; 32],
            index: 0,
        };
        let utxo2 = UTXO {
            value: 300000000, // 3 BTC
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };
        utxo_set.insert(outpoint2, std::sync::Arc::new(utxo2));

        let tx = Transaction {
            version: 1,
            inputs: vec![
                TransactionInput {
                    prevout: OutPoint {
                        hash: [1; 32].into(),
                        index: 0,
                    },
                    script_sig: vec![],
                    sequence: 0xffffffff,
                },
                TransactionInput {
                    prevout: OutPoint {
                        hash: [2; 32],
                        index: 0,
                    },
                    script_sig: vec![],
                    sequence: 0xffffffff,
                },
            ]
            .into(),
            outputs: vec![TransactionOutput {
                value: 700000000, // 7 BTC output
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        let (result, fee) = check_tx_inputs(&tx, &utxo_set, 0).unwrap();

        assert_eq!(result, ValidationResult::Valid);
        assert_eq!(fee, 100000000); // 1 BTC fee (8 BTC input - 7 BTC output)
    }

    #[test]
    fn test_is_coinbase_edge_cases() {
        // Valid coinbase
        let valid_coinbase = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0xffffffff,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(is_coinbase(&valid_coinbase));

        // Wrong hash
        let wrong_hash = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [1; 32].into(),
                    index: 0xffffffff,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(!is_coinbase(&wrong_hash));

        // Wrong index
        let wrong_index = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(!is_coinbase(&wrong_index));

        // Multiple inputs
        let multiple_inputs = Transaction {
            version: 1,
            inputs: vec![
                TransactionInput {
                    prevout: OutPoint {
                        hash: [0; 32].into(),
                        index: 0xffffffff,
                    },
                    script_sig: vec![],
                    sequence: 0xffffffff,
                },
                TransactionInput {
                    prevout: OutPoint {
                        hash: [1; 32],
                        index: 0,
                    },
                    script_sig: vec![],
                    sequence: 0xffffffff,
                },
            ]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(!is_coinbase(&multiple_inputs));

        // No inputs
        let no_inputs = Transaction {
            version: 1,
            inputs: vec![].into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(!is_coinbase(&no_inputs));
    }

    #[test]
    fn test_calculate_transaction_size() {
        let tx = Transaction {
            version: 1,
            inputs: vec![
                TransactionInput {
                    prevout: OutPoint {
                        hash: [0; 32].into(),
                        index: 0,
                    },
                    script_sig: vec![1, 2, 3],
                    sequence: 0xffffffff,
                },
                TransactionInput {
                    prevout: OutPoint {
                        hash: [1; 32],
                        index: 1,
                    },
                    script_sig: vec![4, 5, 6],
                    sequence: 0xffffffff,
                },
            ]
            .into(),
            outputs: vec![
                TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![7, 8, 9].into(),
                },
                TransactionOutput {
                    value: 2000,
                    script_pubkey: vec![10, 11, 12],
                },
            ]
            .into(),
            lock_time: 12345,
        };

        let size = calculate_transaction_size(&tx);
        // Expected actual serialized size:
        // 4 (version) + 1 (input_count varint) +
        // 2 * (32 + 4 + 1 + 3 + 4) (inputs: hash + index + script_len_varint + script + sequence) +
        // 1 (output_count varint) +
        // 2 * (8 + 1 + 3) (outputs: value + script_len_varint + script) +
        // 4 (lock_time) = 4 + 1 + 88 + 1 + 24 + 4 = 122
        // This matches actual serialization (not simplified calculation)
        assert_eq!(size, 122);
    }
}