blvm-node 0.1.2

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
//! Raw Transaction RPC Methods
//!
//! Implements raw transaction-related JSON-RPC methods:
//! - sendrawtransaction
//! - testmempoolaccept
//! - decoderawtransaction
//! - getrawtransaction (enhanced)
//! - gettxout
//! - gettxoutproof
//! - verifytxoutproof

use crate::config::RequestTimeoutConfig;
use crate::node::mempool::MempoolManager;
use crate::node::metrics::MetricsCollector;
use crate::node::performance::{OperationType, PerformanceProfiler, PerformanceTimer};
use crate::rpc::errors::{RpcError, RpcErrorCode, RpcResult};
use crate::rpc::params::{
    param_array, param_bool_default, param_f64, param_str, param_u64_default,
};
use crate::storage::Storage;
use crate::utils::{storage_timeout_from_config, with_custom_timeout};
use hex;
use serde_json::{json, Value};
use std::result::Result;
use std::sync::Arc;
use std::time::Instant;
use tracing::{debug, warn};

/// Decode a Bitcoin address to `script_pubkey` (Bech32/Bech32m and legacy Base58Check).
pub(crate) fn address_string_to_script_pubkey(address: &str) -> Result<Vec<u8>, RpcError> {
    use blvm_protocol::address::BitcoinAddress;
    use blvm_protocol::opcodes::{
        OP_CHECKSIG, OP_DUP, OP_EQUAL, OP_EQUALVERIFY, OP_HASH160, PUSH_20_BYTES,
    };

    if let Ok(addr) = BitcoinAddress::decode(address) {
        match (addr.witness_version, addr.witness_program.len()) {
            (0, 20) | (0, 32) => {
                let mut script = vec![0x00];
                script.extend_from_slice(&addr.witness_program);
                Ok(script)
            }
            (1, 32) => {
                let mut script = vec![blvm_protocol::opcodes::OP_1];
                script.extend_from_slice(&addr.witness_program);
                Ok(script)
            }
            _ => Err(RpcError::invalid_address_format(
                address,
                Some("Unsupported witness version or program length"),
                None,
            )),
        }
    } else {
        let decoded = match bs58::decode(address).with_check(None).into_vec() {
            Ok(v) => v,
            Err(_) => {
                return Err(RpcError::invalid_address_format(
                    address,
                    Some("Invalid address: not Bech32/Bech32m and not valid Base58Check"),
                    None,
                ))
            }
        };
        if decoded.len() != 21 {
            return Err(RpcError::invalid_address_format(
                address,
                Some("Base58Check address must decode to 21 bytes (version + 20-byte hash)"),
                None,
            ));
        }
        let version = decoded[0];
        let hash: &[u8; 20] = decoded[1..21]
            .try_into()
            .expect("slice length checked above");
        match version {
            0x00 => {
                let mut script = vec![OP_DUP, OP_HASH160, PUSH_20_BYTES];
                script.extend_from_slice(hash);
                script.extend_from_slice(&[OP_EQUALVERIFY, OP_CHECKSIG]);
                Ok(script)
            }
            0x05 => {
                let mut script = vec![OP_HASH160, PUSH_20_BYTES];
                script.extend_from_slice(hash);
                script.push(OP_EQUAL);
                Ok(script)
            }
            _ => Err(RpcError::invalid_address_format(
                address,
                Some("Base58Check version must be 0x00 (P2PKH) or 0x05 (P2SH)"),
                None,
            )),
        }
    }
}

/// Raw Transaction RPC methods
pub struct RawTxRpc {
    storage: Option<Arc<Storage>>,
    mempool: Option<Arc<MempoolManager>>,
    metrics: Option<Arc<MetricsCollector>>,
    profiler: Option<Arc<PerformanceProfiler>>,
    /// Request timeout config (storage/network/rpc timeouts)
    request_timeouts: Option<RequestTimeoutConfig>,
}

impl RawTxRpc {
    /// Create a new raw transaction RPC handler
    pub fn new() -> Self {
        Self {
            storage: None,
            mempool: None,
            metrics: None,
            profiler: None,
            request_timeouts: None,
        }
    }

    /// Create with dependencies
    pub fn with_dependencies(
        storage: Arc<Storage>,
        mempool: Arc<MempoolManager>,
        metrics: Option<Arc<MetricsCollector>>,
        profiler: Option<Arc<PerformanceProfiler>>,
    ) -> Self {
        Self {
            storage: Some(storage),
            mempool: Some(mempool),
            metrics,
            profiler,
            request_timeouts: None,
        }
    }

    /// Set request timeout config (storage/network/rpc timeouts from config)
    pub fn with_request_timeouts(mut self, config: Option<RequestTimeoutConfig>) -> Self {
        self.request_timeouts = config;
        self
    }

    fn storage_timeout(&self) -> std::time::Duration {
        storage_timeout_from_config(self.request_timeouts.as_ref())
    }

