ethrex-rpc 17.0.0

JSON-RPC and Engine API server for the ethrex Ethereum execution client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
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
use crate::authentication::authenticate;
use crate::debug::chain_config::ChainConfigRequest;
use crate::debug::execution_witness::ExecutionWitnessRequest;
use crate::debug::execution_witness_by_hash::ExecutionWitnessByBlockHashRequest;
use crate::engine::blobs::{BlobsV2Request, BlobsV3Request};
use crate::engine::client_version::GetClientVersionV1Request;
use crate::engine::payload::{
    GetPayloadV5Request, GetPayloadV6Request, NewPayloadV5Request, NewPayloadWithWitnessV5Request,
};
use crate::engine::{
    ExchangeCapabilitiesRequest,
    blobs::BlobsV1Request,
    exchange_transition_config::ExchangeTransitionConfigV1Req,
    fork_choice::{
        ForkChoiceUpdatedV1, ForkChoiceUpdatedV2, ForkChoiceUpdatedV3, ForkChoiceUpdatedV4,
    },
    payload::{
        GetPayloadBodiesByHashV1Request, GetPayloadBodiesByHashV2Request,
        GetPayloadBodiesByRangeV1Request, GetPayloadBodiesByRangeV2Request, GetPayloadV1Request,
        GetPayloadV2Request, GetPayloadV3Request, GetPayloadV4Request, NewPayloadV1Request,
        NewPayloadV2Request, NewPayloadV3Request, NewPayloadV4Request,
    },
};
use crate::eth::client::Config;
use crate::eth::{
    account::{
        GetBalanceRequest, GetCodeRequest, GetProofRequest, GetStorageAtRequest,
        GetTransactionCountRequest,
    },
    block::{
        BlockNumberRequest, GetBlobBaseFee, GetBlockByHashRequest, GetBlockByNumberRequest,
        GetBlockReceiptsRequest, GetBlockTransactionCountRequest, GetRawBlockRequest,
        GetRawHeaderRequest, GetRawReceipts,
    },
    block_access_list::BlockAccessListRequest,
    client::{ChainId, Syncing},
    fee_market::FeeHistoryRequest,
    filter::{self, ActiveFilters, DeleteFilterRequest, FilterChangesRequest, NewFilterRequest},
    gas_price::GasPrice,
    gas_tip_estimator::GasTipEstimator,
    logs::LogsFilter,
    transaction::{
        CallRequest, CreateAccessListRequest, EstimateGasRequest, GetRawTransaction,
        GetTransactionByBlockHashAndIndexRequest, GetTransactionByBlockNumberAndIndexRequest,
        GetTransactionByHashRequest, GetTransactionReceiptRequest,
    },
};
use crate::subscription_manager::{SubscriptionManager, SubscriptionManagerProtocol};
use crate::tracing::{TraceBlockByNumberRequest, TraceTransactionRequest};
use crate::types::transaction::SendRawTransactionRequest;
use crate::utils::{
    RpcErr, RpcErrorMetadata, RpcErrorResponse, RpcNamespace, RpcRequest, RpcRequestId,
    RpcSuccessResponse,
};
use crate::{admin, net};
use crate::{eth, mempool};
use axum::extract::ws::{Message, WebSocket};
use axum::extract::{DefaultBodyLimit, State, WebSocketUpgrade};
use axum::{Json, Router, http::StatusCode, routing::post};
use axum_extra::{
    TypedHeader,
    headers::{Authorization, authorization::Bearer},
};
use bytes::Bytes;
use ethrex_blockchain::Blockchain;
use ethrex_blockchain::error::ChainError;
use ethrex_common::types::Block;
use ethrex_common::types::block_access_list::BlockAccessList;
use ethrex_common::types::block_execution_witness::ExecutionWitness;
use ethrex_metrics::rpc::{RpcOutcome, record_async_duration, record_rpc_outcome};
use ethrex_p2p::peer_handler::PeerHandler;
use ethrex_p2p::sync_manager::SyncManager;
use ethrex_p2p::types::Node;
use ethrex_p2p::types::NodeRecord;
use ethrex_storage::Store;
use serde::Deserialize;
use serde_json::Value;
use spawned_concurrency::tasks::ActorRef;
use std::{
    collections::{HashMap, HashSet},
    future::IntoFuture,
    net::SocketAddr,
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::net::TcpListener;
use tokio::sync::{
    Mutex as TokioMutex,
    mpsc::{UnboundedSender, unbounded_channel},
    oneshot,
};
use tokio::time::timeout;
use tower_http::cors::CorsLayer;
use tracing::{error, info, warn};
use tracing_subscriber::{EnvFilter, Registry, reload};

#[cfg(all(feature = "jemalloc_profiling", target_os = "linux"))]
use axum::response::IntoResponse;
// only works on linux
#[cfg(all(feature = "jemalloc_profiling", target_os = "linux"))]
pub async fn handle_get_heap() -> Result<impl IntoResponse, (StatusCode, String)> {
    let Some(mutex) = jemalloc_pprof::PROF_CTL.as_ref() else {
        return Err((
            StatusCode::NOT_IMPLEMENTED,
            "jemalloc profiling is not available".into(),
        ));
    };
    let mut prof_ctl = mutex.lock().await;
    require_profiling_activated(&prof_ctl)?;
    let pprof = prof_ctl
        .dump_pprof()
        .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
    Ok(pprof)
}

/// Checks whether jemalloc profiling is activated an returns an error response if not.
#[cfg(all(feature = "jemalloc_profiling", target_os = "linux"))]
fn require_profiling_activated(
    prof_ctl: &jemalloc_pprof::JemallocProfCtl,
) -> Result<(), (StatusCode, String)> {
    if prof_ctl.activated() {
        Ok(())
    } else {
        Err((
            axum::http::StatusCode::FORBIDDEN,
            "heap profiling not activated".into(),
        ))
    }
}

#[cfg(all(feature = "jemalloc_profiling", target_os = "linux"))]
pub async fn handle_get_heap_flamegraph() -> Result<impl IntoResponse, (StatusCode, String)> {
    use axum::body::Body;
    use axum::http::header::CONTENT_TYPE;
    use axum::response::Response;

    let Some(mutex) = jemalloc_pprof::PROF_CTL.as_ref() else {
        return Err((
            StatusCode::NOT_IMPLEMENTED,
            "jemalloc profiling is not available".into(),
        ));
    };
    let mut prof_ctl = mutex.lock().await;
    require_profiling_activated(&prof_ctl)?;
    let svg = prof_ctl
        .dump_flamegraph()
        .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
    Response::builder()
        .header(CONTENT_TYPE, "image/svg+xml")
        .body(Body::from(svg))
        .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
}

// Feature-disabled stubs (no dependency on jemalloc_pprof)
#[cfg(not(all(feature = "jemalloc_profiling", target_os = "linux")))]
pub async fn handle_get_heap() -> Result<(), (StatusCode, String)> {
    Err((
        StatusCode::NOT_IMPLEMENTED,
        "jemalloc profiling is not available (build with `ethrex-rpc/jemalloc_profiling`, it only works on linux)".into(),
    ))
}

#[cfg(not(all(feature = "jemalloc_profiling", target_os = "linux")))]
pub async fn handle_get_heap_flamegraph() -> Result<(), (StatusCode, String)> {
    Err((
        StatusCode::NOT_IMPLEMENTED,
        "jemalloc profiling is not available (build with `ethrex-rpc/jemalloc_profiling`, it only works on linux)".into(),
    ))
}

/// Wrapper for JSON-RPC requests that can be either single or batched.
///
/// According to the JSON-RPC 2.0 specification, clients may send either a single
/// request object or an array of request objects (batch request).
#[derive(Deserialize)]
#[serde(untagged)]
pub enum RpcRequestWrapper {
    /// A single JSON-RPC request.
    Single(RpcRequest),
    /// A batch of JSON-RPC requests to be processed together.
    Multiple(Vec<RpcRequest>),
}

/// Channel message type for the block executor worker thread.
type BlockWorkerMessage = (
    oneshot::Sender<Result<Option<ExecutionWitness>, ChainError>>,
    Block,
    Option<BlockAccessList>,
    bool,
);

/// This struct contains all the dependencies that RPC handlers need to process requests,
/// including storage access, blockchain state, P2P networking, and configuration.
///
/// The context is cloned for each request, with most fields being cheap `Arc` references.
#[derive(Clone)]
pub struct RpcApiContext {
    /// Database storage for blocks, transactions, and state.
    pub storage: Store,
    /// Blockchain instance for block validation and execution.
    pub blockchain: Arc<Blockchain>,
    /// Active log filters for `eth_newFilter` / `eth_getFilterChanges` endpoints.
    pub active_filters: ActiveFilters,
    /// Sync manager for coordinating block synchronization (None for L2 nodes).
    pub syncer: Option<Arc<SyncManager>>,
    /// Peer handler for P2P network operations (None for L2 nodes).
    pub peer_handler: Option<PeerHandler>,
    /// Node identity and configuration data.
    pub node_data: NodeData,
    /// Gas tip estimator for `eth_gasPrice` and `eth_maxPriorityFeePerGas`.
    pub gas_tip_estimator: Arc<TokioMutex<GasTipEstimator>>,
    /// Handler for dynamically changing log filter levels via `admin_setLogLevel`.
    pub log_filter_handler: Option<reload::Handle<EnvFilter, Registry>>,
    /// Maximum gas limit for blocks (used in payload building).
    pub gas_ceil: u64,
    /// Channel for sending blocks to the block executor worker thread.
    pub block_worker_channel: UnboundedSender<BlockWorkerMessage>,
    /// WebSocket configuration. `None` when the WS server is disabled.
    pub ws: Option<WebSocketConfig>,
    /// Set of RPC namespaces that are allowed over the public HTTP/WS endpoints.
    ///
    /// Methods belonging to namespaces not in this set return `MethodNotFound`.
    /// The `engine` namespace is always served via the authenticated RPC port
    /// and is not gated here.
    pub allowed_namespaces: Arc<HashSet<RpcNamespace>>,
}

/// Configuration for the WebSocket RPC server.
#[derive(Clone)]
pub struct WebSocketConfig {
    /// Socket address the WS server listens on.
    pub addr: SocketAddr,
    /// Actor handle for managing `eth_subscribe` / `eth_unsubscribe` connections.
    pub subscription_manager: ActorRef<SubscriptionManager>,
}

impl std::fmt::Debug for RpcApiContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("RpcApiContext");
        s.field("storage", &self.storage)
            .field("blockchain", &self.blockchain)
            .field("syncer", &self.syncer.as_ref().map(|_| ".."))
            .field("peer_handler", &self.peer_handler.as_ref().map(|_| ".."))
            .field("gas_ceil", &self.gas_ceil);
        s.finish()
    }
}

