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
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
//! JSON-RPC server implementation
//!
//! HTTP JSON-RPC server: accepts connections and routes JSON-RPC requests.
//! Uses hyper for secure HTTP handling with proper request size limits.

use anyhow::Result;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use tracing::{debug, error, info, warn, Span};
use uuid::Uuid;

#[cfg(feature = "miniscript")]
use super::miniscript::miniscript_rpc;
#[cfg(feature = "bip70-http")]
use super::payment;
use super::{auth, blockchain, control, errors, mempool, mining, network, rawtx};
use crate::module::rpc::handler::ModuleRpcHandler;
use crate::network::dos_protection::ConnectionRateLimiter;
use crate::node::metrics::MetricsCollector;
use crate::utils::{RPC_CLIENT_READ_TIMEOUT, RPC_SERVER_STARTUP_WAIT};
use std::collections::HashMap;

/// Default maximum request body size (1MB) when not configured.
/// Matches config rpc.max_request_size_bytes default.
pub const DEFAULT_MAX_REQUEST_SIZE: usize = 1_048_576;

/// JSON-RPC server
#[derive(Clone)]
pub struct RpcServer {
    addr: SocketAddr,
    // Cached RPC handlers to avoid recreating on every request
    blockchain: Arc<blockchain::BlockchainRpc>,
    network: Arc<network::NetworkRpc>,
    mempool: Arc<mempool::MempoolRpc>,
    mining: Arc<mining::MiningRpc>,
    rawtx: Arc<rawtx::RawTxRpc>,
    control: Arc<control::ControlRpc>,
    #[cfg(feature = "bip70-http")]
    payment: Option<Arc<payment::PaymentRpc>>,
    // Authentication manager (optional)
    auth_manager: Option<Arc<auth::RpcAuthManager>>,
    // Metrics collector (optional, for Prometheus export)
    metrics: Option<Arc<MetricsCollector>>,
    // Module RPC endpoints (dynamic registration)
    module_endpoints: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn ModuleRpcHandler>>>>,
    /// Maximum request body size in bytes
    max_request_size: usize,
    /// Connection rate limiter (per-IP connection attempts per minute)
    connection_limiter: Option<Arc<tokio::sync::Mutex<ConnectionRateLimiter>>>,
    /// Batch rate multiplier cap: min(batch_len, this) tokens consumed
    batch_rate_multiplier_cap: u32,
}

impl RpcServer {
    /// Default RPC handlers (used by `new` and `with_auth`). Single place so adding a handler type updates one spot.
    fn default_handlers() -> (
        Arc<blockchain::BlockchainRpc>,
        Arc<network::NetworkRpc>,
        Arc<mempool::MempoolRpc>,
        Arc<mining::MiningRpc>,
        Arc<rawtx::RawTxRpc>,
        Arc<control::ControlRpc>,
    ) {
        (
            Arc::new(blockchain::BlockchainRpc::new()),
            Arc::new(network::NetworkRpc::new()),
            Arc::new(mempool::MempoolRpc::new()),
            Arc::new(mining::MiningRpc::new()),
            Arc::new(rawtx::RawTxRpc::new()),
            Arc::new(control::ControlRpc::new()),
        )
    }

    /// Build server from required components and optional auth/metrics/limiter. Single assignment site for all fields.
    fn from_components(
        addr: SocketAddr,
        blockchain: Arc<blockchain::BlockchainRpc>,
        network: Arc<network::NetworkRpc>,
        mempool: Arc<mempool::MempoolRpc>,
        mining: Arc<mining::MiningRpc>,
        rawtx: Arc<rawtx::RawTxRpc>,
        control: Arc<control::ControlRpc>,
        auth_manager: Option<Arc<auth::RpcAuthManager>>,
        metrics: Option<Arc<MetricsCollector>>,
        connection_limiter: Option<Arc<tokio::sync::Mutex<ConnectionRateLimiter>>>,
        max_request_size: usize,
        batch_rate_multiplier_cap: u32,
    ) -> Self {
        Self {
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            #[cfg(feature = "bip70-http")]
            payment: None,
            auth_manager,
            metrics,
            module_endpoints: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
            max_request_size,
            connection_limiter,
            batch_rate_multiplier_cap,
        }
    }