    /// Send a raw transaction to the network
    ///
    /// Params: ["hexstring", maxfeerate (optional), allowhighfees (optional)]
    /// - hexstring: Raw transaction hex
    /// - maxfeerate: Maximum fee rate in BTC per kvB (optional, default: no limit)
    /// - allowhighfees: Allow transactions with high fees (optional, default: false)
    pub async fn sendrawtransaction(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: sendrawtransaction");

        // Validate hex string parameter with length limits
        use crate::rpc::validation::validate_hex_string_param;
        let hex_string = validate_hex_string_param(
            params,
            0,
            "hexstring",
            Some(crate::rpc::validation::MAX_HEX_STRING_LENGTH),
        )?;

        // Parse optional parameters
        let maxfeerate_btc_per_kvb: Option<f64> = param_f64(params, 1)
            .or_else(|| param_str(params, 1).and_then(|s| s.parse::<f64>().ok()));

        let allowhighfees: bool = param_bool_default(params, 2, false);

        let tx_bytes = hex::decode(&hex_string).map_err(|e| {
            RpcError::invalid_params_with_fields(
                format!("Invalid hex string: {e}"),
                vec![("hexstring", &format!("Invalid hex encoding: {e}"))],
                Some(json!([
                    "Hex string must contain only characters 0-9, a-f, A-F",
                    "Ensure the hex string is complete (even number of characters)"
                ])),
            )
        })?;

        if let (Some(storage), Some(mempool)) = (self.storage.as_ref(), self.mempool.as_ref()) {
            use blvm_protocol::serialization::transaction::deserialize_transaction;
            let tx = deserialize_transaction(&tx_bytes).map_err(|e| {
                RpcError::invalid_params_with_fields(
                    format!("Failed to parse transaction: {e}"),
                    vec![(
                        "hexstring",
                        &format!("Transaction deserialization failed: {e}"),
                    )],
                    Some(json!([
                        "Ensure the transaction hex is valid and complete",
                        "Check that the transaction format matches Bitcoin transaction structure"
                    ])),
                )
            })?;

            use blvm_protocol::block::calculate_tx_id;
            let txid = calculate_tx_id(&tx);
            let txid_hex = hex::encode(txid);

            // Check if already in mempool
            if mempool.get_transaction(&txid).is_some() {
                return Err(RpcError::tx_already_in_mempool(&txid_hex));
            }

            // Check if in chain
            if storage
                .transactions()
                .has_transaction(&txid)
                .unwrap_or(false)
            {
                return Err(RpcError::with_data(
                    RpcErrorCode::TxAlreadyInChain,
                    format!("Transaction already in chain: {txid_hex}"),
                    json!({
                        "txid": txid_hex,
                        "reason": "already_confirmed",
                        "suggestions": [
                            "Transaction has already been confirmed in a block",
                            "Use getrawtransaction to retrieve the transaction from the blockchain"
                        ]
                    }),
                ));
            }

            // Validate transaction using consensus layer
            let _timer = self
                .profiler
                .as_ref()
                .map(|p| PerformanceTimer::start(Arc::clone(p), OperationType::TxValidation));
            let validation_start = Instant::now();
            use blvm_protocol::ConsensusProof;
            let consensus = ConsensusProof::new();
            match consensus.validate_transaction(&tx) {
                Ok(blvm_protocol::ValidationResult::Valid) => {
                    let validation_time = validation_start.elapsed();
                    // Timer will record duration when dropped

                    // Update metrics
                    if let Some(ref metrics) = self.metrics {
                        metrics.update_performance(|m| {
                            let time_ms = validation_time.as_secs_f64() * 1000.0;
                            // Update average transaction validation time (exponential moving average)
                            m.avg_tx_validation_time_ms =
                                (m.avg_tx_validation_time_ms * 0.9) + (time_ms * 0.1);
                            // Update transactions per second
                            if validation_time.as_secs_f64() > 0.0 {
                                m.transactions_per_second = 1.0 / validation_time.as_secs_f64();
                            }
                        });
                    }

                    // Transaction structure is valid, now check inputs against UTXO set
                    let utxo_set = storage.utxos().get_all_utxos().map_err(|e| {
                        RpcError::internal_error(format!("Failed to get UTXO set: {e}"))
                    })?;

                    // Check if all inputs exist in UTXO set
                    for input in &tx.inputs {
                        if !utxo_set.contains_key(&input.prevout) {
                            let prevout_str = format!(
                                "{}:{}",
                                hex::encode(input.prevout.hash),
                                input.prevout.index
                            );
                            return Err(RpcError::with_data(
                                RpcErrorCode::TxMissingInputs,
                                format!("Input {prevout_str} not found in UTXO set"),
                                json!({
                                    "prevout": prevout_str,
                                    "txid": txid_hex,
                                    "reason": "missing_input",
                                    "suggestions": [
                                        "The referenced output does not exist or has already been spent",
                                        "Ensure the transaction is spending valid UTXOs",
                                        "Check that the previous transaction is confirmed"
                                    ]
                                }),
                            ));
                        }
                    }

                    // Calculate transaction fee and fee rate for maxfeerate check
                    let fee_satoshis = mempool.calculate_transaction_fee(&tx, &utxo_set);

                    // Calculate transaction size and vsize
                    use blvm_protocol::serialization::transaction::serialize_transaction;
                    let base_size = serialize_transaction(&tx).len() as u64;
                    // For non-SegWit transactions, weight = 4 * size, vsize = size
                    // For SegWit, we'd need witness data, but for fee rate check we can use base size
                    // This is a simplification - in production, we'd need full witness data
                    let vsize = base_size; // Simplified: assume non-SegWit for now

                    // Calculate fee rate in BTC per kvB
                    let fee_rate_btc_per_kvb = if vsize > 0 {
                        (fee_satoshis as f64 / vsize as f64) * 1000.0 / 100_000_000.0
                    } else {
                        0.0
                    };

                    // Check maxfeerate if provided and allowhighfees is false
                    if let Some(max_feerate) = maxfeerate_btc_per_kvb {
                        if !allowhighfees && fee_rate_btc_per_kvb > max_feerate {
                            return Err(RpcError::with_data(
                                RpcErrorCode::TxRejected,
                                format!(
                                    "Fee rate {fee_rate_btc_per_kvb} BTC/kvB exceeds maximum allowed {max_feerate} BTC/kvB"
                                ),
                                json!({
                                    "txid": txid_hex,
                                    "fee_rate": fee_rate_btc_per_kvb,
                                    "max_feerate": max_feerate,
                                    "reason": "fee_rate_too_high",
                                    "suggestions": [
                                        "Reduce the transaction fee",
                                        "Use allowhighfees=true to override this check",
                                        "Or increase the maxfeerate parameter"
                                    ]
                                }),
                            ));
                        }
                    }

                    // Add to mempool
                    // Note: add_transaction requires &mut self, but we have Arc<MempoolManager>
                    // In production, this would need to use interior mutability (Mutex/RwLock)
                    // For now, we'll skip adding to mempool as it requires mutable access
                    debug!(
                        "Transaction validated but not added to mempool (requires mutable access)"
                    );
                }
                Ok(blvm_protocol::ValidationResult::Invalid(reason)) => {
                    return Err(RpcError::tx_rejected_with_context(
                        format!("Transaction validation failed: {reason}"),
                        Some(&txid_hex),
                        Some("validation_failed"),
                        Some(json!({
                            "validation_reason": reason,
                            "suggestions": [
                                "Review the transaction structure and ensure it follows Bitcoin protocol rules",
                                "Check that all inputs are valid and outputs are properly formatted",
                                "Verify that the transaction size and weight are within limits"
                            ]
                        })),
                    ));
                }
                Err(e) => {
                    return Err(RpcError::internal_error(format!(
                        "Transaction validation error: {e}"
                    )));
                }
            }

            Ok(json!(hex::encode(txid)))
        } else {
            Err(RpcError::invalid_params(
                "RPC not initialized with dependencies",
            ))
        }
    }

    /// Test if a raw transaction would be accepted to the mempool
    ///
    /// Params: [["hexstring", ...], maxfeerate (optional)] or ["hexstring", maxfeerate (optional)]
    /// Supports both single transaction and package validation
    pub async fn testmempoolaccept(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: testmempoolaccept");

        // Handle both array of transactions (package) and single transaction
        let rawtxs = if let Some(arr) = param_array(params, 0) {
            // Array of hex strings (package validation)
            arr.iter()
                .map(|v| {
                    v.as_str().ok_or_else(|| {
                        RpcError::invalid_params(
                            "First parameter must be array of hex strings or single hex string",
                        )
                    })
                })
                .collect::<Result<Vec<&str>, _>>()?
        } else if let Some(hex_str) = param_str(params, 0) {
            // Single hex string
            vec![hex_str]
        } else {
            return Err(RpcError::missing_parameter(
                "rawtxs",
                Some("array of hex strings or single hex string"),
            ));
        };

        // Parse all transactions with witness data
        let mut transactions = Vec::new();
        let mut all_witnesses = Vec::new(); // Vec<Vec<Witness>> - one Vec<Witness> per transaction

        for hex_string in &rawtxs {
            let tx_bytes = hex::decode(hex_string).map_err(|e| {
                RpcError::invalid_params_with_fields(
                    format!("Invalid hex string: {e}"),
                    vec![("hexstring", &format!("Invalid hex encoding: {e}"))],
                    Some(json!([
                        "Hex string must contain only characters 0-9, a-f, A-F",
                        "Ensure the hex string is complete (even number of characters)"
                    ])),
                )
            })?;

            // Parse transaction and witness data (witnesses is Vec<Witness> - one per input)
            let (tx, witnesses) = Self::deserialize_transaction_with_witness(&tx_bytes)?;
            transactions.push(tx);
            all_witnesses.push(witnesses);
        }

        // Package validation: check for conflicts and dependencies
        let package_error = if transactions.len() > 1 {
            Self::validate_package(&transactions)
        } else {
            None
        };

        // Process each transaction
        let mut results = Vec::new();

        for (tx, tx_witnesses) in transactions.iter().zip(all_witnesses.iter()) {
            // If package validation failed, mark all transactions as failed
            if let Some(ref pkg_err) = package_error {
                results.push(json!({
                    "txid": hex::encode(blvm_protocol::block::calculate_tx_id(tx)),
                    "wtxid": Self::calculate_wtxid(tx, tx_witnesses),
                    "package-error": pkg_err,
                    "allowed": false
                }));
                continue;
            }

            // Calculate txid and wtxid
            use blvm_protocol::block::calculate_tx_id;
            let txid = calculate_tx_id(tx);
            let txid_hex = hex::encode(txid);
            let wtxid_hex = Self::calculate_wtxid(tx, tx_witnesses);

            // Validate transaction using consensus layer
            use blvm_protocol::ConsensusProof;
            let consensus = ConsensusProof::new();
            let validation_result = consensus.validate_transaction(tx);

            let allowed = matches!(
                validation_result,
                Ok(blvm_protocol::ValidationResult::Valid)
            );
            let reject_reason = if !allowed {
                match validation_result {
                    Ok(blvm_protocol::ValidationResult::Invalid(reason)) => Some(reason),
                    Err(e) => Some(format!("Validation error: {e}")),
                    _ => None,
                }
            } else {
                None
            };

            // Calculate transaction size and weight with witness
            use blvm_protocol::serialization::transaction::serialize_transaction;
            let base_size = serialize_transaction(tx).len() as u64;
            // Calculate total witness size (sum of all witness stacks for all inputs)
            let witness_size: u64 = tx_witnesses
                .iter()
                .map(|witness_stack| witness_stack.iter().map(|w| w.len() as u64).sum::<u64>())
                .sum();
            let total_size = base_size + witness_size;

            // Calculate weight using BIP141 formula: weight = 4 * base_size + total_size
            let weight = 4 * base_size + total_size;

            // Calculate vsize using proper BIP141 formula: vsize = ceil(weight / 4)
            use blvm_protocol::witness::weight_to_vsize;
            let vsize = weight_to_vsize(weight) as usize;

            // Calculate fee using mempool manager if available
            let fee_satoshis = if let Some(ref mempool) = self.mempool {
                if let Some(ref storage) = self.storage {
                    let utxo_set = storage.utxos().get_all_utxos().unwrap_or_default();
                    mempool.calculate_transaction_fee(tx, &utxo_set)
                } else {
                    1000 // Default 1000 satoshis if no storage
                }
            } else {
                1000 // Default 1000 satoshis if no mempool
            };

            let fee_btc = fee_satoshis as f64 / 100_000_000.0; // Convert to BTC

            // Calculate effective fee rate (satoshis per kvB)
            // effective-feerate = (fee in satoshis) / (vsize in bytes) * 1000
            let effective_feerate_sat_per_kvb = if vsize > 0 {
                (fee_satoshis as f64 / vsize as f64) * 1000.0
            } else {
                0.0
            };
            let effective_feerate_btc_per_kvb = effective_feerate_sat_per_kvb / 100_000_000.0;

            // Get effective-includes (ancestor wtxids from mempool)
            let effective_includes = if allowed && transactions.len() == 1 {
                // Only calculate for single transaction (not in package)
                Self::get_effective_includes(&txid, self.mempool.as_ref())
            } else {
                Vec::<String>::new()
            };

            // Build fees object (standard format)
            let mut fees_obj = json!({
                "base": fee_btc
            });

            // Add effective-feerate if transaction is allowed
            if allowed {
                fees_obj.as_object_mut().unwrap().insert(
                    "effective-feerate".to_string(),
                    json!(effective_feerate_btc_per_kvb),
                );
                // Add effective-includes (wtxids of ancestor transactions as hex strings)
                fees_obj
                    .as_object_mut()
                    .unwrap()
                    .insert("effective-includes".to_string(), json!(effective_includes));
            }

            // Build result object
            let mut result_obj = json!({
                "txid": txid_hex,
                "wtxid": wtxid_hex,
                "allowed": allowed,
                "vsize": vsize,
                "fees": fees_obj,
            });

            // Add reject-reason only if transaction is not allowed
            if !allowed {
                result_obj
                    .as_object_mut()
                    .unwrap()
                    .insert("reject-reason".to_string(), json!(reject_reason));
            }

            results.push(result_obj);
        }

        Ok(json!(results))
    }