/// Client version information used for identification in the Engine API and P2P.
///
/// This struct contains the individual components of the client version, which are
/// used by `engine_getClientVersionV1` and other identification endpoints.
///
/// Implements `Display` to return the pre-formatted version string.
#[derive(Debug, Clone)]
pub struct ClientVersion {
    /// Client name (e.g., "ethrex").
    pub name: String,
    /// Semantic version (e.g., "0.1.0").
    pub version: String,
    /// Git branch name (e.g., "main").
    pub branch: String,
    /// Git commit hash (full SHA).
    pub commit: String,
    /// OS and architecture (e.g., "x86_64-apple-darwin").
    pub os_arch: String,
    /// Rust compiler version (e.g., "1.70.0").
    pub rustc_version: String,
    /// Pre-formatted version string for efficient Display.
    formatted: String,
}

impl ClientVersion {
    /// Creates a new ClientVersion with all fields and a pre-formatted string.
    pub fn new(
        name: String,
        version: String,
        branch: String,
        commit: String,
        os_arch: String,
        rustc_version: String,
    ) -> Self {
        let formatted = format!(
            "{}/v{}-{}-{}/{}/rustc-v{}",
            name, version, branch, commit, os_arch, rustc_version
        );
        Self {
            name,
            version,
            branch,
            commit,
            os_arch,
            rustc_version,
            formatted,
        }
    }
}

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

/// Node identity and configuration information.
///
/// Contains the node's cryptographic identity, network endpoints, and metadata
/// used for P2P discovery and RPC responses.
#[derive(Debug, Clone)]
pub struct NodeData {
    /// JWT secret for authenticating Engine API requests from consensus clients.
    pub jwt_secret: Bytes,
    /// Local P2P node identity (public key and address).
    pub local_p2p_node: Node,
    /// ENR (Ethereum Node Record) for node discovery.
    pub local_node_record: NodeRecord,
    /// Client version information.
    pub client_version: ClientVersion,
    /// Extra data included in mined blocks.
    pub extra_data: Bytes,
}

/// Trait for implementing JSON-RPC method handlers.
///
/// Each RPC method (e.g., `eth_getBalance`, `engine_newPayloadV3`) is implemented
/// as a struct that implements this trait. The trait provides a standard pattern
/// for parsing parameters and handling requests.
///
/// # Example
///
/// ```ignore
/// struct GetBalanceRequest {
///     address: Address,
///     block: BlockId,
/// }
///
/// impl RpcHandler for GetBalanceRequest {
///     fn parse(params: &Option<Vec<Value>>) -> Result<Self, RpcErr> {
///         let params = params.as_ref().ok_or(RpcErr::MissingParam("params"))?;
///         Ok(Self {
///             address: serde_json::from_value(params[0].clone())?,
///             block: serde_json::from_value(params[1].clone())?,
///         })
///     }
///
///     async fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr> {
///         let balance = context.storage.get_balance(self.address, self.block)?;
///         Ok(serde_json::to_value(balance)?)
///     }
/// }
/// ```
#[allow(async_fn_in_trait)]
pub trait RpcHandler: Sized {
    /// Parse JSON-RPC parameters into the handler struct.
    ///
    /// Returns an error if required parameters are missing or have invalid types.
    fn parse(params: &Option<Vec<Value>>) -> Result<Self, RpcErr>;

    /// Entry point for handling an RPC request.
    ///
    /// This method parses the request, records metrics, and delegates to `handle()`.
    /// Most implementations should not override this method.
    async fn call(req: &RpcRequest, context: RpcApiContext) -> Result<Value, RpcErr> {
        let request = Self::parse(&req.params)?;
        let namespace = match req.namespace() {
            Ok(RpcNamespace::Engine) => "engine",
            _ => "rpc",
        };
        let method = req.method.as_str();

        let result =
            record_async_duration(
                namespace,
                method,
                async move { request.handle(context).await },
            )
            .await;

        let outcome = match &result {
            Ok(_) => RpcOutcome::Success,
            Err(err) => RpcOutcome::Error(get_error_kind(err)),
        };
        record_rpc_outcome(namespace, method, outcome);

        result
    }

    /// Handle the RPC request and return a JSON response.
    ///
    /// This is where the actual business logic for the RPC method lives.
    async fn handle(&self, context: RpcApiContext) -> Result<Value, RpcErr>;
}

fn get_error_kind(err: &RpcErr) -> &'static str {
    match err {
        RpcErr::MethodNotFound(_) => "MethodNotFound",
        RpcErr::WrongParam(_) => "WrongParam",
        RpcErr::BadParams(_) => "BadParams",
        RpcErr::InvalidRequest(_) => "InvalidRequest",
        RpcErr::MissingParam(_) => "MissingParam",
        RpcErr::TooLargeRequest => "TooLargeRequest",
        RpcErr::BadHexFormat(_) => "BadHexFormat",
        RpcErr::UnsupportedFork(_) => "UnsupportedFork",
        RpcErr::Internal(_) => "Internal",
        RpcErr::Vm(_) => "Vm",
        RpcErr::Revert { .. } => "Revert",
        RpcErr::Halt { .. } => "Halt",
        RpcErr::AuthenticationError(_) => "AuthenticationError",
        RpcErr::InvalidForkChoiceState(_) => "InvalidForkChoiceState",
        RpcErr::InvalidPayloadAttributes(_) => "InvalidPayloadAttributes",
        RpcErr::TooDeepReorg(_) => "TooDeepReorg",
        RpcErr::UnknownPayload(_) => "UnknownPayload",
        RpcErr::InvalidProofFormat(_) => "InvalidProofFormat",
        RpcErr::InvalidHeaderFormat(_) => "InvalidHeaderFormat",
        RpcErr::InvalidPayload(_) => "InvalidPayload",
        RpcErr::ProofGenerationUnavailable(_) => "ProofGenerationUnavailable",
    }
}

/// Duration after which inactive filters are cleaned up.
///
/// Filters created via `eth_newFilter` are automatically removed if not
/// accessed within this duration. In tests, this is set to 1 second for
/// faster test execution.
pub const FILTER_DURATION: Duration = {
    if cfg!(test) {
        Duration::from_secs(1)
    } else {
        Duration::from_secs(5 * 60)
    }
};

/// Spawns a dedicated thread for sequential block execution.
///
/// Blocks received from the consensus client via `engine_newPayload` are sent
/// to this worker thread for execution. This ensures blocks are processed
/// sequentially and prevents the async runtime from being blocked by CPU-intensive
/// block execution.
///
/// # Returns
///
/// An unbounded channel sender for submitting blocks. Each submission includes
/// a oneshot channel for receiving the execution result.
///
/// # Panics
///
/// Panics if the worker thread cannot be spawned.
pub fn start_block_executor(blockchain: Arc<Blockchain>) -> UnboundedSender<BlockWorkerMessage> {
    let (block_worker_channel, mut block_receiver) = unbounded_channel::<BlockWorkerMessage>();
    std::thread::Builder::new()
        .name("block_executor".to_string())
        .spawn(move || {
            while let Some((notify, block, bal, make_witness)) = block_receiver.blocking_recv() {
                let result = (|| {
                    if make_witness {
                        let witness =
                            blockchain.add_block_pipeline_with_witness(block, bal.as_ref())?;
                        Ok(Some(witness))
                    } else {
                        blockchain.add_block_pipeline(block, bal.as_ref())?;
                        Ok(None)
                    }
                })();
                let _ = notify
                    .send(result)
                    .inspect_err(|_| tracing::error!("failed to notify caller"));
            }
        })
        .expect("Falied to spawn block_executor thread");
    block_worker_channel
}