    /// Create a new RPC server
    pub fn new(addr: SocketAddr) -> Self {
        let (blockchain, network, mempool, mining, rawtx, control) = Self::default_handlers();
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            None,
            None,
            None,
            DEFAULT_MAX_REQUEST_SIZE,
            10,
        )
    }

    /// Create a new RPC server with authentication
    pub fn with_auth(addr: SocketAddr, auth_manager: Arc<auth::RpcAuthManager>) -> Self {
        let (blockchain, network, mempool, mining, rawtx, control) = Self::default_handlers();
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            Some(auth_manager),
            None,
            None,
            DEFAULT_MAX_REQUEST_SIZE,
            10,
        )
    }

    /// Set connection rate limiter (per-IP connections per minute)
    pub fn with_connection_limiter(
        mut self,
        limiter: Arc<tokio::sync::Mutex<ConnectionRateLimiter>>,
    ) -> Self {
        self.connection_limiter = Some(limiter);
        self
    }

    /// Set batch rate multiplier cap (min(batch_len, cap) tokens consumed)
    pub fn with_batch_rate_multiplier_cap(mut self, cap: u32) -> Self {
        self.batch_rate_multiplier_cap = cap;
        self
    }

    /// Create with dependencies
    pub fn with_dependencies(
        addr: SocketAddr,
        blockchain: Arc<blockchain::BlockchainRpc>,
        network: Arc<network::NetworkRpc>,
        mempool: Arc<mempool::MempoolRpc>,
        mining: Arc<mining::MiningRpc>,
        rawtx: Arc<rawtx::RawTxRpc>,
        control: Arc<control::ControlRpc>,
        max_request_size: usize,
    ) -> Self {
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            None,
            None,
            None,
            max_request_size,
            10,
        )
    }

    /// Create with dependencies including payment RPC
    #[cfg(feature = "bip70-http")]
    pub fn with_payment(mut self, payment: Arc<payment::PaymentRpc>) -> Self {
        self.payment = Some(payment);
        self
    }

    /// Create with dependencies and metrics
    pub fn with_dependencies_and_metrics(
        addr: SocketAddr,
        blockchain: Arc<blockchain::BlockchainRpc>,
        network: Arc<network::NetworkRpc>,
        mempool: Arc<mempool::MempoolRpc>,
        mining: Arc<mining::MiningRpc>,
        rawtx: Arc<rawtx::RawTxRpc>,
        control: Arc<control::ControlRpc>,
        metrics: Arc<MetricsCollector>,
        max_request_size: usize,
    ) -> Self {
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            None,
            Some(metrics),
            None,
            max_request_size,
            10,
        )
    }

    /// Create with dependencies and authentication
    pub fn with_dependencies_and_auth(
        addr: SocketAddr,
        blockchain: Arc<blockchain::BlockchainRpc>,
        network: Arc<network::NetworkRpc>,
        mempool: Arc<mempool::MempoolRpc>,
        mining: Arc<mining::MiningRpc>,
        rawtx: Arc<rawtx::RawTxRpc>,
        control: Arc<control::ControlRpc>,
        auth_manager: Arc<auth::RpcAuthManager>,
        max_request_size: usize,
    ) -> Self {
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            Some(auth_manager),
            None,
            None,
            max_request_size,
            10,
        )
    }

    /// Create with dependencies, authentication, and metrics
    pub fn with_dependencies_auth_and_metrics(
        addr: SocketAddr,
        blockchain: Arc<blockchain::BlockchainRpc>,
        network: Arc<network::NetworkRpc>,
        mempool: Arc<mempool::MempoolRpc>,
        mining: Arc<mining::MiningRpc>,
        rawtx: Arc<rawtx::RawTxRpc>,
        control: Arc<control::ControlRpc>,
        auth_manager: Arc<auth::RpcAuthManager>,
        metrics: Arc<MetricsCollector>,
        max_request_size: usize,
    ) -> Self {
        Self::from_components(
            addr,
            blockchain,
            network,
            mempool,
            mining,
            rawtx,
            control,
            Some(auth_manager),
            Some(metrics),
            None,
            max_request_size,
            10,
        )
    }

    /// Start the RPC server
    ///
    /// Handles both HTTP (via hyper) and raw TCP JSON-RPC (for backward compatibility)
    pub async fn start(&self) -> Result<()> {
        let listener = TcpListener::bind(self.addr).await?;
        info!("RPC server listening on {}", self.addr);

        // Wrap server in Arc to share across connections
        // Create a new server instance with cloned Arc handlers
        let server = Arc::new(RpcServer {
            addr: self.addr,
            blockchain: Arc::clone(&self.blockchain),
            network: Arc::clone(&self.network),
            mempool: Arc::clone(&self.mempool),
            mining: Arc::clone(&self.mining),
            rawtx: Arc::clone(&self.rawtx),
            control: Arc::clone(&self.control),
            #[cfg(feature = "bip70-http")]
            payment: self.payment.clone(),
            auth_manager: self.auth_manager.clone(),
            metrics: self.metrics.clone(),
            module_endpoints: Arc::clone(&self.module_endpoints),
            max_request_size: self.max_request_size,
            connection_limiter: self.connection_limiter.clone(),
            batch_rate_multiplier_cap: self.batch_rate_multiplier_cap,
        });

        loop {
            match listener.accept().await {
                Ok((stream, addr)) => {
                    // Connection rate limit check (per-IP per minute)
                    if let Some(ref limiter) = server.connection_limiter {
                        let mut guard = limiter.lock().await;
                        if !guard.check_connection(addr.ip()) {
                            debug!("RPC connection rejected (rate limit) from {}", addr);
                            drop(stream);
                            continue;
                        }
                    }

                    debug!("New RPC connection from {}", addr);
                    let peer_addr = addr;
                    let server = Arc::clone(&server);

                    // Spawn task to handle connection
                    // Clone values before moving into async block to ensure Send
                    let server_for_spawn = Arc::clone(&server);
                    let peer_addr_for_spawn = peer_addr;
                    tokio::spawn(async move {
                        // Use hyper for HTTP - it will handle protocol detection and parsing
                        let io = TokioIo::new(stream);
                        let server_clone = Arc::clone(&server_for_spawn);
                        let peer_addr_clone = peer_addr_for_spawn;
                        let service = service_fn({
                            let server_for_service = Arc::clone(&server_clone);
                            let addr_for_service = peer_addr_clone;
                            move |req| {
                                let server_inner = Arc::clone(&server_for_service);
                                let addr_inner = addr_for_service;
                                Self::handle_http_request_with_server(server_inner, req, addr_inner)
                            }
                        });

                        // Try to serve as HTTP
                        if let Err(e) = http1::Builder::new().serve_connection(io, service).await {
                            // If hyper fails, it might be raw TCP
                            // But we can't recover here since hyper consumed the connection
                            // For now, log and continue - raw TCP support would need separate port
                            debug!(
                                "HTTP connection failed from {} (might be raw TCP): {}",
                                peer_addr_clone, e
                            );
                        }
                    });
                }
                Err(e) => {
                    error!("Failed to accept RPC connection: {}", e);
                }
            }
        }
    }

    /// Handle HTTP request using hyper (with server instance for cached handlers)
    async fn handle_http_request_with_server(
        server: Arc<Self>,
        req: Request<Incoming>,
        addr: SocketAddr,
    ) -> Result<Response<Full<Bytes>>, hyper::Error> {
        // Extract headers before consuming request body
        let headers = req.headers().clone();

        // Handle GET requests for health and metrics endpoints
        if req.method() == Method::GET {
            let path = req.uri().path();

            // Optional authentication for health/metrics (stricter for metrics)
            if let Some(ref auth_manager) = server.auth_manager {
                // Metrics endpoint requires authentication if auth is enabled
                if path == "/metrics" {
                    let auth_result = auth_manager.authenticate_request(&headers, addr).await;
                    if let Some(error) = &auth_result.error {
                        warn!(
                            "Metrics endpoint authentication failed from {}: {}",
                            addr, error
                        );
                        return Ok(Self::http_error_response(
                            StatusCode::UNAUTHORIZED,
                            "Authentication required for metrics endpoint",
                        ));
                    }
                    // Check rate limit for metrics (stricter)
                    if let Some(ref user_id) = auth_result.user_id {
                        if !auth_manager
                            .check_rate_limit_with_endpoint(user_id, Some(addr), Some("/metrics"))
                            .await
                        {
                            return Ok(Self::http_error_response(
                                StatusCode::TOO_MANY_REQUESTS,
                                "Rate limit exceeded",
                            ));
                        }
                    } else if !auth_manager
                        .check_ip_rate_limit_with_endpoint(addr, Some("/metrics"))
                        .await
                    {
                        return Ok(Self::http_error_response(
                            StatusCode::TOO_MANY_REQUESTS,
                            "IP rate limit exceeded",
                        ));
                    }
                } else if path.starts_with("/health") {
                    // Health endpoints: optional auth, but rate limit if unauthenticated
                    let auth_result = auth_manager.authenticate_request(&headers, addr).await;
                    if auth_result.user_id.is_none() {
                        // Unauthenticated health check - apply stricter rate limiting
                        if !auth_manager
                            .check_ip_rate_limit_with_endpoint(addr, Some(path))
                            .await
                        {
                            return Ok(Self::http_error_response(
                                StatusCode::TOO_MANY_REQUESTS,
                                "IP rate limit exceeded",
                            ));
                        }
                    }
                }
            }

            if path == "/metrics" {
                return Self::handle_metrics_endpoint(server).await;
            }
            return Self::handle_health_endpoint(server, req).await;
        }

        // Only allow POST method for JSON-RPC
        if req.method() != Method::POST {
            return Ok(Self::http_error_response(
                StatusCode::METHOD_NOT_ALLOWED,
                "Only POST method is supported for JSON-RPC",
            ));
        }

        // Extract headers before consuming request body
        let headers = req.headers().clone();

        // Check Content-Type
        if let Some(content_type) = headers.get("content-type") {
            if content_type != "application/json" {
                warn!("Invalid Content-Type from {}: {:?}", addr, content_type);
            }
        }

        // Read request body with size limit
        let body = req.collect().await?;
        let body_bytes = body.to_bytes();

        // Enforce maximum request size
        if body_bytes.len() > server.max_request_size {
            return Ok(Self::http_error_response(
                StatusCode::PAYLOAD_TOO_LARGE,
                &format!(
                    "Request body too large: {} bytes (max: {} bytes)",
                    body_bytes.len(),
                    server.max_request_size
                ),
            ));
        }

        // Parse JSON body
        let json_body = match std::str::from_utf8(&body_bytes) {
            Ok(s) => s.to_string(),
            Err(e) => {
                return Ok(Self::http_error_response(
                    StatusCode::BAD_REQUEST,
                    &format!("Invalid UTF-8 in request body: {e}"),
                ));
            }
        };

        // Generate request ID for tracing
        let request_id = Uuid::new_v4().to_string();
        let request_id_short = request_id.chars().take(8).collect::<String>();

        // Create tracing span with request context
        let span = tracing::span!(
            tracing::Level::DEBUG,
            "rpc_request",
            request_id = %request_id_short,
            method = tracing::field::Empty,
            client_addr = %addr,
            request_size = json_body.len()
        );

        let _guard = span.enter();

        debug!("HTTP RPC request from {}: {} bytes", addr, json_body.len());

        // Parse request for method name and batch detection
        let parsed = serde_json::from_str::<Value>(&json_body).ok();
        let (method_name, rate_limit_n) = match &parsed {
            Some(Value::Array(requests)) => {
                // Batch request: consume min(len, cap) tokens
                let cap = server.batch_rate_multiplier_cap as usize;
                let n = requests.len().min(cap) as u32;
                ("batch".to_string(), n)
            }
            Some(req) => (
                req.get("method")
                    .and_then(|m| m.as_str())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "unknown".to_string()),
                1u32,
            ),
            None => ("unknown".to_string(), 1u32),
        };

        // Record method in span
        Span::current().record("method", &method_name);

        // Authenticate request if authentication is enabled
        let auth_result = if let Some(ref auth_manager) = server.auth_manager {
            Some(auth_manager.authenticate_request(&headers, addr).await)
        } else {
            None
        };

        // Check rate limiting (multiple layers)
        if let Some(ref auth_manager) = server.auth_manager {
            if let Some(ref auth_result) = auth_result {
                // Check if authentication failed
                if let Some(error) = &auth_result.error {
                    return Ok(Self::http_error_response(StatusCode::UNAUTHORIZED, error));
                }

                // Check per-user rate limiting (for authenticated users)
                if let Some(ref user_id) = auth_result.user_id {
                    let endpoint = format!("rpc:{method_name}");
                    if !auth_manager
                        .check_rate_limit_with_endpoint_n(
                            user_id,
                            Some(addr),
                            Some(&endpoint),
                            rate_limit_n,
                        )
                        .await
                    {
                        return Ok(Self::http_error_response(
                            StatusCode::TOO_MANY_REQUESTS,
                            "User rate limit exceeded",
                        ));
                    }
                }
            } else {
                // Unauthenticated request - check per-IP rate limit
                let endpoint = format!("rpc:{method_name}");
                if !auth_manager
                    .check_ip_rate_limit_with_endpoint_n(addr, Some(&endpoint), rate_limit_n)
                    .await
                {
                    return Ok(Self::http_error_response(
                        StatusCode::TOO_MANY_REQUESTS,
                        "IP rate limit exceeded",
                    ));
                }
            }

            // Check per-method rate limiting (applies to all requests; batch uses "batch")
            if !auth_manager.check_method_rate_limit(&method_name).await {
                return Ok(Self::http_error_response(
                    StatusCode::TOO_MANY_REQUESTS,
                    &format!("Method '{method_name}' rate limit exceeded"),
                ));
            }
        }

        // Process JSON-RPC request (reuse server instance with cached handlers)
        let start_time = std::time::Instant::now();
        let response_json = Self::process_request_with_server(server, &json_body).await;
        let duration = start_time.elapsed();

        // Record response metrics in span
        Span::current().record("duration_ms", duration.as_millis() as u64);
        Span::current().record("response_size", response_json.len());

        debug!(
            "RPC request completed in {:?} (request_id: {})",
            duration, request_id_short
        );

        // Build HTTP response with request ID header
        // Response::builder() returns http::Error, but we need hyper::Error
        // Since hyper::Error doesn't implement From<http::Error> or From<io::Error>,
        // we use expect() since Response::builder() should never fail with valid inputs
        Ok(Response::builder()
            .status(StatusCode::OK)
            .header("Content-Type", "application/json")
            .header("Content-Length", response_json.len())
            .header("X-Request-ID", request_id_short)
            .body(Full::new(Bytes::from(response_json)))
            .expect("Failed to build HTTP response - this should never happen with valid inputs"))
    }

    /// Handle Prometheus metrics endpoint
    async fn handle_metrics_endpoint(
        server: Arc<Self>,
    ) -> Result<Response<Full<Bytes>>, hyper::Error> {
        // Get metrics if available
        let metrics_text = if let Some(ref metrics_collector) = server.metrics {
            Self::format_prometheus_metrics(metrics_collector.collect())
        } else {
            // Return empty metrics if collector not available
            "# No metrics available\n".to_string()
        };

        let mut response = Response::builder()
            .status(StatusCode::OK)
            .header("Content-Type", "text/plain; version=0.0.4")
            .header("Content-Length", metrics_text.len())
            .body(Full::new(Bytes::from(metrics_text)))
            .expect("Failed to build metrics response");

        // Add security headers
        let headers = response.headers_mut();
        headers.insert("X-Content-Type-Options", "nosniff".parse().unwrap());
        headers.insert(
            "Cache-Control",
            "no-store, no-cache, must-revalidate".parse().unwrap(),
        );

        Ok(response)
    }

    /// Format NodeMetrics as Prometheus text format
    fn format_prometheus_metrics(metrics: crate::node::metrics::NodeMetrics) -> String {
        let mut output = String::new();

        // Network metrics
        output.push_str("# HELP blvm_network_peers_total Total number of connected peers\n");
        output.push_str("# TYPE blvm_network_peers_total gauge\n");
        output.push_str(&format!(
            "blvm_network_peers_total {}\n",
            metrics.network.peer_count
        ));

        output.push_str("# HELP blvm_network_bytes_sent_total Total bytes sent\n");
        output.push_str("# TYPE blvm_network_bytes_sent_total counter\n");
        output.push_str(&format!(
            "blvm_network_bytes_sent_total {}\n",
            metrics.network.bytes_sent
        ));

        output.push_str("# HELP blvm_network_bytes_received_total Total bytes received\n");
        output.push_str("# TYPE blvm_network_bytes_received_total counter\n");
        output.push_str(&format!(
            "blvm_network_bytes_received_total {}\n",
            metrics.network.bytes_received
        ));

        output.push_str("# HELP blvm_network_messages_sent_total Total messages sent\n");
        output.push_str("# TYPE blvm_network_messages_sent_total counter\n");
        output.push_str(&format!(
            "blvm_network_messages_sent_total {}\n",
            metrics.network.messages_sent
        ));

        output.push_str("# HELP blvm_network_messages_received_total Total messages received\n");
        output.push_str("# TYPE blvm_network_messages_received_total counter\n");
        output.push_str(&format!(
            "blvm_network_messages_received_total {}\n",
            metrics.network.messages_received
        ));

        output.push_str("# HELP blvm_network_active_connections Active network connections\n");
        output.push_str("# TYPE blvm_network_active_connections gauge\n");
        output.push_str(&format!(
            "blvm_network_active_connections {}\n",
            metrics.network.active_connections
        ));

        output.push_str("# HELP blvm_network_banned_peers Banned peers count\n");
        output.push_str("# TYPE blvm_network_banned_peers gauge\n");
        output.push_str(&format!(
            "blvm_network_banned_peers {}\n",
            metrics.network.banned_peers
        ));

        // Storage metrics
        output.push_str("# HELP blvm_storage_blocks_total Total blocks stored\n");
        output.push_str("# TYPE blvm_storage_blocks_total gauge\n");
        output.push_str(&format!(
            "blvm_storage_blocks_total {}\n",
            metrics.storage.block_count
        ));

        output.push_str("# HELP blvm_storage_utxos_total Total UTXOs\n");
        output.push_str("# TYPE blvm_storage_utxos_total gauge\n");
        output.push_str(&format!(
            "blvm_storage_utxos_total {}\n",
            metrics.storage.utxo_count
        ));

        output.push_str("# HELP blvm_storage_transactions_total Total transactions indexed\n");
        output.push_str("# TYPE blvm_storage_transactions_total gauge\n");
        output.push_str(&format!(
            "blvm_storage_transactions_total {}\n",
            metrics.storage.transaction_count
        ));

        output.push_str("# HELP blvm_storage_disk_size_bytes Estimated disk size in bytes\n");
        output.push_str("# TYPE blvm_storage_disk_size_bytes gauge\n");
        output.push_str(&format!(
            "blvm_storage_disk_size_bytes {}\n",
            metrics.storage.disk_size
        ));

        output.push_str("# HELP blvm_storage_within_bounds Storage bounds status (1=within bounds, 0=exceeded)\n");
        output.push_str("# TYPE blvm_storage_within_bounds gauge\n");
        output.push_str(&format!(
            "blvm_storage_within_bounds {}\n",
            if metrics.storage.within_bounds { 1 } else { 0 }
        ));

        // RPC metrics
        output.push_str("# HELP blvm_rpc_requests_total Total RPC requests\n");
        output.push_str("# TYPE blvm_rpc_requests_total counter\n");
        output.push_str(&format!(
            "blvm_rpc_requests_total {}\n",
            metrics.rpc.requests_total
        ));

        output.push_str("# HELP blvm_rpc_requests_success_total Successful RPC requests\n");
        output.push_str("# TYPE blvm_rpc_requests_success_total counter\n");
        output.push_str(&format!(
            "blvm_rpc_requests_success_total {}\n",
            metrics.rpc.requests_success
        ));

        output.push_str("# HELP blvm_rpc_requests_failed_total Failed RPC requests\n");
        output.push_str("# TYPE blvm_rpc_requests_failed_total counter\n");
        output.push_str(&format!(
            "blvm_rpc_requests_failed_total {}\n",
            metrics.rpc.requests_failed
        ));

        output.push_str("# HELP blvm_rpc_requests_per_second Current RPC requests per second\n");
        output.push_str("# TYPE blvm_rpc_requests_per_second gauge\n");
        output.push_str(&format!(
            "blvm_rpc_requests_per_second {}\n",
            metrics.rpc.requests_per_second
        ));

        output.push_str(
            "# HELP blvm_rpc_avg_response_time_ms Average RPC response time in milliseconds\n",
        );
        output.push_str("# TYPE blvm_rpc_avg_response_time_ms gauge\n");
        output.push_str(&format!(
            "blvm_rpc_avg_response_time_ms {}\n",
            metrics.rpc.avg_response_time_ms
        ));

        // Performance metrics
        output.push_str("# HELP blvm_performance_avg_block_processing_time_ms Average block processing time in milliseconds\n");
        output.push_str("# TYPE blvm_performance_avg_block_processing_time_ms gauge\n");
        output.push_str(&format!(
            "blvm_performance_avg_block_processing_time_ms {}\n",
            metrics.performance.avg_block_processing_time_ms
        ));

        output.push_str("# HELP blvm_performance_avg_tx_validation_time_ms Average transaction validation time in milliseconds\n");
        output.push_str("# TYPE blvm_performance_avg_tx_validation_time_ms gauge\n");
        output.push_str(&format!(
            "blvm_performance_avg_tx_validation_time_ms {}\n",
            metrics.performance.avg_tx_validation_time_ms
        ));

        output.push_str("# HELP blvm_performance_blocks_per_second Blocks processed per second\n");
        output.push_str("# TYPE blvm_performance_blocks_per_second gauge\n");
        output.push_str(&format!(
            "blvm_performance_blocks_per_second {}\n",
            metrics.performance.blocks_per_second
        ));

        output.push_str(
            "# HELP blvm_performance_transactions_per_second Transactions processed per second\n",
        );
        output.push_str("# TYPE blvm_performance_transactions_per_second gauge\n");
        output.push_str(&format!(
            "blvm_performance_transactions_per_second {}\n",
            metrics.performance.transactions_per_second
        ));

        // System metrics
        output.push_str("# HELP blvm_system_uptime_seconds Node uptime in seconds\n");
        output.push_str("# TYPE blvm_system_uptime_seconds gauge\n");
        output.push_str(&format!(
            "blvm_system_uptime_seconds {}\n",
            metrics.system.uptime_seconds
        ));

        if let Some(memory) = metrics.system.memory_usage_bytes {
            output.push_str("# HELP blvm_system_memory_usage_bytes Memory usage in bytes\n");
            output.push_str("# TYPE blvm_system_memory_usage_bytes gauge\n");
            output.push_str(&format!("blvm_system_memory_usage_bytes {memory}\n"));
        }

        if let Some(cpu) = metrics.system.cpu_usage_percent {
            output.push_str("# HELP blvm_system_cpu_usage_percent CPU usage percentage\n");
            output.push_str("# TYPE blvm_system_cpu_usage_percent gauge\n");
            output.push_str(&format!("blvm_system_cpu_usage_percent {cpu}\n"));
        }

        // DoS protection metrics
        output.push_str(
            "# HELP blvm_dos_connection_rate_violations_total Connection rate violations\n",
        );
        output.push_str("# TYPE blvm_dos_connection_rate_violations_total counter\n");
        output.push_str(&format!(
            "blvm_dos_connection_rate_violations_total {}\n",
            metrics.network.dos_protection.connection_rate_violations
        ));

        output.push_str("# HELP blvm_dos_auto_bans_total Auto-bans triggered\n");
        output.push_str("# TYPE blvm_dos_auto_bans_total counter\n");
        output.push_str(&format!(
            "blvm_dos_auto_bans_total {}\n",
            metrics.network.dos_protection.auto_bans
        ));

        output
    }

    /// Handle health check endpoints
    async fn handle_health_endpoint(
        server: Arc<Self>,
        req: Request<Incoming>,
    ) -> Result<Response<Full<Bytes>>, hyper::Error> {
        let path = req.uri().path();

        // Call gethealth RPC method internally
        let health_params = json!([]);
        let health_result = server.control.gethealth(&health_params).await;

        let (status_code, body) = match health_result {
            Ok(health_value) => {
                match path {
                    "/health" | "/health/live" => {
                        // Quick health check - just return status
                        let status = health_value
                            .get("status")
                            .and_then(|s| s.as_str())
                            .unwrap_or("unknown");
                        let is_healthy = status == "healthy" || status == "degraded";

                        let response_body = json!({
                            "status": status,
                            "service": "blvm-node"
                        });

                        let status_code = if is_healthy {
                            StatusCode::OK
                        } else {
                            StatusCode::SERVICE_UNAVAILABLE
                        };

                        (
                            status_code,
                            serde_json::to_string(&response_body)
                                .unwrap_or_else(|_| "{}".to_string()),
                        )
                    }
                    "/health/ready" => {
                        // Readiness probe - check if node is ready to serve traffic
                        let status = health_value
                            .get("status")
                            .and_then(|s| s.as_str())
                            .unwrap_or("unknown");
                        let is_ready = status == "healthy";

                        let response_body = json!({
                            "status": if is_ready { "ready" } else { "not_ready" },
                            "service": "blvm-node"
                        });

                        let status_code = if is_ready {
                            StatusCode::OK
                        } else {
                            StatusCode::SERVICE_UNAVAILABLE
                        };

                        (
                            status_code,
                            serde_json::to_string(&response_body)
                                .unwrap_or_else(|_| "{}".to_string()),
                        )
                    }
                    "/health/detailed" => {
                        // Detailed health report
                        (
                            StatusCode::OK,
                            serde_json::to_string(&health_value)
                                .unwrap_or_else(|_| "{}".to_string()),
                        )
                    }
                    _ => {
                        return Ok(Self::http_error_response(
                            StatusCode::NOT_FOUND,
                            "Health endpoint not found",
                        ));
                    }
                }
            }
            Err(_) => {
                // Health check failed
                let response_body = json!({
                    "status": "unhealthy",
                    "service": "blvm-node",
                    "error": "Health check failed"
                });
                (
                    StatusCode::SERVICE_UNAVAILABLE,
                    serde_json::to_string(&response_body).unwrap_or_else(|_| "{}".to_string()),
                )
            }
        };

        let mut response = Response::builder()
            .status(status_code)
            .header("Content-Type", "application/json")
            .header("Content-Length", body.len())
            .body(Full::new(Bytes::from(body)))
            .expect("Failed to build health response");

        // Add security headers
        let headers = response.headers_mut();
        headers.insert("X-Content-Type-Options", "nosniff".parse().unwrap());
        headers.insert(
            "Cache-Control",
            "no-store, no-cache, must-revalidate".parse().unwrap(),
        );

        Ok(response)
    }

    /// Create HTTP error response
    fn http_error_response(status: StatusCode, message: &str) -> Response<Full<Bytes>> {
        let body = json!({
            "error": {
                "code": status.as_u16(),
                "message": message
            }
        });
        let body_json = serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_string());

        Response::builder()
            .status(status)
            .header("Content-Type", "application/json")
            .header("Content-Length", body_json.len())
            .body(Full::new(Bytes::from(body_json)))
            .unwrap_or_else(|e| {
                // Fallback response if builder fails (should never happen)
                error!("Failed to build error response: {}", e);
                Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Full::new(Bytes::from(
                        "{\"error\":\"Internal server error\"}",
                    )))
                    .expect("Fallback response should always succeed")
            })
    }

    /// Process a JSON-RPC request
    ///
    /// Public method for use by both HTTP and raw TCP RPC servers
    /// Note: This creates temporary RPC handlers. For better performance,
    /// use process_request_with_server() with a server instance.
    pub async fn process_request(request: &str) -> String {
        // Create temporary server instance for backward compatibility
        // Using 127.0.0.1:0 is safe - it's just a placeholder address for testing
        let addr: SocketAddr = "127.0.0.1:0"
            .parse()
            .expect("127.0.0.1:0 should always parse as valid SocketAddr");
        let server = Arc::new(Self::new(addr));
        Self::process_request_with_server(server, request).await
    }

    /// Process a JSON-RPC request with a server instance (reuses cached handlers)
    /// Supports both single requests and batch requests (JSON-RPC 2.0)
    async fn process_request_with_server(server: Arc<Self>, request: &str) -> String {
        let request: Value = match serde_json::from_str(request) {
            Ok(req) => req,
            Err(e) => {
                let err = errors::RpcError::parse_error(format!("Invalid JSON: {e}"));
                return serde_json::to_string(&err.to_json(None))
                    .unwrap_or_else(|_| "{}".to_string());
            }
        };

        // Check if this is a batch request (array) or single request (object)
        if let Some(requests) = request.as_array() {
            // Batch request - process all requests in parallel
            return Self::process_batch_request(server, requests).await;
        }

        // Single request - process normally
        let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("");

        let params = request.get("params").cloned().unwrap_or_else(|| json!([]));
        let id = request.get("id");

        let result = server.call_method(method, params).await;

        match result {
            Ok(response) => {
                let response_str =
                    serde_json::to_string(&response).unwrap_or_else(|_| "null".to_string());
                let id_str = match id {
                    Some(id_val) => {
                        serde_json::to_string(id_val).unwrap_or_else(|_| "null".to_string())
                    }
                    None => "null".to_string(),
                };
                format!(r#"{{"jsonrpc":"2.0","result":{response_str},"id":{id_str}}}"#)
            }
            Err(e) => {
                serde_json::to_string(&e.to_json(id.cloned())).unwrap_or_else(|_| "{}".to_string())
            }
        }
    }

    /// Process a batch of JSON-RPC requests in parallel
    /// Maintains request order and handles errors per-request
    async fn process_batch_request(server: Arc<Self>, requests: &[Value]) -> String {
        // Empty batch returns empty array (JSON-RPC 2.0 spec)
        if requests.is_empty() {
            return "[]".to_string();
        }

        // Process all requests in parallel using tokio::task::spawn
        // Each request is processed independently, maintaining order
        let handles: Vec<_> = requests
            .iter()
            .enumerate()
            .map(|(index, req)| {
                let server_clone = Arc::clone(&server);
                let req_clone = req.clone();
                tokio::spawn(async move {
                    // Process each request
                    let method = req_clone
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or("");
                    let params = req_clone
                        .get("params")
                        .cloned()
                        .unwrap_or_else(|| json!([]));
                    let id = req_clone.get("id").cloned();

                    let result = server_clone.call_method(method, params).await;

                    // Build response maintaining original request ID
                    let response = match result {
                        Ok(response_value) => {
                            json!({
                                "jsonrpc": "2.0",
                                "result": response_value,
                                "id": id.unwrap_or(Value::Null)
                            })
                        }
                        Err(e) => {
                            // Error response maintains the request ID
                            e.to_json(id)
                        }
                    };

                    (index, response)
                })
            })
            .collect();

        // Wait for all requests to complete
        let mut results = Vec::new();
        for handle in handles {
            match handle.await {
                Ok(result) => results.push(result),
                Err(e) => {
                    // Task join error - create error response
                    error!("Task join error in batch request: {}", e);
                    // We can't recover the original request ID here, so we'll skip this response
                    // In practice, this should rarely happen
                }
            }
        }

        // Sort by original index to maintain request order
        results.sort_by_key(|(index, _)| *index);

        // Extract responses in order
        let responses: Vec<Value> = results.into_iter().map(|(_, response)| response).collect();

        // Return batch response as JSON array
        serde_json::to_string(&responses).unwrap_or_else(|_| "[]".to_string())
    }

    /// Call a specific RPC method
    async fn call_method(&self, method: &str, params: Value) -> Result<Value, errors::RpcError> {
        match method {
            // Blockchain methods
            "getblockchaininfo" => self
                .blockchain
                .get_blockchain_info()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getblock" => {
                let hash = crate::rpc::params::param_str(&params, 0).unwrap_or("");
                self.blockchain
                    .get_block(hash)
                    .await
                    .map_err(errors::rpc_error_from_blockchain_result)
            }
            "getblockhash" => {
                let height = crate::rpc::params::param_u64_default(&params, 0, 0);
                self.blockchain
                    .get_block_hash(height)
                    .await
                    .map_err(errors::rpc_error_from_blockchain_result)
            }
            "getblockheader" => {
                let hash = crate::rpc::params::param_str(&params, 0).unwrap_or("");
                let verbose = crate::rpc::params::param_bool_default(&params, 1, true);
                self.blockchain
                    .get_block_header(hash, verbose)
                    .await
                    .map_err(errors::rpc_error_from_blockchain_result)
            }
            "getbestblockhash" => self
                .blockchain
                .get_best_block_hash()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getblockcount" => self
                .blockchain
                .get_block_count()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getdifficulty" => self
                .blockchain
                .get_difficulty()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "gettxoutsetinfo" => self
                .blockchain
                .get_txoutset_info()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "loadtxoutset" => self
                .blockchain
                .load_txout_set(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "verifychain" => {
                let checklevel = crate::rpc::params::param_u64(&params, 0);
                let numblocks = crate::rpc::params::param_u64(&params, 1);
                self.blockchain
                    .verify_chain(checklevel, numblocks)
                    .await
                    .map_err(errors::rpc_error_from_blockchain_result)
            }
            "getchaintips" => self
                .blockchain
                .get_chain_tips()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getchaintxstats" => self
                .blockchain
                .get_chain_tx_stats(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getblockstats" => self
                .blockchain
                .get_block_stats(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "pruneblockchain" => self
                .blockchain
                .prune_blockchain(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getpruneinfo" => self
                .blockchain
                .get_prune_info(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "invalidateblock" => self
                .blockchain
                .invalidate_block(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "reconsiderblock" => self
                .blockchain
                .reconsider_block(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "waitfornewblock" => self
                .blockchain
                .wait_for_new_block(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "waitforblock" => self
                .blockchain
                .wait_for_block(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "waitforblockheight" => self
                .blockchain
                .wait_for_block_height(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),

            // Raw Transaction methods
            "getrawtransaction" => self.rawtx.getrawtransaction(&params).await,
            "sendrawtransaction" => self.rawtx.sendrawtransaction(&params).await,
            "testmempoolaccept" => self.rawtx.testmempoolaccept(&params).await,
            "decoderawtransaction" => self.rawtx.decoderawtransaction(&params).await,
            "createrawtransaction" => self.rawtx.createrawtransaction(&params).await,
            "gettxout" => self.rawtx.gettxout(&params).await,
            "gettxoutproof" => self.rawtx.gettxoutproof(&params).await,
            "verifytxoutproof" => self.rawtx.verifytxoutproof(&params).await,

            // Mempool methods
            "getmempoolinfo" => self.mempool.getmempoolinfo(&params).await,
            "getrawmempool" => self.mempool.getrawmempool(&params).await,
            "savemempool" => self.mempool.savemempool(&params).await,
            "getmempoolancestors" => self.mempool.getmempoolancestors(&params).await,
            "getmempooldescendants" => self.mempool.getmempooldescendants(&params).await,
            "getmempoolentry" => self.mempool.getmempoolentry(&params).await,

            // Network methods
            "getnetworkinfo" => self.network.get_network_info().await,
            "getpeerinfo" => self.network.get_peer_info().await,
            "getconnectioncount" => self.network.get_connection_count(&params).await,
            "ping" => self.network.ping(&params).await,
            "addnode" => self.network.add_node(&params).await,
            "disconnectnode" => self.network.disconnect_node(&params).await,
            "getnettotals" => self.network.get_net_totals(&params).await,
            "clearbanned" => self.network.clear_banned(&params).await,
            "setban" => self.network.set_ban(&params).await,
            "listbanned" => self.network.list_banned(&params).await,
            "getaddednodeinfo" => self.network.getaddednodeinfo(&params).await,
            "getnodeaddresses" => self.network.getnodeaddresses(&params).await,
            "setnetworkactive" => self.network.setnetworkactive(&params).await,

            // Mining methods
            "getmininginfo" => self.mining.get_mining_info().await,
            "getblocktemplate" => self.mining.get_block_template(&params).await,
            "generatetoaddress" => self.mining.generate_to_address(&params).await,
            "submitblock" => self.mining.submit_block(&params).await,
            "estimatesmartfee" => self.mining.estimate_smart_fee(&params).await,
            "prioritisetransaction" => self.mining.prioritise_transaction(&params).await,
            "getblockfilter" => self
                .blockchain
                .get_block_filter(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getindexinfo" => self
                .blockchain
                .get_index_info(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getblockchainstate" => self
                .blockchain
                .get_blockchain_state()
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "validateaddress" => self
                .blockchain
                .validate_address(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "getaddressinfo" => self
                .blockchain
                .get_address_info(&params)
                .await
                .map_err(errors::rpc_error_from_blockchain_result),
            "gettransactiondetails" => self.rawtx.get_transaction_details(&params).await,

            // Control methods
            "stop" => self.control.stop(&params).await,
            "uptime" => self.control.uptime(&params).await,
            "getmemoryinfo" => self.control.getmemoryinfo(&params).await,
            "getrpcinfo" => self.control.getrpcinfo(&params).await,
            "help" => self.control.help(&params).await,
            "logging" => self.control.logging(&params).await,
            "gethealth" => self.control.gethealth(&params).await,
            "getmetrics" => self.control.getmetrics(&params).await,
            "loadmodule" => self.control.loadmodule(&params).await,
            "unloadmodule" => self.control.unloadmodule(&params).await,
            "reloadmodule" => self.control.reloadmodule(&params).await,
            "listmodules" => self.control.listmodules(&params).await,
            "getmoduleclispecs" => self.control.getmoduleclispecs(&params).await,
            "runmodulecli" => self.control.runmodulecli(&params).await,
            // Payment methods (requires bip70-http feature)
            #[cfg(feature = "bip70-http")]
            "createpaymentrequest" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .create_payment_request(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "createcovenantproof" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .create_covenant_proof(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            "getpaymentstate" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .get_payment_state(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            "listpayments" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .list_payments(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            // Vault RPC methods
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "createvault" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .create_vault(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "getvaultstate" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .get_vault_state(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "unvault" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .unvault(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "withdrawfromvault" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .withdraw_from_vault(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            // Pool RPC methods
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "createpool" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .create_pool(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "getpoolstate" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .get_pool_state(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "joinpool" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .join_pool(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "distributepool" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .distribute_pool(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            // Congestion RPC methods
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "createbatch" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .create_batch(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "addtobatch" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .add_to_batch(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "getcongestion" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .get_congestion(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "getcongestionmetrics" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .get_congestion_metrics(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "bip70-http")]
            #[cfg(feature = "ctv")]
            "broadcastbatch" => {
                if let Some(ref payment_rpc) = self.payment {
                    payment_rpc
                        .broadcast_batch(&params)
                        .await
                        .map_err(|e| errors::RpcError::internal_error(e.to_string()))
                } else {
                    Err(errors::RpcError::internal_error(
                        "Payment RPC not available".to_string(),
                    ))
                }
            }
            #[cfg(feature = "miniscript")]
            "getdescriptorinfo" => miniscript_rpc::get_descriptor_info(&params)
                .await
                .map_err(|e| errors::RpcError::internal_error(e.to_string())),
            #[cfg(feature = "miniscript")]
            "analyzepsbt" => miniscript_rpc::analyze_psbt(&params)
                .await
                .map_err(|e| errors::RpcError::internal_error(e.to_string())),

            _ => {
                // Check module endpoints
                let endpoints = self.module_endpoints.read().await;
                if let Some(handler) = endpoints.get(method) {
                    handler.handle(params).await
                } else {
                    Err(errors::RpcError::method_not_found(method))
                }
            }
        }
    }

    /// Register a module RPC endpoint
    ///
    /// # Arguments
    /// * `method` - RPC method name (must have module prefix, e.g., "lightning_*")
    /// * `handler` - Handler implementation
    ///
    /// # Returns
    /// * `Ok(())` - Success
    /// * `Err(String)` - Error (e.g., method name conflicts with core endpoint)
    pub async fn register_module_endpoint(
        &self,
        method: String,
        handler: Arc<dyn ModuleRpcHandler>,
    ) -> Result<(), String> {
        // Check if method conflicts with core endpoints (see rpc/methods.rs)
        if crate::rpc::methods::CORE_RPC_METHODS.contains(&method.as_str()) {
            return Err(format!("Cannot override core RPC method: {method}"));
        }

        // Check module prefix (recommended but not enforced)
        if !method.contains('_') {
            tracing::warn!(
                "Module RPC method '{}' does not have module prefix (recommended: 'module_method')",
                method
            );
        }

        let mut endpoints = self.module_endpoints.write().await;
        endpoints.insert(method.clone(), handler);
        tracing::info!("Registered module RPC endpoint: {}", method);
        Ok(())
    }

    /// Unregister a module RPC endpoint
    pub async fn unregister_module_endpoint(&self, method: &str) -> Result<(), String> {
        let mut endpoints = self.module_endpoints.write().await;
        if endpoints.remove(method).is_some() {
            tracing::info!("Unregistered module RPC endpoint: {}", method);
            Ok(())
        } else {
            Err(format!("Module RPC endpoint not found: {method}"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpStream as TokioTcpStream;

    #[tokio::test]
    async fn test_rpc_server_creation() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let server = RpcServer::new(addr);
        assert_eq!(server.addr, addr);
    }

    #[tokio::test]
    async fn test_http_rpc_integration() {
        // Start server on random port
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let server_addr = listener.local_addr().unwrap();
        let server = Arc::new(RpcServer::new(server_addr));

        // Spawn server task using hyper
        let server_handle = tokio::spawn(async move {
            while let Ok((stream, addr)) = listener.accept().await {
                let peer_addr = addr;
                let server_clone = server.clone();
                tokio::spawn(async move {
                    let io = TokioIo::new(stream);
                    let service = service_fn(move |req| {
                        RpcServer::handle_http_request_with_server(
                            server_clone.clone(),
                            req,
                            peer_addr,
                        )
                    });
                    let _ = http1::Builder::new().serve_connection(io, service).await;
                });
            }
        });

        // Give server time to start
        tokio::time::sleep(RPC_SERVER_STARTUP_WAIT).await;

        // Connect to server
        let mut client = TokioTcpStream::connect(server_addr).await.unwrap();

        // Send HTTP POST request
        let json_body = r#"{"jsonrpc":"2.0","method":"ping","params":[],"id":1}"#;
        let http_request = format!(
            "POST / HTTP/1.1\r\n\
            Host: 127.0.0.1:18332\r\n\
            Content-Type: application/json\r\n\
            Content-Length: {}\r\n\
            \r\n\
            {}",
            json_body.len(),
            json_body
        );

        client.write_all(http_request.as_bytes()).await.unwrap();

        // Read response
        let mut response = vec![0u8; 4096];
        let n = tokio::time::timeout(RPC_CLIENT_READ_TIMEOUT, client.read(&mut response))
            .await
            .unwrap()
            .unwrap();

        let response_str = String::from_utf8_lossy(&response[..n]);

        // Verify HTTP response (hyper uses lowercase headers)
        assert!(
            response_str.contains("HTTP/1.1 200 OK") || response_str.contains("200 OK"),
            "Response: {response_str}"
        );
        assert!(
            response_str.contains("content-type: application/json")
                || response_str.contains("Content-Type: application/json")
        );
        assert!(response_str.contains("jsonrpc"));
        assert!(response_str.contains("\"result\""));

        server_handle.abort();
    }

    #[tokio::test]
    async fn test_process_request_valid_json() {
        let request = r#"{"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["result"].is_object());
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_process_request_invalid_json() {
        let request = "invalid json";
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["error"]["code"], -32700);
        assert!(
            response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("Parse error")
                || response["error"]["message"]
                    .as_str()
                    .unwrap()
                    .contains("Invalid JSON")
        );
    }

    #[tokio::test]
    async fn test_process_request_unknown_method() {
        let request = r#"{"jsonrpc":"2.0","method":"unknown_method","params":[],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["error"]["code"], -32601);
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Method not found"));
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_process_request_without_id() {
        let request = r#"{"jsonrpc":"2.0","method":"getblockchaininfo","params":[]}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["result"].is_object());
        assert_eq!(response["id"], serde_json::Value::Null);
    }

    #[tokio::test]
    async fn test_process_request_with_params() {
        let request = r#"{"jsonrpc":"2.0","method":"getblock","params":["000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        // Block may not be in storage (test doesn't set up storage)
        // If block found, result should be object; if not found, result should be null or error
        if response.get("error").is_some() {
            // Error response is valid when block not found
            assert!(response["error"].is_object());
        } else {
            // Success response should have object result
            assert!(response["result"].is_object() || response["result"].is_null());
        }
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_call_method_getblockchaininfo() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("getblockchaininfo", json!([])).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.get("chain").is_some());
    }

    #[tokio::test]
    async fn test_call_method_getblock() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let params = json!(["000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"]);
        let result = server.call_method("getblock", params).await;
        // Block may not be in storage (test doesn't set up storage)
        // This is expected - the method should return an error when block not found
        // The important thing is that the method doesn't panic
        if let Ok(response) = result {
            // If block was found, verify response structure
            assert!(response.get("hash").is_some());
        } else {
            // If block not found, that's expected without storage setup
            // Just verify it's a proper error response
            assert!(result.is_err());
        }
    }

    #[tokio::test]
    async fn test_call_method_getblockhash() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let params = json!([0]);
        let result = server.call_method("getblockhash", params).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.is_string());
    }

    #[tokio::test]
    async fn test_call_method_getrawtransaction() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let params = json!(["0000000000000000000000000000000000000000000000000000000000000000"]);
        let result = server.call_method("getrawtransaction", params).await;
        // getrawtransaction may fail if transaction is not found, which is acceptable in tests
        // The important thing is that it doesn't panic
        if let Ok(response) = result {
            // If it succeeds, check that it has expected structure
            assert!(response.is_object() || response.is_string());
        }
    }

    #[tokio::test]
    async fn test_call_method_getnetworkinfo() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("getnetworkinfo", json!([])).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.get("version").is_some());
    }

    #[tokio::test]
    async fn test_call_method_getpeerinfo() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("getpeerinfo", json!([])).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.is_array());
    }

    #[tokio::test]
    async fn test_call_method_getmininginfo() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("getmininginfo", json!([])).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.get("blocks").is_some());
    }

    #[tokio::test]
    async fn test_call_method_getblocktemplate() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("getblocktemplate", json!([])).await;
        // getblocktemplate may fail if chain state is not initialized, which is acceptable in tests
        // The important thing is that it doesn't panic
        if let Ok(response) = result {
            // If it succeeds, check that it has expected structure
            assert!(response.is_object() || response.is_string());
        }
    }

    #[tokio::test]
    async fn test_call_method_unknown_method() {
        let server = RpcServer::new("127.0.0.1:0".parse().unwrap());
        let result = server.call_method("unknown_method", json!([])).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Method not found"));
    }

    #[tokio::test]
    async fn test_json_rpc_2_0_compliance() {
        let request = r#"{"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["result"].is_object());
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_error_response_format() {
        let request = r#"{"jsonrpc":"2.0","method":"unknown_method","params":[],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["error"].is_object());
        assert!(response["error"]["code"].is_number());
        assert!(response["error"]["message"].is_string());
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_parse_error_response() {
        let request = "invalid json";
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["error"]["code"], -32700);
        assert!(
            response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("Parse error")
                || response["error"]["message"]
                    .as_str()
                    .unwrap()
                    .contains("Invalid JSON")
        );
    }

    #[tokio::test]
    async fn test_method_not_found_response() {
        let request = r#"{"jsonrpc":"2.0","method":"nonexistent","params":[],"id":42}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["error"]["code"], -32601);
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Method not found"));
        assert!(response["error"]["data"].is_string() || response["error"]["data"].is_null());
        assert_eq!(response["id"], 42);
    }

    #[tokio::test]
    async fn test_empty_params_handling() {
        let request = r#"{"jsonrpc":"2.0","method":"getblockchaininfo","id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["result"].is_object());
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_missing_method_handling() {
        let request = r#"{"jsonrpc":"2.0","params":[],"id":1}"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["error"]["code"], -32601);
        assert!(response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Method not found"));
        assert_eq!(response["id"], 1);
    }

    #[tokio::test]
    async fn test_blockchain_methods_integration() {
        let methods = vec![
            "getblockchaininfo",
            "getblock",
            "getblockhash",
            "getrawtransaction",
        ];

        for method in methods {
            let request = format!(r#"{{"jsonrpc":"2.0","method":"{method}","params":[],"id":1}}"#);
            let response_str = RpcServer::process_request(&request).await;
            let response: Value = serde_json::from_str(&response_str).unwrap();

            assert_eq!(response["jsonrpc"], "2.0");
            // Result may be an object, string, or null (if method failed)
            assert!(
                response["result"].is_object()
                    || response["result"].is_string()
                    || response["result"].is_null()
            );
            assert_eq!(response["id"], 1);
        }
    }

    #[tokio::test]
    async fn test_network_methods_integration() {
        let methods = vec!["getnetworkinfo", "getpeerinfo"];

        for method in methods {
            let request = format!(r#"{{"jsonrpc":"2.0","method":"{method}","params":[],"id":1}}"#);
            let response_str = RpcServer::process_request(&request).await;
            let response: Value = serde_json::from_str(&response_str).unwrap();

            assert_eq!(response["jsonrpc"], "2.0");
            assert!(response["result"].is_object() || response["result"].is_array());
            assert_eq!(response["id"], 1);
        }
    }

    #[tokio::test]
    async fn test_mining_methods_integration() {
        let methods = vec!["getmininginfo", "getblocktemplate"];

        for method in methods {
            let request = format!(r#"{{"jsonrpc":"2.0","method":"{method}","params":[],"id":1}}"#);
            let response_str = RpcServer::process_request(&request).await;
            let response: Value = serde_json::from_str(&response_str).unwrap();

            assert_eq!(response["jsonrpc"], "2.0");
            // Result may be an object, string, or null (if method failed due to missing dependencies)
            assert!(
                response["result"].is_object()
                    || response["result"].is_string()
                    || response["result"].is_null()
            );
            assert_eq!(response["id"], 1);
        }
    }

    #[tokio::test]
    async fn test_batch_request_empty() {
        let request = "[]";
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        assert_eq!(response.as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_batch_request_single() {
        let request = r#"[{"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1}]"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        let responses = response.as_array().unwrap();
        assert_eq!(responses.len(), 1);
        assert_eq!(responses[0]["jsonrpc"], "2.0");
        assert!(responses[0]["result"].is_object());
        assert_eq!(responses[0]["id"], 1);
    }

    #[tokio::test]
    async fn test_batch_request_multiple() {
        let request = r#"[
            {"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1},
            {"jsonrpc":"2.0","method":"getblockcount","params":[],"id":2},
            {"jsonrpc":"2.0","method":"getnetworkinfo","params":[],"id":3}
        ]"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        let responses = response.as_array().unwrap();
        assert_eq!(responses.len(), 3);

        // Verify order is maintained
        assert_eq!(responses[0]["id"], 1);
        assert_eq!(responses[1]["id"], 2);
        assert_eq!(responses[2]["id"], 3);

        // Verify all are successful
        assert!(responses[0]["result"].is_object());
        assert!(responses[1]["result"].is_number());
        assert!(responses[2]["result"].is_object());
    }

    #[tokio::test]
    async fn test_batch_request_with_errors() {
        let request = r#"[
            {"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1},
            {"jsonrpc":"2.0","method":"unknown_method","params":[],"id":2},
            {"jsonrpc":"2.0","method":"getblockcount","params":[],"id":3}
        ]"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        let responses = response.as_array().unwrap();
        assert_eq!(responses.len(), 3);

        // First request should succeed
        assert_eq!(responses[0]["id"], 1);
        assert!(responses[0]["result"].is_object());
        assert!(responses[0]["error"].is_null());

        // Second request should fail
        assert_eq!(responses[1]["id"], 2);
        assert!(responses[1]["result"].is_null());
        assert!(responses[1]["error"].is_object());
        assert_eq!(responses[1]["error"]["code"], -32601);

        // Third request should succeed
        assert_eq!(responses[2]["id"], 3);
        assert!(responses[2]["result"].is_number());
        assert!(responses[2]["error"].is_null());
    }

    #[tokio::test]
    async fn test_batch_request_order_preserved() {
        let request = r#"[
            {"jsonrpc":"2.0","method":"getblockcount","params":[],"id":3},
            {"jsonrpc":"2.0","method":"getblockchaininfo","params":[],"id":1},
            {"jsonrpc":"2.0","method":"getnetworkinfo","params":[],"id":2}
        ]"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        let responses = response.as_array().unwrap();
        assert_eq!(responses.len(), 3);

        // Order should match request order, not ID order
        assert_eq!(responses[0]["id"], 3);
        assert_eq!(responses[1]["id"], 1);
        assert_eq!(responses[2]["id"], 2);
    }

    #[tokio::test]
    async fn test_batch_request_without_ids() {
        let request = r#"[
            {"jsonrpc":"2.0","method":"getblockchaininfo","params":[]},
            {"jsonrpc":"2.0","method":"getblockcount","params":[]}
        ]"#;
        let response_str = RpcServer::process_request(request).await;
        let response: Value = serde_json::from_str(&response_str).unwrap();

        assert!(response.is_array());
        let responses = response.as_array().unwrap();
        assert_eq!(responses.len(), 2);

        // Both should have null IDs
        assert_eq!(responses[0]["id"], Value::Null);
        assert_eq!(responses[1]["id"], Value::Null);

        // Both should succeed
        assert!(responses[0]["result"].is_object());
        assert!(responses[1]["result"].is_number());
    }
}