    /// Deserialize transaction with witness data from Bitcoin wire format
    /// Returns (transaction, all_witnesses) tuple where all_witnesses is Vec<Witness> (one per input)
    fn deserialize_transaction_with_witness(
        data: &[u8],
    ) -> Result<
        (
            blvm_protocol::Transaction,
            Vec<blvm_protocol::segwit::Witness>,
        ),
        RpcError,
    > {
        use blvm_protocol::serialization::transaction::deserialize_transaction_with_witness as parse;

        let (tx, witnesses, _consumed) = parse(data).map_err(|e| {
            RpcError::invalid_params_with_fields(
                format!("Failed to parse transaction: {e}"),
                vec![(
                    "hexstring",
                    &format!("Transaction deserialization failed: {e}"),
                )],
                Some(json!([
                    "Ensure the transaction hex is valid and complete",
                    "Check that the transaction format matches Bitcoin transaction structure"
                ])),
            )
        })?;

        // Ensure we have a witness vec entry for every input (pad with empty stacks if necessary)
        let mut witnesses = witnesses;
        while witnesses.len() < tx.inputs.len() {
            witnesses.push(blvm_protocol::segwit::Witness::new());
        }

        Ok((tx, witnesses))
    }

    /// Calculate wtxid (witness transaction hash)
    /// For non-SegWit: wtxid == txid
    /// For SegWit: wtxid = SHA256(SHA256(tx_with_witness))
    /// witnesses: Vec<Witness> - one witness stack per input
    fn calculate_wtxid(
        tx: &blvm_protocol::Transaction,
        witnesses: &[blvm_protocol::segwit::Witness],
    ) -> String {
        use blvm_protocol::block::calculate_tx_id;
        let txid = calculate_tx_id(tx);

        // Check if any witness has data
        let has_witness = witnesses.iter().any(|w| !w.is_empty());

        // If no witness data, wtxid == txid
        if !has_witness {
            return hex::encode(txid);
        }

        // For SegWit transactions, wtxid is hash of transaction WITH witness
        // Serialize: version + marker(0x00) + flag(0x01) + inputs + outputs + locktime + witness_data
        use blvm_protocol::serialization::varint::encode_varint;
        use sha2::{Digest, Sha256};

        let mut serialized = Vec::new();

        // Version (4 bytes)
        serialized.extend_from_slice(&(tx.version as u32).to_le_bytes());

        // SegWit marker and flag
        serialized.push(0x00);
        serialized.push(0x01);

        // Input count
        serialized.extend_from_slice(&encode_varint(tx.inputs.len() as u64));

        // Inputs (non-witness serialization)
        for input in &tx.inputs {
            serialized.extend_from_slice(&input.prevout.hash);
            serialized.extend_from_slice(&input.prevout.index.to_le_bytes());
            serialized.extend_from_slice(&encode_varint(input.script_sig.len() as u64));
            serialized.extend_from_slice(&input.script_sig);
            serialized.extend_from_slice(&(input.sequence as u32).to_le_bytes());
        }

        // Output count
        serialized.extend_from_slice(&encode_varint(tx.outputs.len() as u64));

        // Outputs
        for output in &tx.outputs {
            serialized.extend_from_slice(&(output.value as u64).to_le_bytes());
            serialized.extend_from_slice(&encode_varint(output.script_pubkey.len() as u64));
            serialized.extend_from_slice(&output.script_pubkey);
        }

        // Lock time
        serialized.extend_from_slice(&(tx.lock_time as u32).to_le_bytes());

        // Witness data: one witness stack per input
        for witness_stack in witnesses {
            // Witness stack count (number of elements)
            serialized.extend_from_slice(&encode_varint(witness_stack.len() as u64));
            // Each witness element
            for element in witness_stack {
                serialized.extend_from_slice(&encode_varint(element.len() as u64));
                serialized.extend_from_slice(element);
            }
        }

        // Double SHA256
        let first_hash = Sha256::digest(&serialized);
        let second_hash = Sha256::digest(first_hash);
        hex::encode(second_hash)
    }

    /// Validate package (multiple transactions)
    /// Returns error string if package is invalid
    fn validate_package(transactions: &[blvm_protocol::Transaction]) -> Option<String> {
        // Check for duplicate transactions
        use blvm_protocol::block::calculate_tx_id;
        let mut txids = std::collections::HashSet::new();
        for tx in transactions {
            let txid = calculate_tx_id(tx);
            if !txids.insert(txid) {
                return Some("package contains duplicate transactions".to_string());
            }
        }

        // Check for conflicts (transactions spending same outputs)
        let mut spent_outputs = std::collections::HashSet::new();
        for tx in transactions {
            for input in &tx.inputs {
                if !spent_outputs.insert((input.prevout.hash, input.prevout.index)) {
                    return Some("package contains conflicting transactions".to_string());
                }
            }
        }

        None
    }