/// Starts the JSON-RPC API servers.
///
/// This function initializes and runs up to three server endpoints:
///
/// 1. **HTTP Server** (`http_addr`): Public JSON-RPC endpoint for standard Ethereum
///    methods (`eth_*`, `debug_*`, `net_*`, `admin_*`, `web3_*`, `txpool_*`).
///
/// 2. **WebSocket Server** (`ws`): Optional endpoint that serves the same methods as
///    HTTP plus the subscription methods `eth_subscribe` / `eth_unsubscribe` (currently
///    only `"newHeads"` is supported). Enabled by passing a [`WebSocketConfig`]
///    containing the listen address and the [`SubscriptionManager`] actor handle.
///
/// 3. **Auth RPC Server** (`authrpc_addr`): JWT-authenticated endpoint for Engine API
///    methods (`engine_*`) used by consensus clients.
///
/// # Arguments
///
/// * `http_addr` - Socket address for the HTTP server (e.g., `127.0.0.1:8545`)
/// * `ws` - Optional [`WebSocketConfig`] with the WS listen address and the
///   [`SubscriptionManager`] actor handle. `None` disables the WebSocket server.
/// * `authrpc_addr` - Socket address for authenticated Engine API (e.g., `127.0.0.1:8551`)
/// * `storage` - Database storage instance
/// * `blockchain` - Blockchain instance for block operations
/// * `jwt_secret` - JWT secret for Engine API authentication
/// * `local_p2p_node` - Local node identity for P2P networking
/// * `local_node_record` - ENR for node discovery
/// * `syncer` - Sync manager for block synchronization
/// * `peer_handler` - Handler for P2P peer operations
/// * `client_version` - Client version information for `web3_clientVersion` and `engine_getClientVersionV1`
/// * `log_filter_handler` - Optional handler for dynamic log level changes
/// * `gas_ceil` - Maximum gas limit for payload building
/// * `extra_data` - Extra data to include in mined blocks
///
/// # Errors
///
/// Returns an error if any server fails to bind to its address.
///
/// # Shutdown
///
/// All servers shut down gracefully on SIGINT (Ctrl+C).
#[allow(clippy::too_many_arguments)]
pub async fn start_api(
    http_addr: SocketAddr,
    ws: Option<WebSocketConfig>,
    authrpc_addr: SocketAddr,
    storage: Store,
    blockchain: Arc<Blockchain>,
    jwt_secret: Bytes,
    local_p2p_node: Node,
    local_node_record: NodeRecord,
    syncer: SyncManager,
    peer_handler: PeerHandler,
    client_version: ClientVersion,
    log_filter_handler: Option<reload::Handle<EnvFilter, Registry>>,
    gas_ceil: u64,
    extra_data: String,
    allowed_namespaces: HashSet<RpcNamespace>,
) -> Result<(), RpcErr> {
    // TODO: Refactor how filters are handled,
    // filters are used by the filters endpoints (eth_newFilter, eth_getFilterChanges, ...etc)
    let active_filters = Arc::new(Mutex::new(HashMap::new()));
    let block_worker_channel = start_block_executor(blockchain.clone());
    let service_context = RpcApiContext {
        storage,
        blockchain,
        active_filters: active_filters.clone(),
        syncer: Some(Arc::new(syncer)),
        peer_handler: Some(peer_handler),
        node_data: NodeData {
            jwt_secret,
            local_p2p_node,
            local_node_record,
            client_version,
            extra_data: extra_data.into(),
        },
        gas_tip_estimator: Arc::new(TokioMutex::new(GasTipEstimator::new())),
        log_filter_handler,
        gas_ceil,
        block_worker_channel,
        ws: ws.clone(),
        allowed_namespaces: Arc::new(allowed_namespaces),
    };

    // Periodically clean up the active filters for the filters endpoints.
    tokio::task::spawn(async move {
        let mut interval = tokio::time::interval(FILTER_DURATION);
        let filters = active_filters.clone();
        loop {
            interval.tick().await;
            tracing::debug!("Running filter clean task");
            filter::clean_outdated_filters(filters.clone(), FILTER_DURATION);
            tracing::debug!("Filter clean task complete");
        }
    });

    // All request headers allowed.
    // All methods allowed.
    // All origins allowed.
    // All headers exposed.
    let cors = CorsLayer::permissive();

    let http_router = Router::new()
        .route("/debug/pprof/allocs", axum::routing::get(handle_get_heap))
        .route(
            "/debug/pprof/allocs/flamegraph",
            axum::routing::get(handle_get_heap_flamegraph),
        )
        .route("/", post(handle_http_request))
        .layer(cors.clone())
        .with_state(service_context.clone());
    let http_listener = TcpListener::bind(http_addr)
        .await
        .map_err(|error| RpcErr::Internal(error.to_string()))?;
    let http_server = axum::serve(http_listener, http_router)
        .with_graceful_shutdown(shutdown_signal())
        .into_future();
    info!("Starting HTTP server at {http_addr}");

    let (timer_sender, mut timer_receiver) = tokio::sync::watch::channel(());

    tokio::spawn(async move {
        loop {
            let result = timeout(Duration::from_secs(30), timer_receiver.changed()).await;
            if result.is_err() {
                warn!("No messages from the consensus layer. Is the consensus client running?");
            }
        }
    });

    let authrpc_handler = move |ctx, auth, body| async move {
        let _ = timer_sender.send(());
        handle_authrpc_request(ctx, auth, body).await
    };

    let authrpc_router = Router::new()
        .route("/", post(authrpc_handler))
        .with_state(service_context.clone())
        // Bump the body limit for the engine API to 256MB
        // This is needed to receive payloads bigger than the default limit of 2MB
        .layer(DefaultBodyLimit::max(256 * 1024 * 1024));

    let authrpc_listener = TcpListener::bind(authrpc_addr)
        .await
        .map_err(|error| RpcErr::Internal(error.to_string()))?;
    let authrpc_server = axum::serve(authrpc_listener, authrpc_router)
        .with_graceful_shutdown(shutdown_signal())
        .into_future();
    info!("Starting Auth-RPC server at {authrpc_addr}");

    if let Some(ref ws_config) = ws {
        let ws_handler = |ws: WebSocketUpgrade, State(ctx): State<RpcApiContext>| async move {
            ws.on_upgrade(|mut socket| async move {
                handle_websocket(&mut socket, &ctx, |req| {
                    let c = ctx.clone();
                    async move { map_http_requests(&req, c).await }
                })
                .await;
            })
        };
        let ws_router = Router::new()
            .route("/", axum::routing::any(ws_handler))
            .layer(cors)
            .with_state(service_context);
        let ws_listener = TcpListener::bind(ws_config.addr)
            .await
            .map_err(|error| RpcErr::Internal(error.to_string()))?;
        let ws_server = axum::serve(ws_listener, ws_router)
            .with_graceful_shutdown(shutdown_signal())
            .into_future();
        info!("Starting WS server at {}", ws_config.addr);

        let _ = tokio::try_join!(authrpc_server, http_server, ws_server)
            .inspect_err(|e| error!("Error shutting down servers: {e:?}"));
    } else {
        let _ = tokio::try_join!(authrpc_server, http_server)
            .inspect_err(|e| error!("Error shutting down servers: {e:?}"));
    }

    Ok(())
}

/// Returns a future that completes when SIGINT (Ctrl+C) is received.
///
/// Used to implement graceful shutdown for all RPC servers.
pub async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install Ctrl+C handler");
}

/// Maximum number of requests accepted in a single JSON-RPC batch on either
/// the public HTTP port or the engine auth port. Matches geth's
/// `--engine.batchitemlimit` default. Larger batches are rejected up front
/// with `-32600 InvalidRequest` before any per-request work runs.
const MAX_BATCH_SIZE: usize = 1000;

/// JSON-RPC 2.0 §5.1: when the request body is not a valid Request object the
/// response id MUST be null. Build these transport-level errors directly so we
/// don't have to encode "no id" through `RpcRequestId`.
fn null_id_error(err: RpcErr) -> Value {
    let meta: RpcErrorMetadata = err.into();
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": Value::Null,
        "error": meta,
    })
}

/// Validate a batch envelope. Returns `Some(error_value)` for empty or
/// oversize batches (short-circuits dispatch), `None` if the request is
/// ok to process.
fn validate_batch(wrapper: &RpcRequestWrapper) -> Option<Value> {
    let RpcRequestWrapper::Multiple(requests) = wrapper else {
        return None;
    };
    if requests.is_empty() {
        return Some(null_id_error(RpcErr::InvalidRequest(
            "empty batch is not a valid Request".to_string(),
        )));
    }
    if requests.len() > MAX_BATCH_SIZE {
        return Some(null_id_error(RpcErr::InvalidRequest(format!(
            "batch too large: {} > {MAX_BATCH_SIZE}",
            requests.len()
        ))));
    }
    None
}