    /// Get effective-includes (ancestor wtxids from mempool)
    /// Returns wtxids (as hex strings) of ancestor transactions used in fee calculation
    fn get_effective_includes(
        txid: &blvm_protocol::Hash,
        mempool: Option<&Arc<MempoolManager>>,
    ) -> Vec<String> {
        let mut includes = Vec::new();

        if let Some(mempool) = mempool {
            // Get ancestors from mempool
            use blvm_protocol::block::calculate_tx_id;
            if let Some(tx) = mempool.get_transaction(txid) {
                // Find ancestor transactions (transactions that this tx spends from)
                let ancestor_txids: Vec<blvm_protocol::Hash> = mempool
                    .get_transactions()
                    .iter()
                    .filter(|ancestor_tx| {
                        let ancestor_hash = calculate_tx_id(ancestor_tx);
                        tx.inputs
                            .iter()
                            .any(|input| input.prevout.hash == ancestor_hash)
                    })
                    .map(calculate_tx_id)
                    .collect();

                // Convert to wtxids (hex strings)
                // For non-SegWit transactions, txid equals wtxid (by definition)
                // For SegWit transactions, wtxid would require witness data storage in mempool
                includes = ancestor_txids.iter().map(hex::encode).collect();
            }
        }

        includes
    }

    /// Decode a raw transaction
    ///
    /// Params: ["hexstring", iswitness (optional, default: try both)]
    pub async fn decoderawtransaction(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: decoderawtransaction");

        // Validate hex string parameter with length limits
        use crate::rpc::validation::validate_hex_string_param;
        let hex_string = validate_hex_string_param(
            params,
            0,
            "hexstring",
            Some(crate::rpc::validation::MAX_HEX_STRING_LENGTH),
        )?;

        let tx_bytes = hex::decode(&hex_string)
            .map_err(|e| RpcError::invalid_params(format!("Invalid hex string: {e}")))?;

        use blvm_protocol::serialization::transaction::deserialize_transaction;
        let tx = deserialize_transaction(&tx_bytes)
            .map_err(|e| RpcError::invalid_params(format!("Failed to parse transaction: {e}")))?;

        use blvm_protocol::block::calculate_tx_id;
        let txid = calculate_tx_id(&tx);
        let txid_hex = hex::encode(txid);
        let size = tx_bytes.len();

        // Pre-allocate and build vin
        let mut vin = Vec::with_capacity(tx.inputs.len());
        for input in &tx.inputs {
            vin.push(json!({
                "txid": hex::encode(input.prevout.hash),
                "vout": input.prevout.index,
                "scriptSig": {
                    "asm": "",
                    "hex": hex::encode(&input.script_sig)
                },
                "sequence": input.sequence
            }));
        }

        // Pre-allocate and build vout
        let mut vout = Vec::with_capacity(tx.outputs.len());
        for (i, output) in tx.outputs.iter().enumerate() {
            vout.push(json!({
                "value": output.value as f64 / 100_000_000.0,
                "n": i,
                "scriptPubKey": {
                    "asm": "",
                    "hex": hex::encode(&output.script_pubkey),
                    "reqSigs": 1,
                    "type": "pubkeyhash",
                    "addresses": []
                }
            }));
        }

        Ok(json!({
            "txid": txid_hex.clone(),
            "hash": txid_hex,
            "version": tx.version,
            "size": size,
            "vsize": size,
            "weight": size * 4, // Simplified
            "locktime": tx.lock_time,
            "vin": vin,
            "vout": vout,
            "hex": hex_string
        }))
    }

    /// Serialize transaction with witness data (SegWit format)
    /// Returns hex string with witness data if witnesses provided, otherwise non-witness format
    fn serialize_transaction_with_witness(
        tx: &blvm_protocol::Transaction,
        witnesses: Option<&[blvm_protocol::segwit::Witness]>,
    ) -> String {
        use blvm_protocol::serialization::transaction::serialize_transaction;
        use blvm_protocol::serialization::varint::encode_varint;

        // Check if we have witness data
        let has_witness = witnesses
            .map(|w| w.iter().any(|witness_stack| !witness_stack.is_empty()))
            .unwrap_or(false);

        if !has_witness {
            // Non-SegWit: return standard serialization
            return hex::encode(serialize_transaction(tx));
        }

        // SegWit: serialize with witness marker and data
        let witnesses = witnesses.unwrap();
        let mut serialized = Vec::new();

        // Version (4 bytes, little-endian)
        serialized.extend_from_slice(&(tx.version as i32).to_le_bytes());

        // SegWit marker and flag
        serialized.push(0x00);
        serialized.push(0x01);

        // Input count
        serialized.extend_from_slice(&encode_varint(tx.inputs.len() as u64));

        // Inputs (non-witness serialization)
        for input in &tx.inputs {
            serialized.extend_from_slice(&input.prevout.hash);
            serialized.extend_from_slice(&input.prevout.index.to_le_bytes());
            serialized.extend_from_slice(&encode_varint(input.script_sig.len() as u64));
            serialized.extend_from_slice(&input.script_sig);
            serialized.extend_from_slice(&(input.sequence as u32).to_le_bytes());
        }

        // Output count
        serialized.extend_from_slice(&encode_varint(tx.outputs.len() as u64));

        // Outputs
        for output in &tx.outputs {
            serialized.extend_from_slice(&(output.value as u64).to_le_bytes());
            serialized.extend_from_slice(&encode_varint(output.script_pubkey.len() as u64));
            serialized.extend_from_slice(&output.script_pubkey);
        }

        // Lock time
        serialized.extend_from_slice(&(tx.lock_time as u32).to_le_bytes());

        // Witness data: one witness stack per input
        for witness_stack in witnesses {
            // Witness stack count (number of elements)
            serialized.extend_from_slice(&encode_varint(witness_stack.len() as u64));
            // Each witness element
            for element in witness_stack {
                serialized.extend_from_slice(&encode_varint(element.len() as u64));
                serialized.extend_from_slice(element);
            }
        }

        hex::encode(serialized)
    }

    /// Calculate transaction size and weight for SegWit transactions
    /// Returns (base_size, total_size, weight, vsize)
    fn calculate_segwit_sizes(
        tx: &blvm_protocol::Transaction,
        witnesses: Option<&[blvm_protocol::segwit::Witness]>,
    ) -> (usize, usize, u64, usize) {
        use blvm_protocol::serialization::transaction::serialize_transaction;
        use blvm_protocol::witness::{calculate_transaction_weight_segwit, weight_to_vsize};

        // Base size (without witness)
        let base_size = serialize_transaction(tx).len();

        // Check if we have witness data
        let has_witness = witnesses
            .map(|w| w.iter().any(|witness_stack| !witness_stack.is_empty()))
            .unwrap_or(false);

        if !has_witness {
            // Non-SegWit: base_size == total_size
            let total_size = base_size;
            let weight = (base_size * 4) as u64;
            let vsize = base_size;
            return (base_size, total_size, weight, vsize);
        }

        // SegWit: calculate total size with witness
        // Serialize with witness to get total size
        let tx_hex_with_witness = Self::serialize_transaction_with_witness(tx, witnesses);
        let total_size = tx_hex_with_witness.len() / 2; // Hex string length / 2 = bytes

        // Calculate weight: 4 * base_size + total_size
        let weight = calculate_transaction_weight_segwit(base_size as u64, total_size as u64);

        // Calculate vsize: ceil(weight / 4)
        let vsize = weight_to_vsize(weight) as usize;

        (base_size, total_size, weight, vsize)
    }

    /// Get raw transaction by txid
    ///
    /// Params: ["txid", verbose (optional, default: false), blockhash (optional)]
    pub async fn getrawtransaction(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: getrawtransaction");

        let txid = params
            .get(0)
            .and_then(|p| p.as_str())
            .ok_or_else(|| RpcError::invalid_params("Missing txid parameter"))?;

        let verbose = param_bool_default(params, 1, false);

        let txid_bytes = hex::decode(txid)
            .map_err(|e| RpcError::invalid_params(format!("Invalid txid: {e}")))?;
        if txid_bytes.len() != 32 {
            return Err(RpcError::invalid_params("Invalid txid length"));
        }
        let mut txid_array = [0u8; 32];
        txid_array.copy_from_slice(&txid_bytes);

        if let Some(ref storage) = self.storage {
            if let Ok(Some(tx)) = storage.transactions().get_transaction(&txid_array) {
                use blvm_protocol::block::calculate_tx_id;
                let calculated_txid = calculate_tx_id(&tx);
                let txid_hex = hex::encode(calculated_txid);

                // Try to get witness data if available (from raw block data or mempool)
                // For now, we'll assume no witness data is available from storage
                // In a full implementation, we'd retrieve witness data from block storage
                let witnesses: Option<Vec<blvm_protocol::segwit::Witness>> = None;

                // Calculate wtxid
                let wtxid_hex = if let Some(ref witnesses_vec) = witnesses {
                    Self::calculate_wtxid(&tx, witnesses_vec)
                } else {
                    // No witness data available - assume non-SegWit (wtxid == txid)
                    txid_hex.clone()
                };

                // Calculate sizes and weight
                let (base_size, total_size, weight, vsize) =
                    Self::calculate_segwit_sizes(&tx, witnesses.as_deref());

                // For SegWit transactions, hash field should be wtxid
                // For non-SegWit, hash == txid
                let hash_hex = if witnesses
                    .as_ref()
                    .map(|w| w.iter().any(|ws| !ws.is_empty()))
                    .unwrap_or(false)
                {
                    wtxid_hex.clone()
                } else {
                    txid_hex.clone()
                };

                // Serialize transaction hex (with witness if available)
                let tx_hex = Self::serialize_transaction_with_witness(&tx, witnesses.as_deref());

                if verbose {
                    Ok(json!({
                        "txid": txid_hex,
                        "hash": hash_hex,
                        "version": tx.version,
                        "size": total_size,
                        "vsize": vsize,
                        "weight": weight,
                        "locktime": tx.lock_time,
                        "vin": tx.inputs.iter().map(|input| json!({
                            "txid": hex::encode(input.prevout.hash),
                            "vout": input.prevout.index,
                            "scriptSig": {
                                "asm": "",
                                "hex": hex::encode(&input.script_sig)
                            },
                            "sequence": input.sequence
                        })).collect::<Vec<_>>(),
                        "vout": tx.outputs.iter().enumerate().map(|(i, output)| json!({
                            "value": output.value as f64 / 100_000_000.0,
                            "n": i,
                            "scriptPubKey": {
                                "asm": "",
                                "hex": hex::encode(&output.script_pubkey),
                                "reqSigs": 1,
                                "type": "pubkeyhash",
                                "addresses": []
                            }
                        })).collect::<Vec<_>>(),
                        "hex": tx_hex
                    }))
                } else {
                    Ok(json!(tx_hex))
                }
            } else {
                Err(RpcError::tx_not_found(""))
            }
        } else if verbose {
            Ok(json!({
                "txid": txid,
                "hash": txid,
                "version": 1,
                "size": 250,
                "vsize": 250,
                "weight": 1000,
                "locktime": 0,
                "vin": [],
                "vout": [],
                "hex": "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0100f2052a010000001976a914000000000000000000000000000000000000000088ac00000000"
            }))
        } else {
            Ok(json!("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0100f2052a010000001976a914000000000000000000000000000000000000000088ac00000000"))
        }
    }

    /// Get transaction output information
    ///
    /// Params: ["txid", n, includemempool (optional, default: true)]
    pub async fn gettxout(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: gettxout");

        let txid = params
            .get(0)
            .and_then(|p| p.as_str())
            .ok_or_else(|| RpcError::invalid_params("Missing txid parameter"))?;

        let n = params
            .get(1)
            .and_then(|p| p.as_u64())
            .ok_or_else(|| RpcError::invalid_params("Missing n parameter"))?;

        let include_mempool = param_bool_default(params, 2, true);

        let txid_bytes = hex::decode(txid)
            .map_err(|e| RpcError::invalid_params(format!("Invalid txid: {e}")))?;
        if txid_bytes.len() != 32 {
            return Err(RpcError::invalid_params("Invalid txid length"));
        }
        let mut txid_array = [0u8; 32];
        txid_array.copy_from_slice(&txid_bytes);

        use blvm_protocol::OutPoint;
        let outpoint = OutPoint {
            hash: txid_array,
            index: n as u32,
        };

        if let Some(ref storage) = self.storage {
            // Check mempool first if requested
            if include_mempool {
                if let Some(ref mempool) = self.mempool {
                    if let Some(tx) = mempool.get_transaction(&txid_array) {
                        if (n as usize) < tx.outputs.len() {
                            let output = &tx.outputs[n as usize];
                            let (best_hash, _) = storage.chain().get_tip_hash_and_height()?;
                            return Ok(json!({
                                "bestblock": hex::encode(best_hash),
                                "confirmations": 0,
                                "value": output.value as f64 / 100_000_000.0,
                                "scriptPubKey": {
                                    "asm": "",
                                    "hex": hex::encode(&output.script_pubkey),
                                    "reqSigs": 1,
                                    "type": "pubkeyhash",
                                    "addresses": []
                                },
                                "coinbase": false
                            }));
                        }
                    }
                }
            }

            // Check storage with timeout to prevent hanging (wrap sync operations)
            let timeout_dur = self.storage_timeout();
            match with_custom_timeout(
                async {
                    tokio::task::spawn_blocking({
                        let storage = storage.clone();
                        move || storage.utxos().get_utxo(&outpoint)
                    })
                    .await
                },
                timeout_dur,
            )
            .await
            {
                Ok(Ok(Ok(Some(utxo)))) => {
                    // UTXO found - get chain info with timeout
                    let timeout_dur2 = self.storage_timeout();
                    let (best_hash, tip_height) = match with_custom_timeout(
                        async {
                            tokio::task::spawn_blocking({
                                let storage = storage.clone();
                                move || -> Result<([u8; 32], u64), anyhow::Error> {
                                    let best_hash = storage
                                        .chain()
                                        .get_tip_hash()
                                        .ok()
                                        .flatten()
                                        .unwrap_or([0u8; 32]);
                                    let tip_height =
                                        storage.chain().get_height().ok().flatten().unwrap_or(0);
                                    Ok((best_hash, tip_height))
                                }
                            })
                            .await
                        },
                        timeout_dur2,
                    )
                    .await
                    {
                        Ok(Ok(Ok((hash, height)))) => (hash, height),
                        _ => ([0u8; 32], 0), // Fallback on error/timeout
                    };

                    // Find block height containing this transaction (with timeout protection)
                    // Use blocking task with timeout to prevent hanging
                    let timeout_dur3 = self.storage_timeout();
                    let tx_height = match with_custom_timeout(
                        async {
                            tokio::task::spawn_blocking({
                                let storage = storage.clone();
                                let outpoint_hash = outpoint.hash;
                                let search_limit = tip_height.min(1000); // Limit search
                                move || -> Result<Option<u64>, anyhow::Error> {
                                    let mut tx_height: Option<u64> = None;
                                    for h in 0..=search_limit {
                                        if let Ok(Some(block_hash)) =
                                            storage.blocks().get_hash_by_height(h)
                                        {
                                            if let Ok(Some(block)) =
                                                storage.blocks().get_block(&block_hash)
                                            {
                                                for tx in &block.transactions {
                                                    use blvm_protocol::block::calculate_tx_id;
                                                    let txid = calculate_tx_id(tx);
                                                    if txid == outpoint_hash {
                                                        tx_height = Some(h);
                                                        break;
                                                    }
                                                }
                                            }
                                            if tx_height.is_some() {
                                                break;
                                            }
                                        }
                                    }
                                    Ok(tx_height)
                                }
                            })
                            .await
                        },
                        timeout_dur3,
                    )
                    .await
                    {
                        Ok(Ok(Ok(height))) => height,
                        _ => None, // Fallback on error/timeout
                    };

                    let confirmations = tx_height
                        .map(|h| {
                            if h > tip_height {
                                0
                            } else {
                                (tip_height - h + 1) as i64
                            }
                        })
                        .unwrap_or(0);

                    Ok(json!({
                        "bestblock": hex::encode(best_hash),
                        "confirmations": confirmations,
                        "value": utxo.value as f64 / 100_000_000.0,
                        "scriptPubKey": {
                            "asm": "",
                            "hex": hex::encode(&utxo.script_pubkey),
                            "reqSigs": 1,
                            "type": "pubkeyhash",
                            "addresses": []
                        },
                        "coinbase": false
                    }))
                }
                Ok(Ok(Ok(None))) | Ok(Ok(Err(_))) | Ok(Err(_)) => {
                    // UTXO not found or error - return null (normal case)
                    Ok(Value::Null)
                }
                Err(_) => {
                    // Timeout - log and return null (graceful degradation)
                    warn!("Timeout getting UTXO from storage");
                    Ok(Value::Null)
                }
            }
        } else {
            Ok(json!(null))
        }
    }