pub(crate) async fn handle_http_request(
    State(service_context): State<RpcApiContext>,
    body: String,
) -> Result<Json<Value>, StatusCode> {
    let wrapper: RpcRequestWrapper = match serde_json::from_str(&body) {
        Ok(w) => w,
        Err(_) => {
            return Ok(Json(
                rpc_response(
                    RpcRequestId::String("".to_string()),
                    Err(RpcErr::BadParams("Invalid request body".to_string())),
                )
                .map_err(|_| StatusCode::BAD_REQUEST)?,
            ));
        }
    };

    if let Some(err) = validate_batch(&wrapper) {
        return Ok(Json(err));
    }

    let res = match wrapper {
        RpcRequestWrapper::Single(request) => {
            let res = map_http_requests(&request, service_context).await;
            rpc_response(request.id, res).map_err(|_| StatusCode::BAD_REQUEST)?
        }
        RpcRequestWrapper::Multiple(requests) => {
            let mut responses = Vec::with_capacity(requests.len());
            for req in requests {
                let res = map_http_requests(&req, service_context.clone()).await;
                responses.push(rpc_response(req.id, res).map_err(|_| StatusCode::BAD_REQUEST)?);
            }
            serde_json::to_value(responses).map_err(|_| StatusCode::BAD_REQUEST)?
        }
    };
    Ok(Json(res))
}

pub async fn handle_authrpc_request(
    State(service_context): State<RpcApiContext>,
    auth_header: Option<TypedHeader<Authorization<Bearer>>>,
    body: String,
) -> Result<Json<Value>, StatusCode> {
    let wrapper: RpcRequestWrapper = match serde_json::from_str(&body) {
        Ok(w) => w,
        Err(_) => {
            return Ok(Json(null_id_error(RpcErr::InvalidRequest(
                "could not parse JSON-RPC request body".to_string(),
            ))));
        }
    };

    // Reject empty / oversize batches before any auth or dispatch work so a
    // 100k-request body can't burn JWT crypto or memory.
    if let Some(err) = validate_batch(&wrapper) {
        return Ok(Json(err));
    }

    if let Err(error) = authenticate(&service_context.node_data.jwt_secret, auth_header) {
        // Auth failed: respond before dispatching anything. For batches, mirror
        // the batch shape and emit one error response per request so clients
        // can still correlate by id.
        let error_meta: RpcErrorMetadata = error.into();
        let res = match wrapper {
            RpcRequestWrapper::Single(req) => serde_json::json!({
                "jsonrpc": "2.0",
                "id": req.id,
                "error": error_meta,
            }),
            RpcRequestWrapper::Multiple(requests) => {
                let mut responses = Vec::with_capacity(requests.len());
                for req in requests {
                    responses.push(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": req.id,
                        "error": error_meta.clone(),
                    }));
                }
                serde_json::to_value(responses).map_err(|_| StatusCode::BAD_REQUEST)?
            }
        };
        return Ok(Json(res));
    }

    let res = match wrapper {
        RpcRequestWrapper::Single(req) => {
            let res = map_authrpc_requests(&req, service_context).await;
            rpc_response(req.id, res).map_err(|_| StatusCode::BAD_REQUEST)?
        }
        RpcRequestWrapper::Multiple(requests) => {
            let mut responses = Vec::with_capacity(requests.len());
            for req in requests {
                let res = map_authrpc_requests(&req, service_context.clone()).await;
                responses.push(rpc_response(req.id, res).map_err(|_| StatusCode::BAD_REQUEST)?);
            }
            serde_json::to_value(responses).map_err(|_| StatusCode::BAD_REQUEST)?
        }
    };
    Ok(Json(res))
}

/// Handle a WebSocket connection.
///
/// Supports eth_subscribe / eth_unsubscribe for "newHeads" in addition to
/// regular JSON-RPC request-response calls that work the same as over HTTP.
///
/// The `route_request` closure handles non-subscription JSON-RPC methods.
/// L1 passes its own `map_http_requests`; L2 passes its variant so that
/// L2-specific methods (e.g. `ethrexL2_*`) are reachable over WebSocket.
pub async fn handle_websocket<F, Fut, E>(
    socket: &mut WebSocket,
    context: &RpcApiContext,
    route_request: F,
) where
    F: Fn(RpcRequest) -> Fut,
    Fut: std::future::Future<Output = Result<Value, E>>,
    E: Into<RpcErrorMetadata>,
{
    let (out_tx, mut out_rx) = tokio::sync::mpsc::channel::<String>(
        crate::subscription_manager::SUBSCRIBER_CHANNEL_CAPACITY,
    );
    // Currently only "newHeads" subscriptions are supported. When additional
    // subscription types (e.g., "logs", "newPendingTransactions") are added,
    // the subscription tracking below will need per-type handling.
    let mut subscription_ids: Vec<String> = Vec::new();

    loop {
        tokio::select! {
            msg = socket.recv() => {
                let Some(msg) = msg else { break };
                let body = match msg {
                    Ok(Message::Text(text)) => text.to_string(),
                    Ok(Message::Close(_)) => break,
                    Ok(_) => continue,
                    Err(_) => break,
                };

                let response = handle_ws_request(
                    &body, context, &out_tx, &mut subscription_ids, &route_request,
                ).await;
                if let Some(resp) = response
                    && socket.send(Message::Text(resp.into())).await.is_err()
                {
                    break;
                }
            }

            Some(msg) = out_rx.recv() => {
                if socket.send(Message::Text(msg.into())).await.is_err() {
                    break;
                }
            }
        }
    }

    if let Some(ws) = &context.ws {
        for id in subscription_ids {
            let _ = ws.subscription_manager.unsubscribe(id).await;
        }
    }
}

async fn handle_ws_request<F, Fut, E>(
    body: &str,
    context: &RpcApiContext,
    out_tx: &tokio::sync::mpsc::Sender<String>,
    subscription_ids: &mut Vec<String>,
    route_request: &F,
) -> Option<String>
where
    F: Fn(RpcRequest) -> Fut,
    Fut: std::future::Future<Output = Result<Value, E>>,
    E: Into<RpcErrorMetadata>,
{
    // Parse as raw JSON first so we can distinguish between:
    //   -32700 Parse error (malformed JSON)
    //   -32600 Invalid Request (valid JSON, but not a valid JSON-RPC request object)
    let parsed: Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return Some(ws_error_response(None, -32700, "Parse error")),
    };

    // Accept both a single request and a batch (array), matching HTTP behavior.
    let wrapper: RpcRequestWrapper = match serde_json::from_value(parsed) {
        Ok(w) => w,
        Err(_) => return Some(ws_error_response(None, -32600, "Invalid Request")),
    };

    match wrapper {
        RpcRequestWrapper::Single(req) => {
            let resp =
                process_ws_request(req, context, out_tx, subscription_ids, route_request).await?;
            Some(resp.to_string())
        }
        RpcRequestWrapper::Multiple(reqs) => {
            // Per JSON-RPC 2.0 spec, an empty batch is an invalid request.
            if reqs.is_empty() {
                return Some(ws_error_response(None, -32600, "Invalid Request"));
            }
            let mut responses = Vec::with_capacity(reqs.len());
            for req in reqs {
                if let Some(resp) =
                    process_ws_request(req, context, out_tx, subscription_ids, route_request).await
                {
                    responses.push(resp);
                }
            }
            if responses.is_empty() {
                None
            } else {
                serde_json::to_string(&responses).ok()
            }
        }
    }
}

async fn process_ws_request<F, Fut, E>(
    req: RpcRequest,
    context: &RpcApiContext,
    out_tx: &tokio::sync::mpsc::Sender<String>,
    subscription_ids: &mut Vec<String>,
    route_request: &F,
) -> Option<Value>
where
    F: Fn(RpcRequest) -> Fut,
    Fut: std::future::Future<Output = Result<Value, E>>,
    E: Into<RpcErrorMetadata>,
{
    match req.method.as_str() {
        "eth_subscribe" | "eth_unsubscribe" => {
            // Subscriptions are part of the `eth` namespace and must obey the
            // same `--http.api` allowlist as regular `eth_*` requests; otherwise
            // a node started with e.g. `--http.api web3` would still expose
            // `eth_subscribe("newHeads")` over WS.
            if !context.allowed_namespaces.contains(&RpcNamespace::Eth) {
                let err: Result<Value, RpcErr> = Err(RpcErr::MethodNotFound(req.method.clone()));
                return rpc_response(req.id, err).ok();
            }
            let result = if req.method == "eth_subscribe" {
                handle_eth_subscribe(&req, context, out_tx, subscription_ids).await
            } else {
                handle_eth_unsubscribe(&req, context, subscription_ids).await
            };
            rpc_response(req.id, result).ok()
        }
        _ => {
            let id = req.id.clone();
            let res = route_request(req).await;
            rpc_response(id, res).ok()
        }
    }
}

/// Build a JSON-RPC 2.0 error response. Used for transport-level errors
/// (parse error, invalid request) where the request ID is unknown.
fn ws_error_response(id: Option<RpcRequestId>, code: i32, message: &str) -> String {
    let id = match id {
        Some(id) => serde_json::to_value(id).unwrap_or(Value::Null),
        None => Value::Null,
    };
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message },
    })
    .to_string()
}

/// Handle `eth_subscribe`.
///
/// Only `"newHeads"` is supported. Registers this connection with the
/// `SubscriptionManager` actor and returns the subscription ID.
pub async fn handle_eth_subscribe(
    req: &crate::utils::RpcRequest,
    context: &RpcApiContext,
    out_tx: &tokio::sync::mpsc::Sender<String>,
    subscription_ids: &mut Vec<String>,
) -> Result<Value, RpcErr> {
    use crate::subscription_manager::MAX_SUBSCRIPTIONS_PER_CONNECTION;

    let params = req.params.as_deref().unwrap_or(&[]);
    let sub_type = params.first().and_then(|v| v.as_str()).ok_or_else(|| {
        RpcErr::BadParams("eth_subscribe requires a subscription type parameter".to_string())
    })?;

    if subscription_ids.len() >= MAX_SUBSCRIPTIONS_PER_CONNECTION {
        return Err(RpcErr::BadParams(format!(
            "Too many subscriptions (max {MAX_SUBSCRIPTIONS_PER_CONNECTION})"
        )));
    }

    match sub_type {
        "newHeads" => {
            let ws = context
                .ws
                .as_ref()
                .ok_or_else(|| RpcErr::Internal("WebSocket server not enabled".to_string()))?;

            let id = ws
                .subscription_manager
                .subscribe(out_tx.clone())
                .await
                .map_err(|e| RpcErr::Internal(format!("Subscription failed: {e}")))?
                .ok_or_else(|| RpcErr::Internal("Global subscription cap reached".to_string()))?;

            subscription_ids.push(id.clone());
            Ok(Value::String(id))
        }
        other => Err(RpcErr::BadParams(format!(
            "Unsupported subscription type: {other}"
        ))),
    }
}

/// Handle `eth_unsubscribe`.
///
/// Delegates to the [`SubscriptionManager`] actor and returns `true` if the
/// subscription was found and removed, `false` otherwise.
pub async fn handle_eth_unsubscribe(
    req: &crate::utils::RpcRequest,
    context: &RpcApiContext,
    subscription_ids: &mut Vec<String>,
) -> Result<Value, RpcErr> {
    let params = req.params.as_deref().unwrap_or(&[]);
    let sub_id = params
        .first()
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            RpcErr::BadParams("eth_unsubscribe requires a subscription ID parameter".to_string())
        })?
        .to_string();

    // Only unsubscribe if the requested ID belongs to this connection.
    let Some(pos) = subscription_ids.iter().position(|id| id == &sub_id) else {
        return Ok(Value::Bool(false));
    };

    let removed = if let Some(ref ws) = context.ws {
        ws.subscription_manager
            .unsubscribe(sub_id)
            .await
            .unwrap_or(false)
    } else {
        false
    };

    if removed {
        subscription_ids.swap_remove(pos);
    }

    Ok(Value::Bool(removed))
}

/// Handle requests that can come from either clients or other users
pub async fn map_http_requests(req: &RpcRequest, context: RpcApiContext) -> Result<Value, RpcErr> {
    let namespace = match req.namespace() {
        Ok(ns) => ns,
        Err(rpc_err) => return Err(rpc_err),
    };
    if !context.allowed_namespaces.contains(&namespace) {
        return Err(RpcErr::MethodNotFound(req.method.clone()));
    }
    match namespace {
        RpcNamespace::Eth => map_eth_requests(req, context).await,
        RpcNamespace::Admin => map_admin_requests(req, context).await,
        RpcNamespace::Debug => map_debug_requests(req, context).await,
        RpcNamespace::Web3 => map_web3_requests(req, context),
        RpcNamespace::Net => map_net_requests(req, context).await,
        RpcNamespace::Mempool => map_mempool_requests(req, context),
        // Engine is served on the authenticated port only. The CLI parser
        // already rejects `--http.api engine`, but `allowed_namespaces` can
        // also be built programmatically (e.g. in tests or future call sites),
        // so HTTP dispatch must refuse Engine even if it ends up in the set.
        RpcNamespace::Engine => Err(RpcErr::MethodNotFound(req.method.clone())),
    }
}

/// Handle requests from consensus client
pub async fn map_authrpc_requests(
    req: &RpcRequest,
    context: RpcApiContext,
) -> Result<Value, RpcErr> {
    match req.namespace() {
        Ok(RpcNamespace::Engine) => map_engine_requests(req, context).await,
        Ok(RpcNamespace::Eth) => map_eth_requests(req, context).await,
        _ => Err(RpcErr::MethodNotFound(req.method.clone())),
    }
}

/// Routes `eth_*` namespace requests to their handlers.
///
/// Handles all standard Ethereum JSON-RPC methods including:
/// - Account queries: `eth_getBalance`, `eth_getCode`, `eth_getStorageAt`, `eth_getTransactionCount`
/// - Block queries: `eth_getBlockByNumber`, `eth_getBlockByHash`, `eth_blockNumber`
/// - Transaction operations: `eth_sendRawTransaction`, `eth_getTransactionByHash`, `eth_getTransactionReceipt`
/// - Gas estimation: `eth_estimateGas`, `eth_gasPrice`, `eth_maxPriorityFeePerGas`, `eth_feeHistory`
/// - Filters: `eth_newFilter`, `eth_getFilterChanges`, `eth_uninstallFilter`, `eth_getLogs`
/// - Misc: `eth_chainId`, `eth_syncing`, `eth_createAccessList`, `eth_getProof`
pub async fn map_eth_requests(req: &RpcRequest, context: RpcApiContext) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "eth_chainId" => ChainId::call(req, context).await,
        "eth_syncing" => Syncing::call(req, context).await,
        "eth_getBlockByNumber" => GetBlockByNumberRequest::call(req, context).await,
        "eth_getBlockByHash" => GetBlockByHashRequest::call(req, context).await,
        "eth_getBalance" => GetBalanceRequest::call(req, context).await,
        "eth_getCode" => GetCodeRequest::call(req, context).await,
        "eth_getStorageAt" => GetStorageAtRequest::call(req, context).await,
        "eth_getBlockTransactionCountByNumber" => {
            GetBlockTransactionCountRequest::call(req, context).await
        }
        "eth_getBlockTransactionCountByHash" => {
            GetBlockTransactionCountRequest::call(req, context).await
        }
        "eth_getTransactionByBlockNumberAndIndex" => {
            GetTransactionByBlockNumberAndIndexRequest::call(req, context).await
        }
        "eth_getTransactionByBlockHashAndIndex" => {
            GetTransactionByBlockHashAndIndexRequest::call(req, context).await
        }
        "eth_getBlockReceipts" => GetBlockReceiptsRequest::call(req, context).await,
        "eth_getBlockAccessList" => BlockAccessListRequest::call(req, context).await,
        "eth_getTransactionByHash" => GetTransactionByHashRequest::call(req, context).await,
        "eth_getTransactionReceipt" => GetTransactionReceiptRequest::call(req, context).await,
        "eth_createAccessList" => CreateAccessListRequest::call(req, context).await,
        "eth_blockNumber" => BlockNumberRequest::call(req, context).await,
        "eth_call" => CallRequest::call(req, context).await,
        "eth_blobBaseFee" => GetBlobBaseFee::call(req, context).await,
        "eth_getTransactionCount" => GetTransactionCountRequest::call(req, context).await,
        "eth_feeHistory" => FeeHistoryRequest::call(req, context).await,
        "eth_estimateGas" => EstimateGasRequest::call(req, context).await,
        "eth_getLogs" => LogsFilter::call(req, context).await,
        "eth_newFilter" => {
            NewFilterRequest::stateful_call(req, context.storage, context.active_filters).await
        }
        "eth_uninstallFilter" => {
            DeleteFilterRequest::stateful_call(req, context.storage, context.active_filters)
        }
        "eth_getFilterChanges" => {
            FilterChangesRequest::stateful_call(req, context.storage, context.active_filters).await
        }
        "eth_sendRawTransaction" => SendRawTransactionRequest::call(req, context).await,
        "eth_getProof" => GetProofRequest::call(req, context).await,
        "eth_gasPrice" => GasPrice::call(req, context).await,
        "eth_maxPriorityFeePerGas" => {
            eth::max_priority_fee::MaxPriorityFee::call(req, context).await
        }
        "eth_config" => Config::call(req, context).await,
        unknown_eth_method => Err(RpcErr::MethodNotFound(unknown_eth_method.to_owned())),
    }
}