    /// Build merkle proof for transactions in a block
    fn build_merkle_proof(
        transactions: &[blvm_protocol::Transaction],
        tx_indices: &[usize],
    ) -> Result<Vec<[u8; 32]>, RpcError> {
        use crate::storage::hashing::double_sha256;
        use blvm_protocol::block::calculate_tx_id;

        if transactions.is_empty() {
            return Err(RpcError::internal_error(
                "Block has no transactions".to_string(),
            ));
        }

        // Calculate all transaction hashes
        let tx_hashes: Vec<[u8; 32]> = transactions.iter().map(calculate_tx_id).collect();

        let mut proof = Vec::new();
        let mut current_level = tx_hashes.clone();
        let mut current_indices: Vec<usize> = (0..transactions.len()).collect();

        // Build proof by traversing the merkle tree
        while current_level.len() > 1 {
            let mut next_level = Vec::new();
            let mut next_indices = Vec::new();
            let mut proof_added = false;

            for chunk in current_level.chunks(2) {
                if chunk.len() == 2 {
                    // Hash two hashes together
                    let mut combined = Vec::with_capacity(64);
                    combined.extend_from_slice(&chunk[0]);
                    combined.extend_from_slice(&chunk[1]);
                    let parent_hash = double_sha256(&combined);
                    next_level.push(parent_hash);

                    // Check if we need to add sibling to proof
                    if !proof_added {
                        for &idx in tx_indices {
                            let pos = current_indices.iter().position(|&i| i == idx);
                            if let Some(pos) = pos {
                                if pos % 2 == 0 && pos + 1 < current_level.len() {
                                    // Left child - add right sibling
                                    proof.push(chunk[1]);
                                } else if pos % 2 == 1 {
                                    // Right child - add left sibling
                                    proof.push(chunk[0]);
                                }
                                proof_added = true;
                                break;
                            }
                        }
                    }
                } else {
                    // Odd number: duplicate the last hash
                    let mut combined = Vec::with_capacity(64);
                    combined.extend_from_slice(&chunk[0]);
                    combined.extend_from_slice(&chunk[0]);
                    let parent_hash = double_sha256(&combined);
                    next_level.push(parent_hash);
                }
            }

            // Update indices for next level
            for i in 0..next_level.len() {
                next_indices.push(i);
            }

            current_level = next_level;
            current_indices = next_indices;
        }

        Ok(proof)
    }

    /// Get merkle proof that a transaction is in a block
    ///
    /// Params: ["txids", blockhash (optional)]
    pub async fn gettxoutproof(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: gettxoutproof");

        let txids = params
            .get(0)
            .and_then(|p| p.as_array())
            .ok_or_else(|| RpcError::invalid_params("Missing txids parameter"))?;

        let blockhash_opt = param_str(params, 1);

        if let Some(ref storage) = self.storage {
            // Find block containing the transactions
            let mut block: Option<blvm_protocol::Block> = None;
            let tip_height = storage.chain().get_height()?.unwrap_or(0);

            if let Some(blockhash_str) = blockhash_opt {
                // Use specified blockhash
                let blockhash_bytes = hex::decode(blockhash_str)
                    .map_err(|e| RpcError::invalid_params(format!("Invalid blockhash: {e}")))?;
                if blockhash_bytes.len() != 32 {
                    return Err(RpcError::invalid_params("Invalid blockhash length"));
                }
                let mut blockhash_array = [0u8; 32];
                blockhash_array.copy_from_slice(&blockhash_bytes);
                if let Ok(Some(b)) = storage.blocks().get_block(&blockhash_array) {
                    block = Some(b);
                }
            } else {
                // Search for block containing any of the txids
                for h in 0..=tip_height {
                    if let Ok(Some(block_hash)) = storage.blocks().get_hash_by_height(h) {
                        if let Ok(Some(b)) = storage.blocks().get_block(&block_hash) {
                            // Check if block contains any of the requested txids
                            use blvm_protocol::block::calculate_tx_id;
                            for tx in &b.transactions {
                                let txid = calculate_tx_id(tx);
                                let txid_hex = hex::encode(txid);
                                if txids
                                    .iter()
                                    .any(|tid| tid.as_str() == Some(txid_hex.as_str()))
                                {
                                    block = Some(b);
                                    break;
                                }
                            }
                            if block.is_some() {
                                break;
                            }
                        }
                    }
                }
            }

            if let Some(block) = block {
                // Find transaction indices
                use blvm_protocol::block::calculate_tx_id;
                let mut tx_indices = Vec::new();
                for (idx, tx) in block.transactions.iter().enumerate() {
                    let txid = calculate_tx_id(tx);
                    let txid_hex = hex::encode(txid);
                    if txids
                        .iter()
                        .any(|tid| tid.as_str() == Some(txid_hex.as_str()))
                    {
                        tx_indices.push(idx);
                    }
                }

                if tx_indices.is_empty() {
                    return Err(RpcError::invalid_params(
                        "None of the specified transactions found in block",
                    ));
                }

                // Build merkle proof
                let proof_hashes = Self::build_merkle_proof(&block.transactions, &tx_indices)
                    .map_err(|e| {
                        RpcError::internal_error(format!("Failed to build merkle proof: {e}"))
                    })?;

                // Serialize proof (simplified format)
                let mut proof_bytes = Vec::new();
                proof_bytes.push(proof_hashes.len() as u8);
                for hash in &proof_hashes {
                    proof_bytes.extend_from_slice(hash);
                }

                Ok(json!(hex::encode(proof_bytes)))
            } else {
                Err(RpcError::block_not_found(""))
            }
        } else {
            Err(RpcError::invalid_params(
                "RPC not initialized with dependencies",
            ))
        }
    }