/// Routes `debug_*` namespace requests to their handlers.
///
/// Handles debugging and introspection methods:
/// - Raw data: `debug_getRawHeader`, `debug_getRawBlock`, `debug_getRawTransaction`, `debug_getRawReceipts`
/// - Execution witness: `debug_executionWitness` (for stateless validation)
/// - Tracing: `debug_traceTransaction`, `debug_traceBlockByNumber`
pub async fn map_debug_requests(req: &RpcRequest, context: RpcApiContext) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "debug_getRawHeader" => GetRawHeaderRequest::call(req, context).await,
        "debug_getRawBlock" => GetRawBlockRequest::call(req, context).await,
        "debug_getRawTransaction" => GetRawTransaction::call(req, context).await,
        "debug_getRawReceipts" => GetRawReceipts::call(req, context).await,
        "debug_executionWitness" => ExecutionWitnessRequest::call(req, context).await,
        "debug_executionWitnessByBlockHash" => {
            ExecutionWitnessByBlockHashRequest::call(req, context).await
        }
        "debug_chainConfig" => ChainConfigRequest::call(req, context).await,
        "debug_traceTransaction" => TraceTransactionRequest::call(req, context).await,
        "debug_traceBlockByNumber" => TraceBlockByNumberRequest::call(req, context).await,
        unknown_debug_method => Err(RpcErr::MethodNotFound(unknown_debug_method.to_owned())),
    }
}

/// Routes `engine_*` namespace requests to their handlers.
///
/// These are Engine API methods used by consensus clients (e.g., Lighthouse, Prysm)
/// to communicate with the execution layer. All methods require JWT authentication.
///
/// Handles:
/// - Fork choice: `engine_forkchoiceUpdatedV1/V2/V3`
/// - Payload submission: `engine_newPayloadV1/V2/V3/V4/V5`, `engine_newPayloadWithWitnessV5`
/// - Payload retrieval: `engine_getPayloadV1/V2/V3/V4/V5/V6`
/// - Payload bodies: `engine_getPayloadBodiesByHashV1`, `engine_getPayloadBodiesByRangeV1`
/// - Blob retrieval: `engine_getBlobsV1/V2/V3`
/// - Capabilities: `engine_exchangeCapabilities`, `engine_exchangeTransitionConfigurationV1`
pub async fn map_engine_requests(
    req: &RpcRequest,
    context: RpcApiContext,
) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "engine_exchangeCapabilities" => ExchangeCapabilitiesRequest::call(req, context).await,
        "engine_forkchoiceUpdatedV1" => ForkChoiceUpdatedV1::call(req, context).await,
        "engine_forkchoiceUpdatedV2" => ForkChoiceUpdatedV2::call(req, context).await,
        "engine_forkchoiceUpdatedV3" => ForkChoiceUpdatedV3::call(req, context).await,
        "engine_forkchoiceUpdatedV4" => ForkChoiceUpdatedV4::call(req, context).await,
        // The newPayload handlers carry the largest futures of any engine arm
        // (block execution + optional witness collection). Because this `match`
        // awaits each arm inline, the future of `map_engine_requests` is sized to
        // its largest arm and shared by every engine request. Box these arms so
        // they live on the heap instead of inflating the stack frame that even a
        // lightweight `forkchoiceUpdated` poll must reserve — otherwise a single
        // poll overflows the 2 MB tokio worker stack in unoptimized debug builds.
        "engine_newPayloadWithWitnessV5" => {
            Box::pin(NewPayloadWithWitnessV5Request::call(req, context)).await
        }
        "engine_newPayloadV5" => Box::pin(NewPayloadV5Request::call(req, context)).await,
        "engine_newPayloadV4" => Box::pin(NewPayloadV4Request::call(req, context)).await,
        "engine_newPayloadV3" => Box::pin(NewPayloadV3Request::call(req, context)).await,
        "engine_newPayloadV2" => NewPayloadV2Request::call(req, context).await,
        "engine_newPayloadV1" => NewPayloadV1Request::call(req, context).await,
        "engine_exchangeTransitionConfigurationV1" => {
            ExchangeTransitionConfigV1Req::call(req, context).await
        }
        "engine_getPayloadV6" => GetPayloadV6Request::call(req, context).await,
        "engine_getPayloadV5" => GetPayloadV5Request::call(req, context).await,
        "engine_getPayloadV4" => GetPayloadV4Request::call(req, context).await,
        "engine_getPayloadV3" => GetPayloadV3Request::call(req, context).await,
        "engine_getPayloadV2" => GetPayloadV2Request::call(req, context).await,
        "engine_getPayloadV1" => GetPayloadV1Request::call(req, context).await,
        "engine_getPayloadBodiesByHashV1" => {
            GetPayloadBodiesByHashV1Request::call(req, context).await
        }
        "engine_getPayloadBodiesByRangeV1" => {
            GetPayloadBodiesByRangeV1Request::call(req, context).await
        }
        "engine_getPayloadBodiesByHashV2" => {
            GetPayloadBodiesByHashV2Request::call(req, context).await
        }
        "engine_getPayloadBodiesByRangeV2" => {
            GetPayloadBodiesByRangeV2Request::call(req, context).await
        }
        "engine_getBlobsV1" => BlobsV1Request::call(req, context).await,
        "engine_getBlobsV2" => BlobsV2Request::call(req, context).await,
        "engine_getBlobsV3" => BlobsV3Request::call(req, context).await,
        "engine_getClientVersionV1" => GetClientVersionV1Request::call(req, context).await,
        unknown_engine_method => Err(RpcErr::MethodNotFound(unknown_engine_method.to_owned())),
    }
}

pub async fn map_admin_requests(
    req: &RpcRequest,
    mut context: RpcApiContext,
) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "admin_nodeInfo" => admin::node_info(context.storage, &context.node_data).await,
        "admin_peers" => admin::peers(&mut context).await,
        "admin_peerScores" => admin::peer_scores(&mut context).await,
        "admin_syncStatus" => admin::sync_status(&mut context).await,
        "admin_setLogLevel" => admin::set_log_level(req, &context.log_filter_handler),
        "admin_addPeer" => admin::add_peer(&mut context, req).await,
        unknown_admin_method => Err(RpcErr::MethodNotFound(unknown_admin_method.to_owned())),
    }
}

pub fn map_web3_requests(req: &RpcRequest, context: RpcApiContext) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "web3_clientVersion" => Ok(Value::String(context.node_data.client_version.to_string())),
        unknown_web3_method => Err(RpcErr::MethodNotFound(unknown_web3_method.to_owned())),
    }
}

pub async fn map_net_requests(req: &RpcRequest, contex: RpcApiContext) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        "net_version" => net::version(req, contex),
        "net_peerCount" => net::peer_count(req, contex).await,
        unknown_net_method => Err(RpcErr::MethodNotFound(unknown_net_method.to_owned())),
    }
}

pub fn map_mempool_requests(req: &RpcRequest, contex: RpcApiContext) -> Result<Value, RpcErr> {
    match req.method.as_str() {
        // TODO: The endpoint name matches geth's endpoint for compatibility, consider changing it in the future
        "txpool_content" => mempool::content(contex),
        "txpool_contentFrom" => mempool::content_from(&req.params, contex),
        "txpool_status" => mempool::status(contex),
        "txpool_inspect" => mempool::inspect(contex),
        unknown_mempool_method => Err(RpcErr::MethodNotFound(unknown_mempool_method.to_owned())),
    }
}