    /// Verify a merkle proof
    ///
    /// Params: ["proof", blockhash"]
    pub async fn verifytxoutproof(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: verifytxoutproof");

        let proof_hex = params
            .get(0)
            .and_then(|p| p.as_str())
            .ok_or_else(|| RpcError::invalid_params("Missing proof parameter"))?;

        let blockhash = params
            .get(1)
            .and_then(|p| p.as_str())
            .ok_or_else(|| RpcError::invalid_params("Missing blockhash parameter"))?;

        if let Some(ref storage) = self.storage {
            // Decode proof
            let proof_bytes = hex::decode(proof_hex)
                .map_err(|e| RpcError::invalid_params(format!("Invalid proof hex: {e}")))?;

            if proof_bytes.is_empty() {
                return Err(RpcError::invalid_params("Empty proof"));
            }

            let num_hashes = proof_bytes[0] as usize;
            if proof_bytes.len() < 1 + num_hashes * 32 {
                return Err(RpcError::invalid_params("Invalid proof length"));
            }

            let mut proof_hashes = Vec::new();
            for i in 0..num_hashes {
                let start = 1 + i * 32;
                let end = start + 32;
                let mut hash = [0u8; 32];
                hash.copy_from_slice(&proof_bytes[start..end]);
                proof_hashes.push(hash);
            }

            // Get block
            let blockhash_bytes = hex::decode(blockhash)
                .map_err(|e| RpcError::invalid_params(format!("Invalid blockhash: {e}")))?;
            if blockhash_bytes.len() != 32 {
                return Err(RpcError::invalid_params("Invalid blockhash length"));
            }
            let mut blockhash_array = [0u8; 32];
            blockhash_array.copy_from_slice(&blockhash_bytes);

            if let Ok(Some(block)) = storage.blocks().get_block(&blockhash_array) {
                // Calculate merkle root from block
                use blvm_protocol::mining::calculate_merkle_root;
                let calculated_root = calculate_merkle_root(&block.transactions).map_err(|e| {
                    RpcError::internal_error(format!("Failed to calculate merkle root: {e}"))
                })?;

                // Verify proof by reconstructing root (simplified - would need txids from proof)
                // For now, just verify the block's merkle root matches the header
                let matches = calculated_root == block.header.merkle_root;

                // Extract transaction IDs from proof (simplified - full implementation would decode txids)
                use blvm_protocol::block::calculate_tx_id;
                let txids: Vec<String> = block
                    .transactions
                    .iter()
                    .map(|tx| hex::encode(calculate_tx_id(tx)))
                    .collect();

                Ok(json!(json!({
                    "txids": txids,
                    "merkle_root": hex::encode(calculated_root),
                    "matches": matches
                })))
            } else {
                Err(RpcError::block_not_found(""))
            }
        } else {
            Err(RpcError::invalid_params(
                "RPC not initialized with dependencies",
            ))
        }
    }

    /// Get comprehensive transaction details
    ///
    /// Params: ["txid", include_hex (optional, default: false)]
    /// Returns: Complete transaction information including block info, confirmations, inputs, outputs, fees
    pub async fn get_transaction_details(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: gettransactiondetails");

        let txid = params
            .get(0)
            .and_then(|p| p.as_str())
            .ok_or_else(|| RpcError::missing_parameter("txid", Some("string (hex)")))?;

        let include_hex = param_bool_default(params, 1, false);

        let hash_bytes = hex::decode(txid).map_err(|e| {
            RpcError::invalid_hash_format(
                txid,
                Some(32),
                Some(&format!("Invalid hex encoding: {e}")),
            )
        })?;
        if hash_bytes.len() != 32 {
            return Err(RpcError::invalid_hash_format(
                txid,
                Some(32),
                Some("Transaction ID must be 64 hex characters (32 bytes)"),
            ));
        }
        let mut hash = [0u8; 32];
        hash.copy_from_slice(&hash_bytes);

        // Check mempool first
        if let Some(ref mempool) = self.mempool {
            if let Some(tx) = mempool.get_transaction(&hash) {
                use blvm_protocol::serialization::transaction::serialize_transaction;
                let size = serialize_transaction(&tx).len();
                let fee = if let Some(ref storage) = self.storage {
                    let utxo_set = storage.utxos().get_all_utxos().unwrap_or_default();
                    mempool.calculate_transaction_fee(&tx, &utxo_set) as f64 / 100_000_000.0
                } else {
                    0.0
                };

                return Ok(json!({
                    "txid": txid,
                    "hash": txid,
                    "version": tx.version,
                    "size": size,
                    "vsize": size,
                    "weight": size * 4,
                    "locktime": tx.lock_time,
                    "vin": tx.inputs.iter().map(|input| json!({
                        "txid": hex::encode(input.prevout.hash),
                        "vout": input.prevout.index,
                        "scriptSig": hex::encode(&input.script_sig),
                        "sequence": input.sequence
                    })).collect::<Vec<_>>(),
                    "vout": tx.outputs.iter().enumerate().map(|(idx, output)| json!({
                        "value": output.value as f64 / 100_000_000.0,
                        "n": idx,
                        "scriptPubKey": {
                            "asm": hex::encode(&output.script_pubkey),
                            "hex": hex::encode(&output.script_pubkey),
                            "type": "nonstandard" // Would need script analysis
                        }
                    })).collect::<Vec<_>>(),
                    "hex": if include_hex { hex::encode(serialize_transaction(&tx)) } else { "".to_string() },
                    "blockhash": Value::Null,
                    "confirmations": 0,
                    "time": 0,
                    "blocktime": Value::Null,
                    "fee": fee,
                    "fee_rate": if size > 0 { fee / (size as f64 / 1000.0) } else { 0.0 }
                }));
            }
        }

        // Check blockchain
        if let Some(ref storage) = self.storage {
            if let Ok(Some(tx)) = storage.transactions().get_transaction(&hash) {
                use blvm_protocol::serialization::transaction::serialize_transaction;
                let size = serialize_transaction(&tx).len();

                // Get block info if available from transaction metadata
                let metadata = storage.transactions().get_metadata(&hash).ok().flatten();
                let block_hash = metadata.map(|m| m.block_hash);
                let confirmations = if let Some(ref block_hash) = block_hash {
                    let block_height = storage
                        .blocks()
                        .get_height_by_hash(block_hash)
                        .ok()
                        .flatten();
                    let tip_height = storage.chain().get_height().ok().flatten().unwrap_or(0);
                    block_height
                        .map(|h| tip_height.saturating_sub(h) + 1)
                        .unwrap_or(0)
                } else {
                    0
                };

                let block_time = block_hash
                    .and_then(|bh| storage.blocks().get_header(&bh).ok().flatten())
                    .map(|h| h.timestamp)
                    .unwrap_or(0);

                return Ok(json!({
                    "txid": txid,
                    "hash": txid,
                    "version": tx.version,
                    "size": size,
                    "vsize": size,
                    "weight": size * 4,
                    "locktime": tx.lock_time,
                    "vin": tx.inputs.iter().map(|input| json!({
                        "txid": hex::encode(input.prevout.hash),
                        "vout": input.prevout.index,
                        "scriptSig": hex::encode(&input.script_sig),
                        "sequence": input.sequence
                    })).collect::<Vec<_>>(),
                    "vout": tx.outputs.iter().enumerate().map(|(idx, output)| json!({
                        "value": output.value as f64 / 100_000_000.0,
                        "n": idx,
                        "scriptPubKey": {
                            "asm": hex::encode(&output.script_pubkey),
                            "hex": hex::encode(&output.script_pubkey),
                            "type": "nonstandard"
                        }
                    })).collect::<Vec<_>>(),
                    "hex": if include_hex { hex::encode(serialize_transaction(&tx)) } else { "".to_string() },
                    "blockhash": block_hash.map(|h| Value::String(hex::encode(h))).unwrap_or(Value::Null),
                    "confirmations": confirmations,
                    "time": block_time,
                    "blocktime": if block_time > 0 { Some(block_time) } else { None },
                    "fee": Value::Null, // Would need to calculate from inputs/outputs
                    "fee_rate": Value::Null
                }));
            }
        }

        Err(RpcError::tx_not_found_with_context(
            txid,
            false, // Not in mempool
            Some("Transaction not found in mempool or blockchain"),
        ))
    }