/// Formats a handler result into a JSON-RPC 2.0 response.
///
/// Wraps the result in either a success response (with `result` field) or
/// an error response (with `error` field containing code and message).
///
/// # Arguments
///
/// * `id` - The request ID to include in the response (must match the request)
/// * `res` - The handler result, either success value or error
///
/// # Returns
///
/// A JSON value representing the complete JSON-RPC 2.0 response object.
pub fn rpc_response<E>(id: RpcRequestId, res: Result<Value, E>) -> Result<Value, RpcErr>
where
    E: Into<RpcErrorMetadata>,
{
    Ok(match res {
        Ok(result) => serde_json::to_value(RpcSuccessResponse {
            id,
            jsonrpc: "2.0".to_string(),
            result,
        }),
        Err(error) => serde_json::to_value(RpcErrorResponse {
            id,
            jsonrpc: "2.0".to_string(),
            error: error.into(),
        }),
    }?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::default_context_with_storage;
    use ethrex_common::{
        H160,
        types::{BlockHeader, ChainConfig, Genesis},
    };
    use ethrex_crypto::keccak::keccak_hash;
    use ethrex_storage::{EngineType, Store};
    use std::io::BufReader;
    use std::str::FromStr;
    use std::{fs::File, path::Path};

    /// With the default `--http.api` allowlist (`eth,net,web3`), requests for
    /// disabled namespaces like `debug_*` must return MethodNotFound and never
    /// reach the handler.
    #[tokio::test]
    async fn http_api_allowlist_blocks_debug_namespace_by_default() {
        let body = r#"{"jsonrpc":"2.0","method":"debug_traceTransaction","params":["0x0"],"id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let mut context = default_context_with_storage(storage).await;
        context.allowed_namespaces = Arc::new(crate::DEFAULT_HTTP_API.iter().copied().collect());

        let result = map_http_requests(&request, context).await;
        match result {
            Err(RpcErr::MethodNotFound(method)) => {
                assert_eq!(method, "debug_traceTransaction");
            }
            other => panic!("expected MethodNotFound, got {other:?}"),
        }
    }

    /// The default allowlist must keep `eth_*`, `net_*`, and `web3_*` reachable.
    #[tokio::test]
    async fn http_api_allowlist_default_routes_standard_namespaces() {
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let mut context = default_context_with_storage(storage).await;
        context.allowed_namespaces = Arc::new(crate::DEFAULT_HTTP_API.iter().copied().collect());

        for method in ["eth_chainId", "net_version", "web3_clientVersion"] {
            let body = format!(r#"{{"jsonrpc":"2.0","method":"{method}","params":[],"id":1}}"#);
            let request: RpcRequest = serde_json::from_str(&body).unwrap();
            let result = map_http_requests(&request, context.clone()).await;
            assert!(
                !matches!(result, Err(RpcErr::MethodNotFound(_))),
                "default allowlist should route {method}, got {result:?}"
            );
        }
    }

    /// WebSocket subscriptions live in the `eth` namespace and must obey the
    /// same `--http.api` allowlist as regular `eth_*` requests. A node started
    /// without `eth` in the allowlist must not serve `eth_subscribe` over WS.
    #[tokio::test]
    async fn ws_subscribe_blocked_when_eth_namespace_disabled() {
        let body = r#"{"jsonrpc":"2.0","method":"eth_subscribe","params":["newHeads"],"id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let mut context = default_context_with_storage(storage).await;
        // Allow everything except `eth` so the WS path is the only thing under test.
        let mut without_eth: HashSet<RpcNamespace> = crate::test_utils::all_namespaces_for_tests();
        without_eth.remove(&RpcNamespace::Eth);
        context.allowed_namespaces = Arc::new(without_eth);

        let (out_tx, _out_rx) = tokio::sync::mpsc::channel::<String>(1);
        let mut subscription_ids: Vec<String> = Vec::new();
        let route_request = |_req: RpcRequest| async move {
            panic!(
                "route_request must not be called for eth_subscribe when the namespace is disabled"
            );
            #[allow(unreachable_code)]
            Ok::<Value, RpcErr>(Value::Null)
        };

        let response = process_ws_request(
            request,
            &context,
            &out_tx,
            &mut subscription_ids,
            &route_request,
        )
        .await
        .expect("process_ws_request should return an error response");

        let err = response.get("error").expect("expected error field");
        assert_eq!(
            err.get("code").and_then(|v| v.as_i64()),
            Some(-32601),
            "expected MethodNotFound (-32601), got {response}"
        );
        assert!(
            subscription_ids.is_empty(),
            "no subscription should have been registered"
        );
    }

    /// The Engine namespace must never be served over the public HTTP endpoint,
    /// even if an operator passes `engine` to `--http.api` (the CLI rejects it,
    /// but defense-in-depth: the dispatcher still refuses).
    #[tokio::test]
    async fn engine_namespace_rejected_on_http() {
        let body = r#"{"jsonrpc":"2.0","method":"engine_forkchoiceUpdatedV3","params":[],"id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let mut context = default_context_with_storage(storage).await;
        let mut all_with_engine: HashSet<RpcNamespace> =
            crate::test_utils::all_namespaces_for_tests();
        all_with_engine.insert(RpcNamespace::Engine);
        context.allowed_namespaces = Arc::new(all_with_engine);

        let result = map_http_requests(&request, context).await;
        assert!(matches!(result, Err(RpcErr::MethodNotFound(_))));
    }

    // Maps string rpc response to RpcSuccessResponse as serde Value
    // This is used to avoid failures due to field order and allow easier string comparisons for responses
    fn to_rpc_response_success_value(str: &str) -> serde_json::Value {
        serde_json::to_value(serde_json::from_str::<RpcSuccessResponse>(str).unwrap()).unwrap()
    }

    #[tokio::test]
    async fn admin_nodeinfo_request() {
        let body = r#"{"jsonrpc":"2.0", "method":"admin_nodeInfo", "params":[], "id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let context = default_context_with_storage(storage).await;
        let local_p2p_node = context.node_data.local_p2p_node.clone();

        let enr_url = context.node_data.local_node_record.enr_url().unwrap();
        let result = map_http_requests(&request, context).await;
        let rpc_response = rpc_response(request.id, result).unwrap();
        let blob_schedule = serde_json::json!({
            "cancun": { "baseFeeUpdateFraction": 3338477, "max": 6, "target": 3,  },
            "prague": { "baseFeeUpdateFraction": 5007716, "max": 9, "target": 6,  },
            "osaka": { "baseFeeUpdateFraction": 5007716, "max": 9, "target": 6,  },
            "bpo1": { "baseFeeUpdateFraction": 8346193, "max": 15, "target": 10,  },
            "bpo2": { "baseFeeUpdateFraction": 11684671, "max": 21, "target": 14,  },
        });
        // Both genesis and head resolve to the default BlockHeader (number 0).
        let default_hash = BlockHeader::default().hash();
        let json = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": {
                "enode": "enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@127.0.0.1:30303",
                "enr": enr_url,
                "id": hex::encode(keccak_hash(local_p2p_node.public_key)),
                "ip": "127.0.0.1",
                "listenAddr": "127.0.0.1:30303",
                "name": "ethrex/v0.1.0-test-abcd1234/x86_64-unknown-linux/rustc-v1.70.0",
                "ports": {
                    "discovery": 30303,
                    "listener": 30303
                },
                "protocols": {
                    "eth": {
                        "network": 3151908,
                        "genesis": default_hash,
                        "config": {
                            "chainId": 3151908,
                            "homesteadBlock": 0,
                            "daoForkBlock": null,
                            "daoForkSupport": false,
                            "eip150Block": 0,
                            "eip155Block": 0,
                            "eip158Block": 0,
                            "byzantiumBlock": 0,
                            "constantinopleBlock": 0,
                            "petersburgBlock": 0,
                            "istanbulBlock": 0,
                            "muirGlacierBlock": null,
                            "berlinBlock": 0,
                            "londonBlock": 0,
                            "arrowGlacierBlock": null,
                            "grayGlacierBlock": null,
                            "mergeNetsplitBlock": 0,
                            "shanghaiTime": 0,
                            "cancunTime": 0,
                            "pragueTime": 1718232101,
                            "verkleTime": null,
                            "osakaTime": null,
                            "bpo1Time": null,
                            "bpo2Time": null,
                            "bpo3Time": null,
                            "bpo4Time": null,
                            "bpo5Time": null,
                            "amsterdamTime": null,
                            "terminalTotalDifficulty": "0x0",
                            "terminalTotalDifficultyPassed": true,
                            "blobSchedule": blob_schedule,
                            "depositContractAddress": H160::from_str("0x00000000219ab540356cbb839cbe05303d7705fa").unwrap(),
                            "enableVerkleAtGenesis": false,
                        },
                        "head": default_hash,
                    }
                },
            }
        });
        let expected_response = to_rpc_response_success_value(&json.to_string());
        assert_eq!(rpc_response.to_string(), expected_response.to_string())
    }

    // Reads genesis file taken from https://github.com/ethereum/execution-apis/blob/main/tests/genesis.json
    fn read_execution_api_genesis_file() -> Genesis {
        let file = File::open("../../../fixtures/genesis/execution-api.json")
            .expect("Failed to open genesis file");
        let reader = BufReader::new(file);
        serde_json::from_reader(reader).expect("Failed to deserialize genesis file")
    }

    #[tokio::test]
    async fn create_access_list_simple_transfer() {
        // Create Request
        // Request taken from https://github.com/ethereum/execution-apis/blob/main/tests/eth_createAccessList/create-al-value-transfer.io
        let body = r#"{"jsonrpc":"2.0","id":1,"method":"eth_createAccessList","params":[{"from":"0x0c2c51a0990aee1d73c1228de158688341557508","nonce":"0x0","to":"0x0100000000000000000000000000000000000000","value":"0xa"},"0x00"]}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        // Setup initial storage
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        let genesis = read_execution_api_genesis_file();
        storage
            .add_initial_state(genesis)
            .await
            .expect("Failed to add genesis block to DB");
        // Process request
        let context = default_context_with_storage(storage).await;
        let result = map_http_requests(&request, context).await;
        let response = rpc_response(request.id, result).unwrap();
        let expected_response = to_rpc_response_success_value(
            r#"{"jsonrpc":"2.0","id":1,"result":{"accessList":[],"gasUsed":"0x5208"}}"#,
        );
        assert_eq!(response.to_string(), expected_response.to_string());
    }

    fn example_chain_config() -> ChainConfig {
        ChainConfig {
            chain_id: 3151908_u64,
            homestead_block: Some(0),
            eip150_block: Some(0),
            eip155_block: Some(0),
            eip158_block: Some(0),
            byzantium_block: Some(0),
            constantinople_block: Some(0),
            petersburg_block: Some(0),
            istanbul_block: Some(0),
            berlin_block: Some(0),
            london_block: Some(0),
            merge_netsplit_block: Some(0),
            shanghai_time: Some(0),
            cancun_time: Some(0),
            prague_time: Some(1718232101),
            terminal_total_difficulty: Some(0),
            terminal_total_difficulty_passed: true,
            deposit_contract_address: H160::from_str("0x00000000219ab540356cbb839cbe05303d7705fa")
                .unwrap(),
            ..Default::default()
        }
    }

    /// Tests that admin_nodeInfo doesn't fail when terminal_total_difficulty
    /// exceeds u64::MAX. Before the fix, serde_json::to_value() would return
    /// "number out of range" because Value::Number can only hold u64/i64/f64.
    #[tokio::test]
    async fn admin_nodeinfo_large_terminal_total_difficulty() {
        // Mainnet's terminal_total_difficulty: 58_750_000_000_000_000_000_000
        // This exceeds u64::MAX (~1.8e19) and triggers the bug with serde_json::to_value().
        let mainnet_ttd: u128 = 58_750_000_000_000_000_000_000;

        let body = r#"{"jsonrpc":"2.0", "method":"admin_nodeInfo", "params":[], "id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        let mut config = example_chain_config();
        config.terminal_total_difficulty = Some(mainnet_ttd);
        storage.set_chain_config(&config).await.unwrap();
        let context = default_context_with_storage(storage).await;

        let result = map_http_requests(&request, context).await;
        assert!(
            result.is_ok(),
            "admin_nodeInfo should not fail with large terminal_total_difficulty"
        );

        let value = result.unwrap();
        let ttd = value
            .pointer("/protocols/eth/config/terminalTotalDifficulty")
            .expect("terminalTotalDifficulty should be present in response");
        // Serialized as a hex string to avoid serde_json Value::Number u64 limitation.
        assert_eq!(ttd.as_str().unwrap(), "0xc70d808a128d7380000");
    }

    #[tokio::test]
    async fn net_version_test() {
        let body = r#"{"jsonrpc":"2.0","method":"net_version","params":[],"id":67}"#;
        let request: RpcRequest = serde_json::from_str(body).expect("serde serialization failed");
        // Setup initial storage
        let mut storage =
            Store::new("temp.db", EngineType::InMemory).expect("Failed to create test DB");
        storage
            .set_chain_config(&example_chain_config())
            .await
            .unwrap();
        let chain_id = storage.get_chain_config().chain_id.to_string();
        let context = default_context_with_storage(storage).await;
        // Process request
        let result = map_http_requests(&request, context).await;
        let response = rpc_response(request.id, result).unwrap();
        let expected_response_string =
            format!(r#"{{"id":67,"jsonrpc": "2.0","result": "{chain_id}"}}"#);
        let expected_response = to_rpc_response_success_value(&expected_response_string);
        assert_eq!(response.to_string(), expected_response.to_string());
    }

    #[tokio::test]
    async fn eth_config_request_cancun_with_prague_scheduled() {
        let body = r#"{"jsonrpc":"2.0", "method":"eth_config", "params":[], "id":1}"#;
        let request: RpcRequest = serde_json::from_str(body).unwrap();
        let storage = Store::new_from_genesis(
            Path::new("temp.db"),
            EngineType::InMemory,
            "../../../cmd/ethrex/networks/hoodi/genesis.json",
        )
        .await
        .expect("Failed to create test DB");
        let context = default_context_with_storage(storage).await;
        let result = map_http_requests(&request, context).await;
        let rpc_response = rpc_response(request.id, result).unwrap();
        let json = serde_json::json!({
            "id": 1,
            "jsonrpc": "2.0",
            "result": {
                "current": {
                    "activationTime": 0,
                    "blobSchedule": {
                        "baseFeeUpdateFraction": 3338477,
                        "max": 6,
                        "target": 3
                    },
                    "chainId": "0x88bb0",
                    "forkId": "0xbef71d30",
                    "precompiles": {
                        "BLAKE2F": "0x0000000000000000000000000000000000000009",
                        "BN254_ADD": "0x0000000000000000000000000000000000000006",
                        "BN254_MUL": "0x0000000000000000000000000000000000000007",
                        "BN254_PAIRING": "0x0000000000000000000000000000000000000008",
                        "ECREC": "0x0000000000000000000000000000000000000001",
                        "ID": "0x0000000000000000000000000000000000000004",
                        "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a",
                        "MODEXP": "0x0000000000000000000000000000000000000005",
                        "RIPEMD160": "0x0000000000000000000000000000000000000003",
                        "SHA256": "0x0000000000000000000000000000000000000002"
                    },
                    "systemContracts": {
                        "BEACON_ROOTS_ADDRESS": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02"
                    }
                },
                "next": {
                    "activationTime": 1742999832,
                    "blobSchedule": {
                        "baseFeeUpdateFraction": 5007716,
                        "max": 9,
                        "target": 6
                    },
                    "chainId": "0x88bb0",
                    "forkId": "0x0929e24e",
                    "precompiles": {
                        "BLAKE2F": "0x0000000000000000000000000000000000000009",
                        "BLS12_G1ADD": "0x000000000000000000000000000000000000000b",
                        "BLS12_G1MSM": "0x000000000000000000000000000000000000000c",
                        "BLS12_G2ADD": "0x000000000000000000000000000000000000000d",
                        "BLS12_G2MSM": "0x000000000000000000000000000000000000000e",
                        "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011",
                        "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010",
                        "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f",
                        "BN254_ADD": "0x0000000000000000000000000000000000000006",
                        "BN254_MUL": "0x0000000000000000000000000000000000000007",
                        "BN254_PAIRING": "0x0000000000000000000000000000000000000008",
                        "ECREC": "0x0000000000000000000000000000000000000001",
                        "ID": "0x0000000000000000000000000000000000000004",
                        "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a",
                        "MODEXP": "0x0000000000000000000000000000000000000005",
                        "RIPEMD160": "0x0000000000000000000000000000000000000003",
                        "SHA256": "0x0000000000000000000000000000000000000002"
                    },
                    "systemContracts": {
                        "BEACON_ROOTS_ADDRESS": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02",
                        "CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS": "0x0000bbddc7ce488642fb579f8b00f3a590007251",
                        "DEPOSIT_CONTRACT_ADDRESS": "0x00000000219ab540356cbb839cbe05303d7705fa",
                        "HISTORY_STORAGE_ADDRESS": "0x0000f90827f1c53a10cb7a02335b175320002935",
                        "WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS": "0x00000961ef480eb55e80d19ad83579a64c007002"
                    }
                },
                "last": {
                    "activationTime": 1762955544,
                    "blobSchedule": {
                        "baseFeeUpdateFraction": 11684671,
                        "max": 21,
                        "target": 14,
                    },
                    "chainId": "0x88bb0",
                    "forkId": "0x23aa1351",
                    "precompiles": {
                        "BLAKE2F": "0x0000000000000000000000000000000000000009",
                        "BLS12_G1ADD": "0x000000000000000000000000000000000000000b",
                        "BLS12_G1MSM": "0x000000000000000000000000000000000000000c",
                        "BLS12_G2ADD": "0x000000000000000000000000000000000000000d",
                        "BLS12_G2MSM": "0x000000000000000000000000000000000000000e",
                        "BLS12_MAP_FP2_TO_G2": "0x0000000000000000000000000000000000000011",
                        "BLS12_MAP_FP_TO_G1": "0x0000000000000000000000000000000000000010",
                        "BLS12_PAIRING_CHECK": "0x000000000000000000000000000000000000000f",
                        "BN254_ADD": "0x0000000000000000000000000000000000000006",
                        "BN254_MUL": "0x0000000000000000000000000000000000000007",
                        "BN254_PAIRING": "0x0000000000000000000000000000000000000008",
                        "ECREC": "0x0000000000000000000000000000000000000001",
                        "ID": "0x0000000000000000000000000000000000000004",
                        "KZG_POINT_EVALUATION": "0x000000000000000000000000000000000000000a",
                        "MODEXP": "0x0000000000000000000000000000000000000005",
                        "P256VERIFY":"0x0000000000000000000000000000000000000100",
                        "RIPEMD160": "0x0000000000000000000000000000000000000003",
                        "SHA256": "0x0000000000000000000000000000000000000002"
                    },
                    "systemContracts": {
                        "BEACON_ROOTS_ADDRESS": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02",
                        "CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS": "0x0000bbddc7ce488642fb579f8b00f3a590007251",
                        "DEPOSIT_CONTRACT_ADDRESS": "0x00000000219ab540356cbb839cbe05303d7705fa",
                        "HISTORY_STORAGE_ADDRESS": "0x0000f90827f1c53a10cb7a02335b175320002935",
                        "WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS": "0x00000961ef480eb55e80d19ad83579a64c007002"
                    }
                },
            }
        });
        let expected_response = to_rpc_response_success_value(&json.to_string());
        assert_eq!(rpc_response.to_string(), expected_response.to_string())
    }
}