    /// Create a raw transaction
    ///
    /// Params: [inputs, outputs, locktime (optional), replaceable (optional), version (optional)]
    /// - inputs: Array of {"txid": "hex", "vout": n, "sequence": n (optional)}
    /// - outputs: Object with address->amount pairs, or array with {"address": amount} or {"data": "hex"}
    /// - locktime: Transaction locktime (default: 0)
    /// - replaceable: Enable RBF (default: true)
    /// - version: Transaction version (default: 2)
    pub async fn createrawtransaction(&self, params: &Value) -> RpcResult<Value> {
        debug!("RPC: createrawtransaction");

        // Parse inputs
        let inputs = params
            .get(0)
            .and_then(|p| p.as_array())
            .ok_or_else(|| RpcError::missing_parameter("inputs", Some("array")))?;

        // Parse outputs - can be object (address->amount) or array (with "address" or "data" keys)
        let outputs = params
            .get(1)
            .ok_or_else(|| RpcError::missing_parameter("outputs", Some("object or array")))?;

        // Parse optional parameters
        let locktime = param_u64_default(params, 2, 0);
        let replaceable = param_bool_default(params, 3, true);
        let version = param_u64_default(params, 4, 2);

        // Build transaction inputs
        use blvm_protocol::OutPoint;
        use blvm_protocol::TransactionInput;

        let mut tx_inputs = Vec::new();
        for (idx, input) in inputs.iter().enumerate() {
            let input_obj = input.as_object().ok_or_else(|| {
                RpcError::invalid_params(format!("Input {idx} must be an object"))
            })?;

            let txid_hex = input_obj
                .get("txid")
                .and_then(|v| v.as_str())
                .ok_or_else(|| RpcError::invalid_params(format!("Input {idx} missing 'txid'")))?;

            let txid_bytes = hex::decode(txid_hex).map_err(|e| {
                RpcError::invalid_params(format!("Invalid txid hex in input {idx}: {e}"))
            })?;
            if txid_bytes.len() != 32 {
                return Err(RpcError::invalid_params(format!(
                    "Invalid txid length in input {}: expected 32 bytes, got {}",
                    idx,
                    txid_bytes.len()
                )));
            }
            let mut txid = [0u8; 32];
            txid.copy_from_slice(&txid_bytes);

            let vout = input_obj
                .get("vout")
                .and_then(|v| v.as_u64())
                .ok_or_else(|| RpcError::invalid_params(format!("Input {idx} missing 'vout'")))?;

            // Sequence: use provided value, or set based on RBF
            let sequence = if let Some(seq_val) = input_obj.get("sequence").and_then(|v| v.as_u64())
            {
                seq_val as u32
            } else if replaceable {
                0xFFFFFFFD // MAX_BIP125_RBF_SEQUENCE
            } else if locktime > 0 {
                0xFFFFFFFE // MAX_SEQUENCE_NONFINAL
            } else {
                0xFFFFFFFF // SEQUENCE_FINAL
            };

            tx_inputs.push(TransactionInput {
                prevout: OutPoint {
                    hash: txid,
                    index: vout as u32,
                },
                script_sig: Vec::new(),
                sequence: sequence as u64,
            });
        }

        // Build transaction outputs
        use blvm_protocol::TransactionOutput;
        let mut tx_outputs = Vec::new();

        // Handle outputs - can be object (address->amount) or array
        if let Some(outputs_obj) = outputs.as_object() {
            // Object format: {"address": amount, ...}
            for (key, value) in outputs_obj.iter() {
                if key == "data" {
                    // OP_RETURN output
                    let data_hex = value.as_str().ok_or_else(|| {
                        RpcError::invalid_params("'data' output must be hex string")
                    })?;
                    let data = hex::decode(data_hex)
                        .map_err(|e| RpcError::invalid_params(format!("Invalid data hex: {e}")))?;

                    // OP_RETURN script: OP_RETURN <data>
                    let mut script = vec![blvm_protocol::opcodes::OP_RETURN];
                    script.push(data.len() as u8);
                    script.extend_from_slice(&data);

                    tx_outputs.push(TransactionOutput {
                        value: 0,
                        script_pubkey: script,
                    });
                } else {
                    // Address output
                    let address_str = key;
                    let amount = value
                        .as_f64()
                        .or_else(|| value.as_str().and_then(|s| s.parse::<f64>().ok()))
                        .ok_or_else(|| {
                            RpcError::invalid_params(format!(
                                "Invalid amount for address '{address_str}'"
                            ))
                        })?;

                    // Convert amount to satoshis
                    let satoshis = (amount * 100_000_000.0) as u64;

                    // Convert address to script_pubkey
                    let script_pubkey = Self::address_to_script_pubkey(address_str)?;

                    tx_outputs.push(TransactionOutput {
                        value: satoshis as i64,
                        script_pubkey,
                    });
                }
            }
        } else if let Some(outputs_arr) = outputs.as_array() {
            // Array format: [{"address": amount}, {"data": "hex"}, ...]
            for (idx, output) in outputs_arr.iter().enumerate() {
                let output_obj = output.as_object().ok_or_else(|| {
                    RpcError::invalid_params(format!("Output {idx} must be an object"))
                })?;

                if let Some(data_val) = output_obj.get("data") {
                    // OP_RETURN output
                    let data_hex = data_val.as_str().ok_or_else(|| {
                        RpcError::invalid_params(format!("Output {idx} 'data' must be hex string"))
                    })?;
                    let data = hex::decode(data_hex).map_err(|e| {
                        RpcError::invalid_params(format!("Invalid data hex in output {idx}: {e}"))
                    })?;

                    let mut script = vec![blvm_protocol::opcodes::OP_RETURN];
                    script.push(data.len() as u8);
                    script.extend_from_slice(&data);

                    tx_outputs.push(TransactionOutput {
                        value: 0,
                        script_pubkey: script,
                    });
                } else if let Some(addr_val) = output_obj.get("address") {
                    // Address output
                    let address_str = addr_val.as_str().ok_or_else(|| {
                        RpcError::invalid_params(format!("Output {idx} 'address' must be string"))
                    })?;

                    // Get amount from the same object (key-value pair)
                    let amount = output_obj
                        .values()
                        .find_map(|v| {
                            v.as_f64()
                                .or_else(|| v.as_str().and_then(|s| s.parse::<f64>().ok()))
                        })
                        .ok_or_else(|| {
                            RpcError::invalid_params(format!("Output {idx} missing amount"))
                        })?;

                    let satoshis = (amount * 100_000_000.0) as u64;
                    let script_pubkey = Self::address_to_script_pubkey(address_str)?;

                    tx_outputs.push(TransactionOutput {
                        value: satoshis as i64,
                        script_pubkey,
                    });
                } else {
                    return Err(RpcError::invalid_params(format!(
                        "Output {idx} must have either 'address' or 'data' key"
                    )));
                }
            }
        } else {
            return Err(RpcError::invalid_params(
                "Outputs must be an object or array",
            ));
        }

        if tx_outputs.is_empty() {
            return Err(RpcError::invalid_params(
                "Transaction must have at least one output",
            ));
        }

        let tx_bytes =
            Self::serialize_createrawtransaction_bytes(version, tx_inputs, tx_outputs, locktime)?;
        // Bitcoin Core returns the raw transaction as a single hex string.
        Ok(Value::String(hex::encode(&tx_bytes)))
    }
}

/// Build Transaction for createrawtransaction; production uses SmallVec, non-production uses Vec.
macro_rules! createrawtransaction_tx {
    ($version:expr, $inputs:expr, $outputs:expr, $locktime:expr) => {{
        use blvm_protocol::Transaction;
        #[cfg(feature = "production")]
        {
            use smallvec::SmallVec;
            Transaction {
                version: $version,
                inputs: SmallVec::from_vec($inputs),
                outputs: SmallVec::from_vec($outputs),
                lock_time: $locktime,
            }
        }
        #[cfg(not(feature = "production"))]
        {
            Transaction {
                version: $version,
                inputs: $inputs,
                outputs: $outputs,
                lock_time: $locktime,
            }
        }
    }};
}

impl RawTxRpc {
    /// Build Transaction (SmallVec vs Vec by feature) and return serialized bytes.
    /// Single place for serialize; production/non-production differ only in container type (macro).
    fn serialize_createrawtransaction_bytes(
        version: u64,
        tx_inputs: Vec<blvm_protocol::TransactionInput>,
        tx_outputs: Vec<blvm_protocol::TransactionOutput>,
        locktime: u64,
    ) -> RpcResult<Vec<u8>> {
        use blvm_protocol::serialization::transaction::serialize_transaction;

        let tx = createrawtransaction_tx!(version, tx_inputs, tx_outputs, locktime);
        Ok(serialize_transaction(&tx))
    }

    /// Convert Bitcoin address to script_pubkey
    /// Supports Bech32/Bech32m (SegWit/Taproot) and legacy Base58Check (P2PKH/P2SH)
    fn address_to_script_pubkey(address: &str) -> Result<Vec<u8>, RpcError> {
        address_string_to_script_pubkey(address)
    }
}

impl Default for RawTxRpc {
    fn default() -> Self {
        Self::new()
    }
}