1#![doc(
15 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
16 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
17 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
18)]
19#![cfg_attr(not(test), warn(unused_crate_dependencies))]
20#![cfg_attr(docsrs, feature(doc_cfg))]
21
22use crate::{auth::AuthRpcModule, error::WsHttpSamePortError, metrics::RpcRequestMetrics};
23use alloy_network::{Ethereum, IntoWallet};
24use alloy_provider::{fillers::RecommendedFillers, Provider, ProviderBuilder, WsConnect};
25use alloy_rpc_client::{ClientBuilder, RpcClient};
26use alloy_transport::Authorization;
27use core::marker::PhantomData;
28use error::{ConflictingModules, RpcError, ServerKind};
29use jsonrpsee::{
30 core::RegisterMethodError,
31 server::{middleware::rpc::RpcServiceBuilder, AlreadyStoppedError, IdProvider, ServerHandle},
32 Methods, RpcModule,
33};
34use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
35use reth_consensus::FullConsensus;
36use reth_engine_primitives::{ConsensusEngineEvent, ConsensusEngineHandle};
37use reth_evm::ConfigureEvm;
38use reth_network_api::{noop::NoopNetwork, NetworkInfo, Peers};
39use reth_payload_primitives::PayloadTypes;
40use reth_primitives_traits::{NodePrimitives, TxTy};
41use reth_rpc::{
42 AdminApi, DebugApi, EngineEthApi, EthApi, EthApiBuilder, EthBundle, MinerApi, NetApi,
43 OtterscanApi, RPCApi, RethApi, TraceApi, TxPoolApi, Web3Api,
44};
45use reth_rpc_api::servers::*;
46use reth_rpc_engine_api::RethEngineApi;
47use reth_rpc_eth_api::{
48 helpers::{
49 pending_block::PendingEnvBuilder, Call, EthApiSpec, EthBlocks, EthTransactions, TraceExt,
50 },
51 node::RpcNodeCoreAdapter,
52 EthApiServer, EthApiTypes, FullEthApiServer, FullEthApiTypes, RpcBlock, RpcConvert,
53 RpcConverter, RpcHeader, RpcNodeCore, RpcReceipt, RpcTransaction, RpcTxReq,
54};
55use reth_rpc_eth_types::{receipt::EthReceiptConverter, EthConfig, EthSubscriptionIdProvider};
56use reth_rpc_layer::{
57 AuthClientLayer, AuthLayer, Claims, CompressionLayer, DecompressionLayer, JwtAuthValidator,
58 JwtSecret,
59};
60pub use reth_rpc_server_types::RethRpcModule;
61use reth_storage_api::{
62 BlockReader, ChangeSetReader, FullRpcProvider, NodePrimitivesProvider, StateProviderFactory,
63};
64use reth_tasks::{pool::BlockingTaskGuard, Runtime};
65use reth_tokio_util::EventSender;
66use reth_transaction_pool::{noop::NoopTransactionPool, TransactionPool};
67use serde::{Deserialize, Serialize};
68use std::{
69 collections::HashMap,
70 fmt::Debug,
71 net::{Ipv4Addr, SocketAddr, SocketAddrV4},
72 time::{Duration, SystemTime, UNIX_EPOCH},
73};
74use tower_http::{cors::CorsLayer, validate_request::ValidateRequestHeaderLayer};
75
76pub use cors::CorsDomainError;
77
78pub use jsonrpsee::server::ServerBuilder;
80use jsonrpsee::server::ServerConfigBuilder;
81pub use reth_ipc::server::{
82 Builder as IpcServerBuilder, RpcServiceBuilder as IpcRpcServiceBuilder,
83};
84pub use reth_rpc_server_types::{constants, RpcModuleSelection};
85pub use tower::layer::util::{Identity, Stack};
86
87pub mod auth;
89
90pub mod config;
92
93pub mod middleware;
95
96mod cors;
98
99pub mod error;
101
102pub mod eth;
104pub use eth::EthHandlers;
105
106mod metrics;
108use crate::middleware::RethRpcMiddleware;
109pub use metrics::{MeteredBatchRequestsFuture, MeteredRequestFuture, RpcRequestMetricsService};
110use reth_chain_state::{
111 CanonStateSubscriptions, ForkChoiceSubscriptions, PersistedBlockSubscriptions,
112};
113use reth_rpc::eth::sim_bundle::EthSimBundle;
114
115pub mod rate_limiter;
117
118#[derive(Debug, Clone)]
122pub struct RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, Consensus> {
123 provider: Provider,
125 pool: Pool,
127 network: Network,
129 executor: Option<Runtime>,
131 evm_config: EvmConfig,
133 consensus: Consensus,
135 _primitives: PhantomData<N>,
137}
138
139impl<N, Provider, Pool, Network, EvmConfig, Consensus>
142 RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, Consensus>
143{
144 pub const fn new(
146 provider: Provider,
147 pool: Pool,
148 network: Network,
149 executor: Runtime,
150 evm_config: EvmConfig,
151 consensus: Consensus,
152 ) -> Self {
153 Self {
154 provider,
155 pool,
156 network,
157 executor: Some(executor),
158 evm_config,
159 consensus,
160 _primitives: PhantomData,
161 }
162 }
163
164 pub fn with_provider<P>(
166 self,
167 provider: P,
168 ) -> RpcModuleBuilder<N, P, Pool, Network, EvmConfig, Consensus> {
169 let Self { pool, network, executor, evm_config, consensus, _primitives, .. } = self;
170 RpcModuleBuilder { provider, network, pool, executor, evm_config, consensus, _primitives }
171 }
172
173 pub fn with_pool<P>(
175 self,
176 pool: P,
177 ) -> RpcModuleBuilder<N, Provider, P, Network, EvmConfig, Consensus> {
178 let Self { provider, network, executor, evm_config, consensus, _primitives, .. } = self;
179 RpcModuleBuilder { provider, network, pool, executor, evm_config, consensus, _primitives }
180 }
181
182 pub fn with_noop_pool(
188 self,
189 ) -> RpcModuleBuilder<N, Provider, NoopTransactionPool, Network, EvmConfig, Consensus> {
190 let Self { provider, executor, network, evm_config, consensus, _primitives, .. } = self;
191 RpcModuleBuilder {
192 provider,
193 executor,
194 network,
195 evm_config,
196 pool: NoopTransactionPool::default(),
197 consensus,
198 _primitives,
199 }
200 }
201
202 pub fn with_network<Net>(
204 self,
205 network: Net,
206 ) -> RpcModuleBuilder<N, Provider, Pool, Net, EvmConfig, Consensus> {
207 let Self { provider, pool, executor, evm_config, consensus, _primitives, .. } = self;
208 RpcModuleBuilder { provider, network, pool, executor, evm_config, consensus, _primitives }
209 }
210
211 pub fn with_noop_network(
217 self,
218 ) -> RpcModuleBuilder<N, Provider, Pool, NoopNetwork, EvmConfig, Consensus> {
219 let Self { provider, pool, executor, evm_config, consensus, _primitives, .. } = self;
220 RpcModuleBuilder {
221 provider,
222 pool,
223 executor,
224 network: NoopNetwork::default(),
225 evm_config,
226 consensus,
227 _primitives,
228 }
229 }
230
231 pub fn with_executor(self, executor: Runtime) -> Self {
233 let Self { pool, network, provider, evm_config, consensus, _primitives, .. } = self;
234 Self {
235 provider,
236 network,
237 pool,
238 executor: Some(executor),
239 evm_config,
240 consensus,
241 _primitives,
242 }
243 }
244
245 pub fn with_evm_config<E>(
247 self,
248 evm_config: E,
249 ) -> RpcModuleBuilder<N, Provider, Pool, Network, E, Consensus> {
250 let Self { provider, pool, executor, network, consensus, _primitives, .. } = self;
251 RpcModuleBuilder { provider, network, pool, executor, evm_config, consensus, _primitives }
252 }
253
254 pub fn with_consensus<C>(
256 self,
257 consensus: C,
258 ) -> RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, C> {
259 let Self { provider, network, pool, executor, evm_config, _primitives, .. } = self;
260 RpcModuleBuilder { provider, network, pool, executor, evm_config, consensus, _primitives }
261 }
262
263 #[expect(clippy::type_complexity)]
265 pub fn eth_api_builder<ChainSpec>(
266 &self,
267 ) -> EthApiBuilder<
268 RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>,
269 RpcConverter<Ethereum, EvmConfig, EthReceiptConverter<ChainSpec>>,
270 >
271 where
272 Provider: Clone,
273 Pool: Clone,
274 Network: Clone,
275 EvmConfig: Clone,
276 RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>:
277 RpcNodeCore<Provider: ChainSpecProvider<ChainSpec = ChainSpec>, Evm = EvmConfig>,
278 {
279 EthApiBuilder::new(
280 self.provider.clone(),
281 self.pool.clone(),
282 self.network.clone(),
283 self.evm_config.clone(),
284 )
285 }
286
287 #[expect(clippy::type_complexity)]
293 pub fn bootstrap_eth_api<ChainSpec>(
294 &self,
295 ) -> EthApi<
296 RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>,
297 RpcConverter<Ethereum, EvmConfig, EthReceiptConverter<ChainSpec>>,
298 >
299 where
300 Provider: Clone,
301 Pool: Clone,
302 Network: Clone,
303 EvmConfig: ConfigureEvm,
304 RpcNodeCoreAdapter<Provider, Pool, Network, EvmConfig>:
305 RpcNodeCore<Provider: ChainSpecProvider<ChainSpec = ChainSpec>, Evm = EvmConfig>,
306 RpcConverter<Ethereum, EvmConfig, EthReceiptConverter<ChainSpec>>: RpcConvert,
307 (): PendingEnvBuilder<EvmConfig>,
308 {
309 self.eth_api_builder().build()
310 }
311}
312
313impl<N, Provider, Pool, Network, EvmConfig, Consensus>
314 RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, Consensus>
315where
316 N: NodePrimitives,
317 Provider: FullRpcProvider<Block = N::Block, Receipt = N::Receipt, Header = N::BlockHeader>
318 + CanonStateSubscriptions<Primitives = N>
319 + ForkChoiceSubscriptions<Header = N::BlockHeader>
320 + PersistedBlockSubscriptions
321 + ChangeSetReader
322 + NodePrimitivesProvider<Primitives = N>,
323 Pool: TransactionPool + 'static,
324 Network: NetworkInfo + Peers + Clone + 'static,
325 EvmConfig: ConfigureEvm<Primitives = N> + 'static,
326 Consensus: FullConsensus<N> + Clone + 'static,
327{
328 pub fn build_with_auth_server<EthApi, Payload>(
335 self,
336 module_config: TransportRpcModuleConfig,
337 engine: impl IntoEngineApiRpcModule,
338 eth: EthApi,
339 engine_events: EventSender<ConsensusEngineEvent<N>>,
340 beacon_engine_handle: ConsensusEngineHandle<Payload>,
341 ) -> (
342 TransportRpcModules,
343 AuthRpcModule,
344 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>,
345 )
346 where
347 EthApi: FullEthApiServer<Provider = Provider, Pool = Pool>,
348 Payload: PayloadTypes,
349 {
350 let config = module_config.config.clone().unwrap_or_default();
351
352 let mut registry = self.into_registry(config, eth, engine_events);
353 let modules = registry.create_transport_rpc_modules(module_config);
354 let auth_module = registry.create_auth_module(engine, beacon_engine_handle);
355
356 (modules, auth_module, registry)
357 }
358
359 pub fn into_registry<EthApi>(
364 self,
365 config: RpcModuleConfig,
366 eth: EthApi,
367 engine_events: EventSender<ConsensusEngineEvent<N>>,
368 ) -> RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
369 where
370 EthApi: FullEthApiServer<Provider = Provider, Pool = Pool>,
371 {
372 let Self { provider, pool, network, executor, consensus, evm_config, .. } = self;
373 let executor =
374 executor.expect("RpcModuleBuilder requires a Runtime to be set via `with_executor`");
375 RpcRegistryInner::new(
376 provider,
377 pool,
378 network,
379 executor,
380 consensus,
381 config,
382 evm_config,
383 eth,
384 engine_events,
385 )
386 }
387
388 pub fn build<EthApi>(
391 self,
392 module_config: TransportRpcModuleConfig,
393 eth: EthApi,
394 engine_events: EventSender<ConsensusEngineEvent<N>>,
395 ) -> TransportRpcModules<()>
396 where
397 EthApi: FullEthApiServer<Provider = Provider, Pool = Pool>,
398 {
399 if module_config.is_empty() {
400 TransportRpcModules::default()
401 } else {
402 let config = module_config.config.clone().unwrap_or_default();
403 let mut registry = self.into_registry(config, eth, engine_events);
404 registry.create_transport_rpc_modules(module_config)
405 }
406 }
407}
408
409impl<N: NodePrimitives> Default for RpcModuleBuilder<N, (), (), (), (), ()> {
410 fn default() -> Self {
411 Self {
412 provider: (),
413 pool: (),
414 network: (),
415 executor: None,
416 evm_config: (),
417 consensus: (),
418 _primitives: PhantomData,
419 }
420 }
421}
422
423#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
425pub struct RpcModuleConfig {
426 eth: EthConfig,
428}
429
430impl RpcModuleConfig {
433 pub fn builder() -> RpcModuleConfigBuilder {
435 RpcModuleConfigBuilder::default()
436 }
437
438 pub const fn new(eth: EthConfig) -> Self {
440 Self { eth }
441 }
442
443 pub const fn eth(&self) -> &EthConfig {
445 &self.eth
446 }
447
448 pub const fn eth_mut(&mut self) -> &mut EthConfig {
450 &mut self.eth
451 }
452}
453
454#[derive(Clone, Debug, Default)]
456pub struct RpcModuleConfigBuilder {
457 eth: Option<EthConfig>,
458}
459
460impl RpcModuleConfigBuilder {
463 pub fn eth(mut self, eth: EthConfig) -> Self {
465 self.eth = Some(eth);
466 self
467 }
468
469 pub fn build(self) -> RpcModuleConfig {
471 let Self { eth } = self;
472 RpcModuleConfig { eth: eth.unwrap_or_default() }
473 }
474
475 pub const fn get_eth(&self) -> Option<&EthConfig> {
477 self.eth.as_ref()
478 }
479
480 pub const fn eth_mut(&mut self) -> &mut Option<EthConfig> {
482 &mut self.eth
483 }
484
485 pub fn eth_mut_or_default(&mut self) -> &mut EthConfig {
487 self.eth.get_or_insert_with(EthConfig::default)
488 }
489}
490
491#[derive(Debug)]
493pub struct RpcRegistryInner<Provider, Pool, Network, EthApi: EthApiTypes, EvmConfig, Consensus> {
494 provider: Provider,
495 pool: Pool,
496 network: Network,
497 executor: Runtime,
498 evm_config: EvmConfig,
499 consensus: Consensus,
500 eth: EthHandlers<EthApi>,
502 blocking_pool_guard: BlockingTaskGuard,
504 modules: HashMap<RethRpcModule, Methods>,
506 eth_config: EthConfig,
508 engine_events:
510 EventSender<ConsensusEngineEvent<<EthApi::RpcConvert as RpcConvert>::Primitives>>,
511}
512
513impl<N, Provider, Pool, Network, EthApi, EvmConfig, Consensus>
516 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
517where
518 N: NodePrimitives,
519 Provider: StateProviderFactory
520 + CanonStateSubscriptions<Primitives = N>
521 + BlockReader<Block = N::Block, Receipt = N::Receipt>
522 + Clone
523 + Unpin
524 + 'static,
525 Pool: Send + Sync + Clone + 'static,
526 Network: Clone + 'static,
527 EthApi: FullEthApiTypes,
528 EvmConfig: ConfigureEvm<Primitives = N>,
529{
530 #[expect(clippy::too_many_arguments)]
532 pub fn new(
533 provider: Provider,
534 pool: Pool,
535 network: Network,
536 executor: Runtime,
537 consensus: Consensus,
538 config: RpcModuleConfig,
539 evm_config: EvmConfig,
540 eth_api: EthApi,
541 engine_events: EventSender<
542 ConsensusEngineEvent<<EthApi::Provider as NodePrimitivesProvider>::Primitives>,
543 >,
544 ) -> Self
545 where
546 EvmConfig: ConfigureEvm<Primitives = N>,
547 {
548 let blocking_pool_guard = BlockingTaskGuard::new(config.eth.max_tracing_requests);
549
550 let eth = EthHandlers::bootstrap(config.eth.clone(), executor.clone(), eth_api);
551
552 Self {
553 provider,
554 pool,
555 network,
556 eth,
557 executor,
558 consensus,
559 modules: Default::default(),
560 blocking_pool_guard,
561 eth_config: config.eth,
562 evm_config,
563 engine_events,
564 }
565 }
566}
567
568impl<Provider, Pool, Network, EthApi, Evm, Consensus>
569 RpcRegistryInner<Provider, Pool, Network, EthApi, Evm, Consensus>
570where
571 EthApi: EthApiTypes,
572{
573 pub const fn eth_api(&self) -> &EthApi {
575 &self.eth.api
576 }
577
578 pub const fn eth_handlers(&self) -> &EthHandlers<EthApi> {
580 &self.eth
581 }
582
583 pub const fn pool(&self) -> &Pool {
585 &self.pool
586 }
587
588 pub const fn tasks(&self) -> &Runtime {
590 &self.executor
591 }
592
593 pub const fn provider(&self) -> &Provider {
595 &self.provider
596 }
597
598 pub const fn evm_config(&self) -> &Evm {
600 &self.evm_config
601 }
602
603 pub fn methods(&self) -> Vec<Methods> {
605 self.modules.values().cloned().collect()
606 }
607
608 pub fn module(&self) -> RpcModule<()> {
610 let mut module = RpcModule::new(());
611 for methods in self.modules.values().cloned() {
612 module.merge(methods).expect("No conflicts");
613 }
614 module
615 }
616}
617
618impl<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
619 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
620where
621 Network: NetworkInfo + Clone + 'static,
622 EthApi: EthApiTypes,
623 Provider: BlockReader + ChainSpecProvider<ChainSpec: EthereumHardforks>,
624 EvmConfig: ConfigureEvm,
625{
626 pub fn admin_api(&self) -> AdminApi<Network, Provider::ChainSpec, Pool>
628 where
629 Network: Peers,
630 Pool: TransactionPool + 'static,
631 {
632 AdminApi::new(self.network.clone(), self.provider.chain_spec(), self.pool.clone())
633 }
634
635 pub fn web3_api(&self) -> Web3Api<Network> {
637 Web3Api::new(self.network.clone())
638 }
639
640 pub fn register_admin(&mut self) -> &mut Self
642 where
643 Network: Peers,
644 Pool: TransactionPool + 'static,
645 {
646 let adminapi = self.admin_api();
647 self.modules.insert(RethRpcModule::Admin, adminapi.into_rpc().into());
648 self
649 }
650
651 pub fn register_web3(&mut self) -> &mut Self {
653 let web3api = self.web3_api();
654 self.modules.insert(RethRpcModule::Web3, web3api.into_rpc().into());
655 self
656 }
657}
658
659impl<N, Provider, Pool, Network, EthApi, EvmConfig, Consensus>
660 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
661where
662 N: NodePrimitives,
663 Provider: FullRpcProvider<
664 Header = N::BlockHeader,
665 Block = N::Block,
666 Receipt = N::Receipt,
667 Transaction = N::SignedTx,
668 > + ChangeSetReader
669 + CanonStateSubscriptions<Primitives = N>
670 + ForkChoiceSubscriptions<Header = N::BlockHeader>
671 + PersistedBlockSubscriptions,
672 Network: NetworkInfo + Peers + Clone + 'static,
673 EthApi: EthApiServer<
674 RpcTxReq<EthApi::NetworkTypes>,
675 RpcTransaction<EthApi::NetworkTypes>,
676 RpcBlock<EthApi::NetworkTypes>,
677 RpcReceipt<EthApi::NetworkTypes>,
678 RpcHeader<EthApi::NetworkTypes>,
679 TxTy<N>,
680 > + EthApiTypes,
681 EvmConfig: ConfigureEvm<Primitives = N> + 'static,
682{
683 pub fn register_eth(&mut self) -> &mut Self {
689 let eth_api = self.eth_api().clone();
690 self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into());
691 self
692 }
693
694 pub fn register_ots(&mut self) -> &mut Self
700 where
701 EthApi: TraceExt + EthTransactions<Primitives = N> + EthBlocks,
702 {
703 let otterscan_api = self.otterscan_api();
704 self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into());
705 self
706 }
707
708 pub fn register_debug(&mut self) -> &mut Self
714 where
715 EthApi: EthTransactions + TraceExt,
716 {
717 let debug_api = self.debug_api();
718 self.modules.insert(RethRpcModule::Debug, debug_api.into_rpc().into());
719 self
720 }
721
722 pub fn register_trace(&mut self) -> &mut Self
728 where
729 EthApi: TraceExt,
730 {
731 let trace_api = self.trace_api();
732 self.modules.insert(RethRpcModule::Trace, trace_api.into_rpc().into());
733 self
734 }
735
736 pub fn register_net(&mut self) -> &mut Self
744 where
745 EthApi: EthApiSpec,
746 {
747 let netapi = self.net_api();
748 self.modules.insert(RethRpcModule::Net, netapi.into_rpc().into());
749 self
750 }
751
752 pub fn register_reth(&mut self) -> &mut Self {
760 let rethapi = self.reth_api();
761 self.modules.insert(RethRpcModule::Reth, rethapi.into_rpc().into());
762 self
763 }
764
765 pub fn otterscan_api(&self) -> OtterscanApi<EthApi> {
771 let eth_api = self.eth_api().clone();
772 OtterscanApi::new(eth_api)
773 }
774}
775
776impl<N, Provider, Pool, Network, EthApi, EvmConfig, Consensus>
777 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
778where
779 N: NodePrimitives,
780 Provider: FullRpcProvider<
781 Block = N::Block,
782 Header = N::BlockHeader,
783 Transaction = N::SignedTx,
784 Receipt = N::Receipt,
785 > + ChangeSetReader,
786 Network: NetworkInfo + Peers + Clone + 'static,
787 EthApi: EthApiTypes,
788 EvmConfig: ConfigureEvm<Primitives = N>,
789{
790 pub fn trace_api(&self) -> TraceApi<EthApi> {
796 TraceApi::new(
797 self.eth_api().clone(),
798 self.blocking_pool_guard.clone(),
799 self.eth_config.clone(),
800 )
801 }
802
803 pub fn bundle_api(&self) -> EthBundle<EthApi>
809 where
810 EthApi: EthTransactions + Call,
811 {
812 let eth_api = self.eth_api().clone();
813 EthBundle::new(eth_api, self.blocking_pool_guard.clone())
814 }
815
816 pub fn debug_api(&self) -> DebugApi<EthApi>
822 where
823 EthApi: FullEthApiTypes,
824 {
825 DebugApi::new(
826 self.eth_api().clone(),
827 self.blocking_pool_guard.clone(),
828 self.tasks(),
829 self.engine_events.new_listener(),
830 )
831 }
832
833 pub fn net_api(&self) -> NetApi<Network, EthApi>
839 where
840 EthApi: EthApiSpec,
841 {
842 let eth_api = self.eth_api().clone();
843 NetApi::new(self.network.clone(), eth_api)
844 }
845
846 pub fn reth_api(&self) -> RethApi<Provider, EvmConfig> {
848 RethApi::new(
849 self.provider.clone(),
850 self.evm_config.clone(),
851 self.blocking_pool_guard.clone(),
852 self.executor.clone(),
853 )
854 }
855}
856
857impl<N, Provider, Pool, Network, EthApi, EvmConfig, Consensus>
858 RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
859where
860 N: NodePrimitives,
861 Provider: FullRpcProvider<Block = N::Block>
862 + CanonStateSubscriptions<Primitives = N>
863 + ForkChoiceSubscriptions<Header = N::BlockHeader>
864 + PersistedBlockSubscriptions
865 + ChangeSetReader,
866 Pool: TransactionPool + 'static,
867 Network: NetworkInfo + Peers + Clone + 'static,
868 EthApi: FullEthApiServer,
869 EvmConfig: ConfigureEvm<Primitives = N> + 'static,
870 Consensus: FullConsensus<N> + Clone + 'static,
871{
872 pub fn create_auth_module<Payload>(
879 &self,
880 engine_api: impl IntoEngineApiRpcModule,
881 beacon_engine_handle: ConsensusEngineHandle<Payload>,
882 ) -> AuthRpcModule
883 where
884 Payload: PayloadTypes,
885 {
886 let mut module = engine_api.into_rpc_module();
887
888 let reth_engine_api = RethEngineApi::new(beacon_engine_handle);
890 module
891 .merge(RethEngineApiServer::into_rpc(reth_engine_api).remove_context())
892 .expect("No conflicting methods");
893
894 let eth_handlers = self.eth_handlers();
896 let engine_eth = EngineEthApi::new(eth_handlers.api.clone(), eth_handlers.filter.clone());
897
898 module.merge(engine_eth.into_rpc()).expect("No conflicting methods");
899
900 AuthRpcModule { inner: module }
901 }
902
903 fn maybe_module(&mut self, config: Option<&RpcModuleSelection>) -> Option<RpcModule<()>> {
905 config.map(|config| self.module_for(config))
906 }
907
908 pub fn create_transport_rpc_modules(
912 &mut self,
913 config: TransportRpcModuleConfig,
914 ) -> TransportRpcModules<()> {
915 let mut modules = TransportRpcModules::default();
916 let http = self.maybe_module(config.http.as_ref());
917 let ws = self.maybe_module(config.ws.as_ref());
918 let ipc = self.maybe_module(config.ipc.as_ref());
919
920 modules.config = config;
921 modules.http = http;
922 modules.ws = ws;
923 modules.ipc = ipc;
924 modules
925 }
926
927 pub fn module_for(&mut self, config: &RpcModuleSelection) -> RpcModule<()> {
930 let mut module = RpcModule::new(());
931 let all_methods = self.reth_methods(config.iter_selection());
932 for methods in all_methods {
933 module.merge(methods).expect("No conflicts");
934 }
935 module
936 }
937
938 pub fn reth_methods(
947 &mut self,
948 namespaces: impl Iterator<Item = RethRpcModule>,
949 ) -> Vec<Methods> {
950 let EthHandlers { api: eth_api, filter: eth_filter, pubsub: eth_pubsub, .. } =
951 self.eth_handlers().clone();
952
953 let namespaces: Vec<_> = namespaces.collect();
955 namespaces
956 .iter()
957 .map(|namespace| {
958 if matches!(namespace, RethRpcModule::Rpc) {
961 return RPCApi::new(
962 namespaces
963 .iter()
964 .map(|module| (module.to_string(), "1.0".to_string()))
965 .collect(),
966 )
967 .into_rpc()
968 .into();
969 }
970
971 self.modules
972 .entry(namespace.clone())
973 .or_insert_with(|| match namespace.clone() {
974 RethRpcModule::Admin => AdminApi::new(
975 self.network.clone(),
976 self.provider.chain_spec(),
977 self.pool.clone(),
978 )
979 .into_rpc()
980 .into(),
981 RethRpcModule::Debug => DebugApi::new(
982 eth_api.clone(),
983 self.blocking_pool_guard.clone(),
984 &self.executor,
985 self.engine_events.new_listener(),
986 )
987 .into_rpc()
988 .into(),
989 RethRpcModule::Eth => {
990 let mut module = eth_api.clone().into_rpc();
992 module.merge(eth_filter.clone().into_rpc()).expect("No conflicts");
993 module.merge(eth_pubsub.clone().into_rpc()).expect("No conflicts");
994 module
995 .merge(
996 EthBundle::new(
997 eth_api.clone(),
998 self.blocking_pool_guard.clone(),
999 )
1000 .into_rpc(),
1001 )
1002 .expect("No conflicts");
1003
1004 module.into()
1005 }
1006 RethRpcModule::Net => {
1007 NetApi::new(self.network.clone(), eth_api.clone()).into_rpc().into()
1008 }
1009 RethRpcModule::Trace => TraceApi::new(
1010 eth_api.clone(),
1011 self.blocking_pool_guard.clone(),
1012 self.eth_config.clone(),
1013 )
1014 .into_rpc()
1015 .into(),
1016 RethRpcModule::Web3 => Web3Api::new(self.network.clone()).into_rpc().into(),
1017 RethRpcModule::Txpool => TxPoolApi::new(
1018 self.eth.api.pool().clone(),
1019 dyn_clone::clone(self.eth.api.converter()),
1020 )
1021 .into_rpc()
1022 .into(),
1023 RethRpcModule::Ots => OtterscanApi::new(eth_api.clone()).into_rpc().into(),
1024 RethRpcModule::Reth => RethApi::new(
1025 self.provider.clone(),
1026 self.evm_config.clone(),
1027 self.blocking_pool_guard.clone(),
1028 self.executor.clone(),
1029 )
1030 .into_rpc()
1031 .into(),
1032 RethRpcModule::Miner => MinerApi::default().into_rpc().into(),
1033 RethRpcModule::Mev => {
1034 EthSimBundle::new(eth_api.clone(), self.blocking_pool_guard.clone())
1035 .into_rpc()
1036 .into()
1037 }
1038 RethRpcModule::Rpc |
1042 RethRpcModule::Flashbots |
1043 RethRpcModule::Testing |
1044 RethRpcModule::Other(_) => Default::default(),
1045 })
1046 .clone()
1047 })
1048 .collect::<Vec<_>>()
1049 }
1050}
1051
1052impl<Provider, Pool, Network, EthApi, EvmConfig, Consensus> Clone
1053 for RpcRegistryInner<Provider, Pool, Network, EthApi, EvmConfig, Consensus>
1054where
1055 EthApi: EthApiTypes,
1056 Provider: Clone,
1057 Pool: Clone,
1058 Network: Clone,
1059 EvmConfig: Clone,
1060 Consensus: Clone,
1061{
1062 fn clone(&self) -> Self {
1063 Self {
1064 provider: self.provider.clone(),
1065 pool: self.pool.clone(),
1066 network: self.network.clone(),
1067 executor: self.executor.clone(),
1068 evm_config: self.evm_config.clone(),
1069 consensus: self.consensus.clone(),
1070 eth: self.eth.clone(),
1071 blocking_pool_guard: self.blocking_pool_guard.clone(),
1072 modules: self.modules.clone(),
1073 eth_config: self.eth_config.clone(),
1074 engine_events: self.engine_events.clone(),
1075 }
1076 }
1077}
1078
1079#[derive(Debug)]
1091pub struct RpcServerConfig<RpcMiddleware = Identity> {
1092 http_server_config: Option<ServerConfigBuilder>,
1094 http_cors_domains: Option<String>,
1096 http_addr: Option<SocketAddr>,
1098 http_disable_compression: bool,
1100 http_compression_algorithms: Option<Vec<String>>,
1104 http_decompression_algorithms: Option<Vec<String>>,
1108 http_max_request_body_size: Option<u32>,
1110 ws_server_config: Option<ServerConfigBuilder>,
1112 ws_cors_domains: Option<String>,
1114 ws_addr: Option<SocketAddr>,
1116 ipc_server_config: Option<IpcServerBuilder<Identity>>,
1118 ipc_endpoint: Option<String>,
1120 jwt_secret: Option<JwtSecret>,
1122 rpc_metrics_enabled: bool,
1124 rpc_middleware: RpcMiddleware,
1126}
1127
1128impl Default for RpcServerConfig<Identity> {
1131 fn default() -> Self {
1133 Self {
1134 http_server_config: None,
1135 http_cors_domains: None,
1136 http_addr: None,
1137 http_disable_compression: false,
1138 http_compression_algorithms: None,
1139 http_decompression_algorithms: None,
1140 http_max_request_body_size: None,
1141 ws_server_config: None,
1142 ws_cors_domains: None,
1143 ws_addr: None,
1144 ipc_server_config: None,
1145 ipc_endpoint: None,
1146 jwt_secret: None,
1147 rpc_metrics_enabled: true,
1148 rpc_middleware: Default::default(),
1149 }
1150 }
1151}
1152
1153impl RpcServerConfig {
1154 pub fn http(config: ServerConfigBuilder) -> Self {
1156 Self::default().with_http(config)
1157 }
1158
1159 pub fn ws(config: ServerConfigBuilder) -> Self {
1161 Self::default().with_ws(config)
1162 }
1163
1164 pub fn ipc(config: IpcServerBuilder<Identity>) -> Self {
1166 Self::default().with_ipc(config)
1167 }
1168
1169 pub fn with_http(mut self, config: ServerConfigBuilder) -> Self {
1174 self.http_server_config =
1175 Some(config.set_id_provider(EthSubscriptionIdProvider::default()));
1176 self
1177 }
1178
1179 pub fn with_ws(mut self, config: ServerConfigBuilder) -> Self {
1184 self.ws_server_config = Some(config.set_id_provider(EthSubscriptionIdProvider::default()));
1185 self
1186 }
1187
1188 pub fn with_ipc(mut self, config: IpcServerBuilder<Identity>) -> Self {
1193 self.ipc_server_config = Some(config.set_id_provider(EthSubscriptionIdProvider::default()));
1194 self
1195 }
1196}
1197
1198impl<RpcMiddleware> RpcServerConfig<RpcMiddleware> {
1199 pub fn set_rpc_middleware<T>(self, rpc_middleware: T) -> RpcServerConfig<T> {
1201 RpcServerConfig {
1202 http_server_config: self.http_server_config,
1203 http_cors_domains: self.http_cors_domains,
1204 http_addr: self.http_addr,
1205 http_disable_compression: self.http_disable_compression,
1206 http_compression_algorithms: self.http_compression_algorithms,
1207 http_decompression_algorithms: self.http_decompression_algorithms,
1208 http_max_request_body_size: self.http_max_request_body_size,
1209 ws_server_config: self.ws_server_config,
1210 ws_cors_domains: self.ws_cors_domains,
1211 ws_addr: self.ws_addr,
1212 ipc_server_config: self.ipc_server_config,
1213 ipc_endpoint: self.ipc_endpoint,
1214 jwt_secret: self.jwt_secret,
1215 rpc_metrics_enabled: self.rpc_metrics_enabled,
1216 rpc_middleware,
1217 }
1218 }
1219
1220 pub const fn with_rpc_metrics_enabled(mut self, enabled: bool) -> Self {
1222 self.rpc_metrics_enabled = enabled;
1223 self
1224 }
1225
1226 pub fn with_cors(self, cors_domain: Option<String>) -> Self {
1228 self.with_http_cors(cors_domain.clone()).with_ws_cors(cors_domain)
1229 }
1230
1231 pub fn with_ws_cors(mut self, cors_domain: Option<String>) -> Self {
1233 self.ws_cors_domains = cors_domain;
1234 self
1235 }
1236
1237 pub fn with_http_cors(mut self, cors_domain: Option<String>) -> Self {
1239 self.http_cors_domains = cors_domain;
1240 self
1241 }
1242
1243 pub const fn with_http_disable_compression(mut self, http_disable_compression: bool) -> Self {
1245 self.http_disable_compression = http_disable_compression;
1246 self
1247 }
1248
1249 pub fn with_http_compression_algorithms(mut self, algos: Option<Vec<String>>) -> Self {
1254 self.http_compression_algorithms = algos;
1255 self
1256 }
1257
1258 pub fn with_http_decompression(mut self, algos: Option<Vec<String>>, max_size: u32) -> Self {
1262 self.http_decompression_algorithms = algos;
1263 self.http_max_request_body_size = Some(max_size);
1264 self
1265 }
1266
1267 pub const fn with_http_address(mut self, addr: SocketAddr) -> Self {
1272 self.http_addr = Some(addr);
1273 self
1274 }
1275
1276 pub const fn with_ws_address(mut self, addr: SocketAddr) -> Self {
1281 self.ws_addr = Some(addr);
1282 self
1283 }
1284
1285 pub fn with_id_provider<I>(mut self, id_provider: I) -> Self
1289 where
1290 I: IdProvider + Clone + 'static,
1291 {
1292 if let Some(config) = self.http_server_config {
1293 self.http_server_config = Some(config.set_id_provider(id_provider.clone()));
1294 }
1295 if let Some(config) = self.ws_server_config {
1296 self.ws_server_config = Some(config.set_id_provider(id_provider.clone()));
1297 }
1298 if let Some(ipc) = self.ipc_server_config {
1299 self.ipc_server_config = Some(ipc.set_id_provider(id_provider));
1300 }
1301
1302 self
1303 }
1304
1305 pub fn with_ipc_endpoint(mut self, path: impl Into<String>) -> Self {
1309 self.ipc_endpoint = Some(path.into());
1310 self
1311 }
1312
1313 pub const fn with_jwt_secret(mut self, secret: Option<JwtSecret>) -> Self {
1315 self.jwt_secret = secret;
1316 self
1317 }
1318
1319 pub fn with_tokio_runtime(mut self, tokio_runtime: Option<tokio::runtime::Handle>) -> Self {
1321 let Some(tokio_runtime) = tokio_runtime else { return self };
1322 if let Some(http_server_config) = self.http_server_config {
1323 self.http_server_config =
1324 Some(http_server_config.custom_tokio_runtime(tokio_runtime.clone()));
1325 }
1326 if let Some(ws_server_config) = self.ws_server_config {
1327 self.ws_server_config =
1328 Some(ws_server_config.custom_tokio_runtime(tokio_runtime.clone()));
1329 }
1330 if let Some(ipc_server_config) = self.ipc_server_config {
1331 self.ipc_server_config = Some(ipc_server_config.custom_tokio_runtime(tokio_runtime));
1332 }
1333 self
1334 }
1335
1336 pub const fn has_server(&self) -> bool {
1340 self.http_server_config.is_some() ||
1341 self.ws_server_config.is_some() ||
1342 self.ipc_server_config.is_some()
1343 }
1344
1345 pub const fn http_address(&self) -> Option<SocketAddr> {
1347 self.http_addr
1348 }
1349
1350 pub const fn ws_address(&self) -> Option<SocketAddr> {
1352 self.ws_addr
1353 }
1354
1355 pub fn ipc_endpoint(&self) -> Option<String> {
1357 self.ipc_endpoint.clone()
1358 }
1359
1360 pub const fn rpc_metrics_enabled(&self) -> bool {
1362 self.rpc_metrics_enabled
1363 }
1364
1365 fn maybe_cors_layer(cors: Option<String>) -> Result<Option<CorsLayer>, CorsDomainError> {
1367 cors.as_deref().map(cors::create_cors_layer).transpose()
1368 }
1369
1370 fn maybe_jwt_layer(jwt_secret: Option<JwtSecret>) -> Option<AuthLayer<JwtAuthValidator>> {
1372 jwt_secret.map(|secret| AuthLayer::new(JwtAuthValidator::new(secret)))
1373 }
1374
1375 fn maybe_compression_layer(
1381 addr: SocketAddr,
1382 disable_compression: bool,
1383 algos: Option<&[String]>,
1384 ) -> Option<CompressionLayer> {
1385 if disable_compression || addr.ip().to_canonical().is_loopback() {
1386 None
1387 } else {
1388 match algos {
1389 None => Some(CompressionLayer::new()),
1391 Some(algos) => Some(CompressionLayer::with_algorithms(algos)),
1392 }
1393 }
1394 }
1395
1396 fn maybe_decompression_layer(
1402 max_request_body_size: Option<u32>,
1403 algos: Option<&[String]>,
1404 ) -> Option<DecompressionLayer> {
1405 let algos = algos?;
1406 if algos.is_empty() {
1407 return None;
1408 }
1409
1410 let max = max_request_body_size?;
1411 Some(DecompressionLayer::new(algos, max as usize))
1412 }
1413
1414 pub async fn start(self, modules: &TransportRpcModules) -> Result<RpcServerHandle, RpcError>
1420 where
1421 RpcMiddleware: RethRpcMiddleware,
1422 {
1423 let mut http_handle = None;
1424 let mut ws_handle = None;
1425 let mut ipc_handle = None;
1426
1427 let http_socket_addr = self.http_addr.unwrap_or(SocketAddr::V4(SocketAddrV4::new(
1428 Ipv4Addr::LOCALHOST,
1429 constants::DEFAULT_HTTP_RPC_PORT,
1430 )));
1431
1432 let ws_socket_addr = self.ws_addr.unwrap_or(SocketAddr::V4(SocketAddrV4::new(
1433 Ipv4Addr::LOCALHOST,
1434 constants::DEFAULT_WS_RPC_PORT,
1435 )));
1436
1437 let rpc_metrics_enabled = self.rpc_metrics_enabled;
1438 let ipc_path =
1439 self.ipc_endpoint.clone().unwrap_or_else(|| constants::DEFAULT_IPC_ENDPOINT.into());
1440
1441 if let Some(builder) = self.ipc_server_config {
1442 let ipc = builder
1443 .set_rpc_middleware(
1444 IpcRpcServiceBuilder::new().option_layer(
1445 rpc_metrics_enabled
1446 .then(|| modules.ipc.as_ref().map(RpcRequestMetrics::ipc))
1447 .flatten(),
1448 ),
1449 )
1450 .build(ipc_path);
1451 ipc_handle = Some(ipc.start(modules.ipc.clone().expect("ipc server error")).await?);
1452 }
1453
1454 if self.http_addr == self.ws_addr &&
1456 self.http_server_config.is_some() &&
1457 self.ws_server_config.is_some()
1458 {
1459 let cors = match (self.ws_cors_domains.as_ref(), self.http_cors_domains.as_ref()) {
1460 (Some(ws_cors), Some(http_cors)) => {
1461 if ws_cors.trim() != http_cors.trim() {
1462 return Err(WsHttpSamePortError::ConflictingCorsDomains {
1463 http_cors_domains: Some(http_cors.clone()),
1464 ws_cors_domains: Some(ws_cors.clone()),
1465 }
1466 .into());
1467 }
1468 Some(ws_cors)
1469 }
1470 (a, b) => a.or(b),
1471 }
1472 .cloned();
1473
1474 modules.config.ensure_ws_http_identical()?;
1476
1477 if let Some(config) = self.http_server_config {
1478 let server = ServerBuilder::new()
1479 .set_http_middleware(
1480 tower::ServiceBuilder::new()
1481 .option_layer(Self::maybe_cors_layer(cors.clone())?)
1482 .option_layer(Self::maybe_jwt_layer(self.jwt_secret))
1483 .option_layer(Self::maybe_decompression_layer(
1484 self.http_max_request_body_size,
1485 self.http_decompression_algorithms.as_deref(),
1486 ))
1487 .option_layer(Self::maybe_compression_layer(
1488 http_socket_addr,
1489 self.http_disable_compression,
1490 self.http_compression_algorithms.as_deref(),
1491 ))
1492 .layer(ValidateRequestHeaderLayer::custom(
1493 cors::WsOriginValidator::new(cors.as_deref())?,
1494 )),
1495 )
1496 .set_rpc_middleware(
1497 RpcServiceBuilder::default()
1498 .option_layer(
1499 rpc_metrics_enabled
1500 .then(|| {
1501 modules
1502 .http
1503 .as_ref()
1504 .or(modules.ws.as_ref())
1505 .map(RpcRequestMetrics::same_port)
1506 })
1507 .flatten(),
1508 )
1509 .layer(self.rpc_middleware.clone()),
1510 )
1511 .set_config(config.build())
1512 .build(http_socket_addr)
1513 .await
1514 .map_err(|err| {
1515 RpcError::server_error(err, ServerKind::WsHttp(http_socket_addr))
1516 })?;
1517 let addr = server.local_addr().map_err(|err| {
1518 RpcError::server_error(err, ServerKind::WsHttp(http_socket_addr))
1519 })?;
1520 if let Some(module) = modules.http.as_ref().or(modules.ws.as_ref()) {
1521 http_handle = Some(server.start(module.clone()));
1523 }
1524 return Ok(RpcServerHandle {
1525 http_local_addr: Some(addr),
1526 ws_local_addr: Some(addr),
1527 http: http_handle,
1528 ws: ws_handle,
1529 ipc_endpoint: self.ipc_endpoint.clone(),
1530 ipc: ipc_handle,
1531 jwt_secret: self.jwt_secret,
1532 });
1533 }
1534 }
1535
1536 let mut ws_local_addr = None;
1537 let mut ws_server = None;
1538 let mut http_local_addr = None;
1539 let mut http_server = None;
1540
1541 if let Some(config) = self.ws_server_config {
1542 let server = ServerBuilder::new()
1543 .set_config(config.ws_only().build())
1544 .set_http_middleware(
1545 tower::ServiceBuilder::new()
1546 .option_layer(Self::maybe_cors_layer(self.ws_cors_domains.clone())?)
1547 .option_layer(Self::maybe_jwt_layer(self.jwt_secret))
1548 .layer(ValidateRequestHeaderLayer::custom(cors::WsOriginValidator::new(
1549 self.ws_cors_domains.as_deref(),
1550 )?)),
1551 )
1552 .set_rpc_middleware(
1553 RpcServiceBuilder::default()
1554 .option_layer(
1555 rpc_metrics_enabled
1556 .then(|| modules.ws.as_ref().map(RpcRequestMetrics::ws))
1557 .flatten(),
1558 )
1559 .layer(self.rpc_middleware.clone()),
1560 )
1561 .build(ws_socket_addr)
1562 .await
1563 .map_err(|err| RpcError::server_error(err, ServerKind::WS(ws_socket_addr)))?;
1564
1565 let addr = server
1566 .local_addr()
1567 .map_err(|err| RpcError::server_error(err, ServerKind::WS(ws_socket_addr)))?;
1568
1569 ws_local_addr = Some(addr);
1570 ws_server = Some(server);
1571 }
1572
1573 if let Some(config) = self.http_server_config {
1574 let server = ServerBuilder::new()
1575 .set_config(config.http_only().build())
1576 .set_http_middleware(
1577 tower::ServiceBuilder::new()
1578 .option_layer(Self::maybe_cors_layer(self.http_cors_domains.clone())?)
1579 .option_layer(Self::maybe_jwt_layer(self.jwt_secret))
1580 .option_layer(Self::maybe_decompression_layer(
1581 self.http_max_request_body_size,
1582 self.http_decompression_algorithms.as_deref(),
1583 ))
1584 .option_layer(Self::maybe_compression_layer(
1585 http_socket_addr,
1586 self.http_disable_compression,
1587 self.http_compression_algorithms.as_deref(),
1588 )),
1589 )
1590 .set_rpc_middleware(
1591 RpcServiceBuilder::default()
1592 .option_layer(
1593 rpc_metrics_enabled
1594 .then(|| modules.http.as_ref().map(RpcRequestMetrics::http))
1595 .flatten(),
1596 )
1597 .layer(self.rpc_middleware.clone()),
1598 )
1599 .build(http_socket_addr)
1600 .await
1601 .map_err(|err| RpcError::server_error(err, ServerKind::Http(http_socket_addr)))?;
1602 let local_addr = server
1603 .local_addr()
1604 .map_err(|err| RpcError::server_error(err, ServerKind::Http(http_socket_addr)))?;
1605 http_local_addr = Some(local_addr);
1606 http_server = Some(server);
1607 }
1608
1609 http_handle = http_server
1610 .map(|http_server| http_server.start(modules.http.clone().expect("http server error")));
1611 ws_handle = ws_server
1612 .map(|ws_server| ws_server.start(modules.ws.clone().expect("ws server error")));
1613 Ok(RpcServerHandle {
1614 http_local_addr,
1615 ws_local_addr,
1616 http: http_handle,
1617 ws: ws_handle,
1618 ipc_endpoint: self.ipc_endpoint.clone(),
1619 ipc: ipc_handle,
1620 jwt_secret: self.jwt_secret,
1621 })
1622 }
1623}
1624
1625#[derive(Debug, Clone, Default, Eq, PartialEq)]
1637pub struct TransportRpcModuleConfig {
1638 http: Option<RpcModuleSelection>,
1640 ws: Option<RpcModuleSelection>,
1642 ipc: Option<RpcModuleSelection>,
1644 config: Option<RpcModuleConfig>,
1646}
1647
1648impl TransportRpcModuleConfig {
1651 pub fn set_http(http: impl Into<RpcModuleSelection>) -> Self {
1653 Self::default().with_http(http)
1654 }
1655
1656 pub fn set_ws(ws: impl Into<RpcModuleSelection>) -> Self {
1658 Self::default().with_ws(ws)
1659 }
1660
1661 pub fn set_ipc(ipc: impl Into<RpcModuleSelection>) -> Self {
1663 Self::default().with_ipc(ipc)
1664 }
1665
1666 pub fn with_http(mut self, http: impl Into<RpcModuleSelection>) -> Self {
1668 self.http = Some(http.into());
1669 self
1670 }
1671
1672 pub fn with_ws(mut self, ws: impl Into<RpcModuleSelection>) -> Self {
1674 self.ws = Some(ws.into());
1675 self
1676 }
1677
1678 pub fn with_ipc(mut self, ipc: impl Into<RpcModuleSelection>) -> Self {
1680 self.ipc = Some(ipc.into());
1681 self
1682 }
1683
1684 pub fn with_config(mut self, config: RpcModuleConfig) -> Self {
1686 self.config = Some(config);
1687 self
1688 }
1689
1690 pub const fn http_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1692 &mut self.http
1693 }
1694
1695 pub const fn ws_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1697 &mut self.ws
1698 }
1699
1700 pub const fn ipc_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1702 &mut self.ipc
1703 }
1704
1705 pub const fn config_mut(&mut self) -> &mut Option<RpcModuleConfig> {
1707 &mut self.config
1708 }
1709
1710 pub const fn is_empty(&self) -> bool {
1712 self.http.is_none() && self.ws.is_none() && self.ipc.is_none()
1713 }
1714
1715 pub const fn http(&self) -> Option<&RpcModuleSelection> {
1717 self.http.as_ref()
1718 }
1719
1720 pub const fn ws(&self) -> Option<&RpcModuleSelection> {
1722 self.ws.as_ref()
1723 }
1724
1725 pub const fn ipc(&self) -> Option<&RpcModuleSelection> {
1727 self.ipc.as_ref()
1728 }
1729
1730 pub const fn config(&self) -> Option<&RpcModuleConfig> {
1732 self.config.as_ref()
1733 }
1734
1735 pub fn contains_any(&self, module: &RethRpcModule) -> bool {
1737 self.contains_http(module) || self.contains_ws(module) || self.contains_ipc(module)
1738 }
1739
1740 pub fn contains_http(&self, module: &RethRpcModule) -> bool {
1742 self.http.as_ref().is_some_and(|http| http.contains(module))
1743 }
1744
1745 pub fn contains_ws(&self, module: &RethRpcModule) -> bool {
1747 self.ws.as_ref().is_some_and(|ws| ws.contains(module))
1748 }
1749
1750 pub fn contains_ipc(&self, module: &RethRpcModule) -> bool {
1752 self.ipc.as_ref().is_some_and(|ipc| ipc.contains(module))
1753 }
1754
1755 fn ensure_ws_http_identical(&self) -> Result<(), WsHttpSamePortError> {
1758 if RpcModuleSelection::are_identical(self.http.as_ref(), self.ws.as_ref()) {
1759 Ok(())
1760 } else {
1761 let http_modules =
1762 self.http.as_ref().map(RpcModuleSelection::to_selection).unwrap_or_default();
1763 let ws_modules =
1764 self.ws.as_ref().map(RpcModuleSelection::to_selection).unwrap_or_default();
1765
1766 let http_not_ws = http_modules.difference(&ws_modules).cloned().collect();
1767 let ws_not_http = ws_modules.difference(&http_modules).cloned().collect();
1768 let overlap = http_modules.intersection(&ws_modules).cloned().collect();
1769
1770 Err(WsHttpSamePortError::ConflictingModules(Box::new(ConflictingModules {
1771 overlap,
1772 http_not_ws,
1773 ws_not_http,
1774 })))
1775 }
1776 }
1777}
1778
1779#[derive(Debug, Clone, Default)]
1781pub struct TransportRpcModules<Context = ()> {
1782 config: TransportRpcModuleConfig,
1784 http: Option<RpcModule<Context>>,
1786 ws: Option<RpcModule<Context>>,
1788 ipc: Option<RpcModule<Context>>,
1790}
1791
1792impl TransportRpcModules {
1795 pub fn with_config(mut self, config: TransportRpcModuleConfig) -> Self {
1798 self.config = config;
1799 self
1800 }
1801
1802 pub fn with_http(mut self, http: RpcModule<()>) -> Self {
1805 self.http = Some(http);
1806 self
1807 }
1808
1809 pub fn with_ws(mut self, ws: RpcModule<()>) -> Self {
1812 self.ws = Some(ws);
1813 self
1814 }
1815
1816 pub fn with_ipc(mut self, ipc: RpcModule<()>) -> Self {
1819 self.ipc = Some(ipc);
1820 self
1821 }
1822
1823 pub const fn module_config(&self) -> &TransportRpcModuleConfig {
1825 &self.config
1826 }
1827
1828 pub fn merge_if_module_configured(
1833 &mut self,
1834 module: RethRpcModule,
1835 other: impl Into<Methods>,
1836 ) -> Result<(), RegisterMethodError> {
1837 let other = other.into();
1838 if self.module_config().contains_http(&module) {
1839 self.merge_http(other.clone())?;
1840 }
1841 if self.module_config().contains_ws(&module) {
1842 self.merge_ws(other.clone())?;
1843 }
1844 if self.module_config().contains_ipc(&module) {
1845 self.merge_ipc(other)?;
1846 }
1847
1848 Ok(())
1849 }
1850
1851 pub fn merge_if_module_configured_with<F>(
1858 &mut self,
1859 module: RethRpcModule,
1860 f: F,
1861 ) -> Result<(), RegisterMethodError>
1862 where
1863 F: FnOnce() -> Methods,
1864 {
1865 if !self.module_config().contains_any(&module) {
1867 return Ok(());
1868 }
1869 self.merge_if_module_configured(module, f())
1870 }
1871
1872 pub fn merge_http(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
1878 if let Some(ref mut http) = self.http {
1879 return http.merge(other.into()).map(|_| true)
1880 }
1881 Ok(false)
1882 }
1883
1884 pub fn merge_ws(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
1890 if let Some(ref mut ws) = self.ws {
1891 return ws.merge(other.into()).map(|_| true)
1892 }
1893 Ok(false)
1894 }
1895
1896 pub fn merge_ipc(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
1902 if let Some(ref mut ipc) = self.ipc {
1903 return ipc.merge(other.into()).map(|_| true)
1904 }
1905 Ok(false)
1906 }
1907
1908 pub fn merge_configured(
1912 &mut self,
1913 other: impl Into<Methods>,
1914 ) -> Result<(), RegisterMethodError> {
1915 let other = other.into();
1916 self.merge_http(other.clone())?;
1917 self.merge_ws(other.clone())?;
1918 self.merge_ipc(other)?;
1919 Ok(())
1920 }
1921
1922 pub fn methods_by_module(&self, module: RethRpcModule) -> Methods {
1926 self.methods_by(|name| name.starts_with(module.as_str()))
1927 }
1928
1929 pub fn methods_by<F>(&self, mut filter: F) -> Methods
1933 where
1934 F: FnMut(&str) -> bool,
1935 {
1936 let mut methods = Methods::new();
1937
1938 let mut f =
1940 |name: &str, mm: &Methods| filter(name) && !mm.method_names().any(|m| m == name);
1941
1942 if let Some(m) = self.http_methods(|name| f(name, &methods)) {
1943 let _ = methods.merge(m);
1944 }
1945 if let Some(m) = self.ws_methods(|name| f(name, &methods)) {
1946 let _ = methods.merge(m);
1947 }
1948 if let Some(m) = self.ipc_methods(|name| f(name, &methods)) {
1949 let _ = methods.merge(m);
1950 }
1951 methods
1952 }
1953
1954 pub fn http_methods<F>(&self, filter: F) -> Option<Methods>
1958 where
1959 F: FnMut(&str) -> bool,
1960 {
1961 self.http.as_ref().map(|module| methods_by(module, filter))
1962 }
1963
1964 pub fn ws_methods<F>(&self, filter: F) -> Option<Methods>
1968 where
1969 F: FnMut(&str) -> bool,
1970 {
1971 self.ws.as_ref().map(|module| methods_by(module, filter))
1972 }
1973
1974 pub fn ipc_methods<F>(&self, filter: F) -> Option<Methods>
1978 where
1979 F: FnMut(&str) -> bool,
1980 {
1981 self.ipc.as_ref().map(|module| methods_by(module, filter))
1982 }
1983
1984 pub fn remove_http_method(&mut self, method_name: &'static str) -> bool {
1992 self.http.as_mut().is_some_and(|module| module.remove_method(method_name).is_some())
1993 }
1994
1995 pub fn remove_http_methods(&mut self, methods: impl IntoIterator<Item = &'static str>) {
1997 for name in methods {
1998 self.remove_http_method(name);
1999 }
2000 }
2001
2002 pub fn remove_ws_method(&mut self, method_name: &'static str) -> bool {
2010 self.ws.as_mut().is_some_and(|module| module.remove_method(method_name).is_some())
2011 }
2012
2013 pub fn remove_ws_methods(&mut self, methods: impl IntoIterator<Item = &'static str>) {
2015 for name in methods {
2016 self.remove_ws_method(name);
2017 }
2018 }
2019
2020 pub fn remove_ipc_method(&mut self, method_name: &'static str) -> bool {
2028 self.ipc.as_mut().is_some_and(|module| module.remove_method(method_name).is_some())
2029 }
2030
2031 pub fn remove_ipc_methods(&mut self, methods: impl IntoIterator<Item = &'static str>) {
2033 for name in methods {
2034 self.remove_ipc_method(name);
2035 }
2036 }
2037
2038 pub fn remove_method_from_configured(&mut self, method_name: &'static str) -> bool {
2042 let http_removed = self.remove_http_method(method_name);
2043 let ws_removed = self.remove_ws_method(method_name);
2044 let ipc_removed = self.remove_ipc_method(method_name);
2045
2046 http_removed || ws_removed || ipc_removed
2047 }
2048
2049 pub fn rename(
2053 &mut self,
2054 old_name: &'static str,
2055 new_method: impl Into<Methods>,
2056 ) -> Result<(), RegisterMethodError> {
2057 self.remove_method_from_configured(old_name);
2059
2060 self.merge_configured(new_method)
2062 }
2063
2064 pub fn replace_http(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
2071 let other = other.into();
2072 self.remove_http_methods(other.method_names());
2073 self.merge_http(other)
2074 }
2075
2076 pub fn replace_ipc(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
2083 let other = other.into();
2084 self.remove_ipc_methods(other.method_names());
2085 self.merge_ipc(other)
2086 }
2087
2088 pub fn replace_ws(&mut self, other: impl Into<Methods>) -> Result<bool, RegisterMethodError> {
2095 let other = other.into();
2096 self.remove_ws_methods(other.method_names());
2097 self.merge_ws(other)
2098 }
2099
2100 pub fn replace_configured(
2104 &mut self,
2105 other: impl Into<Methods>,
2106 ) -> Result<bool, RegisterMethodError> {
2107 let other = other.into();
2108 self.replace_http(other.clone())?;
2109 self.replace_ws(other.clone())?;
2110 self.replace_ipc(other)?;
2111 Ok(true)
2112 }
2113
2114 pub fn add_or_replace_http(
2118 &mut self,
2119 other: impl Into<Methods>,
2120 ) -> Result<bool, RegisterMethodError> {
2121 let other = other.into();
2122 self.remove_http_methods(other.method_names());
2123 self.merge_http(other)
2124 }
2125
2126 pub fn add_or_replace_ws(
2130 &mut self,
2131 other: impl Into<Methods>,
2132 ) -> Result<bool, RegisterMethodError> {
2133 let other = other.into();
2134 self.remove_ws_methods(other.method_names());
2135 self.merge_ws(other)
2136 }
2137
2138 pub fn add_or_replace_ipc(
2142 &mut self,
2143 other: impl Into<Methods>,
2144 ) -> Result<bool, RegisterMethodError> {
2145 let other = other.into();
2146 self.remove_ipc_methods(other.method_names());
2147 self.merge_ipc(other)
2148 }
2149
2150 pub fn add_or_replace_configured(
2152 &mut self,
2153 other: impl Into<Methods>,
2154 ) -> Result<(), RegisterMethodError> {
2155 let other = other.into();
2156 self.add_or_replace_http(other.clone())?;
2157 self.add_or_replace_ws(other.clone())?;
2158 self.add_or_replace_ipc(other)?;
2159 Ok(())
2160 }
2161 pub fn add_or_replace_if_module_configured(
2164 &mut self,
2165 module: RethRpcModule,
2166 other: impl Into<Methods>,
2167 ) -> Result<(), RegisterMethodError> {
2168 let other = other.into();
2169 if self.module_config().contains_http(&module) {
2170 self.add_or_replace_http(other.clone())?;
2171 }
2172 if self.module_config().contains_ws(&module) {
2173 self.add_or_replace_ws(other.clone())?;
2174 }
2175 if self.module_config().contains_ipc(&module) {
2176 self.add_or_replace_ipc(other)?;
2177 }
2178 Ok(())
2179 }
2180}
2181
2182fn methods_by<T, F>(module: &RpcModule<T>, mut filter: F) -> Methods
2184where
2185 F: FnMut(&str) -> bool,
2186{
2187 let mut methods = Methods::new();
2188 let method_names = module.method_names().filter(|name| filter(name));
2189
2190 for name in method_names {
2191 if let Some(matched_method) = module.method(name).cloned() {
2192 let _ = methods.verify_and_insert(name, matched_method);
2193 }
2194 }
2195
2196 methods
2197}
2198
2199#[derive(Clone, Debug)]
2204#[must_use = "Server stops if dropped"]
2205pub struct RpcServerHandle {
2206 http_local_addr: Option<SocketAddr>,
2208 ws_local_addr: Option<SocketAddr>,
2209 http: Option<ServerHandle>,
2210 ws: Option<ServerHandle>,
2211 ipc_endpoint: Option<String>,
2212 ipc: Option<jsonrpsee::server::ServerHandle>,
2213 jwt_secret: Option<JwtSecret>,
2214}
2215
2216impl RpcServerHandle {
2219 fn bearer_token(&self) -> Option<String> {
2221 self.jwt_secret.as_ref().map(|secret| {
2222 format!(
2223 "Bearer {}",
2224 secret
2225 .encode(&Claims {
2226 iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() +
2227 Duration::from_secs(60))
2228 .as_secs(),
2229 exp: None,
2230 })
2231 .unwrap()
2232 )
2233 })
2234 }
2235 pub const fn http_local_addr(&self) -> Option<SocketAddr> {
2237 self.http_local_addr
2238 }
2239
2240 pub const fn ws_local_addr(&self) -> Option<SocketAddr> {
2242 self.ws_local_addr
2243 }
2244
2245 pub fn stop(self) -> Result<(), AlreadyStoppedError> {
2247 let shared_server =
2250 self.http_local_addr.is_some() && self.http_local_addr == self.ws_local_addr;
2251
2252 if let Some(handle) = self.http {
2253 handle.stop()?
2254 }
2255
2256 if let Some(handle) = self.ws.filter(|_| !shared_server) {
2257 handle.stop()?
2258 }
2259
2260 if let Some(handle) = self.ipc {
2261 handle.stop()?
2262 }
2263
2264 Ok(())
2265 }
2266
2267 pub fn ipc_endpoint(&self) -> Option<String> {
2269 self.ipc_endpoint.clone()
2270 }
2271
2272 pub fn http_url(&self) -> Option<String> {
2274 self.http_local_addr.map(|addr| format!("http://{addr}"))
2275 }
2276
2277 pub fn ws_url(&self) -> Option<String> {
2279 self.ws_local_addr.map(|addr| format!("ws://{addr}"))
2280 }
2281
2282 pub fn http_client(&self) -> Option<RpcClient> {
2286 let url = self.http_url()?.parse().expect("valid http url");
2287 let client = match self.jwt_secret {
2288 Some(secret) => ClientBuilder::default().layer(AuthClientLayer::new(secret)).http(url),
2289 None => ClientBuilder::default().http(url),
2290 };
2291 Some(client)
2292 }
2293
2294 pub async fn ws_client(&self) -> Option<RpcClient> {
2296 let mut connect = WsConnect::new(self.ws_url()?);
2297 if let Some(token) = self.bearer_token() {
2298 connect = connect.with_auth(Authorization::raw(token));
2299 }
2300 let client =
2301 ClientBuilder::default().ws(connect).await.expect("failed to create ws client");
2302 Some(client)
2303 }
2304
2305 pub fn eth_http_provider(
2307 &self,
2308 ) -> Option<impl Provider<alloy_network::Ethereum> + Clone + Unpin + 'static> {
2309 self.new_http_provider_for()
2310 }
2311
2312 pub fn eth_http_provider_with_wallet<W>(
2315 &self,
2316 wallet: W,
2317 ) -> Option<impl Provider<alloy_network::Ethereum> + Clone + Unpin + 'static>
2318 where
2319 W: IntoWallet<alloy_network::Ethereum, NetworkWallet: Clone + Unpin + 'static>,
2320 {
2321 let rpc_url = self.http_url()?;
2322 let provider =
2323 ProviderBuilder::new().wallet(wallet).connect_http(rpc_url.parse().expect("valid url"));
2324 Some(provider)
2325 }
2326
2327 pub fn new_http_provider_for<N>(&self) -> Option<impl Provider<N> + Clone + Unpin + 'static>
2332 where
2333 N: RecommendedFillers<RecommendedFillers: Unpin>,
2334 {
2335 let rpc_url = self.http_url()?;
2336 let provider = ProviderBuilder::default()
2337 .with_recommended_fillers()
2338 .connect_http(rpc_url.parse().expect("valid url"));
2339 Some(provider)
2340 }
2341
2342 pub async fn eth_ws_provider(
2344 &self,
2345 ) -> Option<impl Provider<alloy_network::Ethereum> + Clone + Unpin + 'static> {
2346 self.new_ws_provider_for().await
2347 }
2348
2349 pub async fn eth_ws_provider_with_wallet<W>(
2352 &self,
2353 wallet: W,
2354 ) -> Option<impl Provider<alloy_network::Ethereum> + Clone + Unpin + 'static>
2355 where
2356 W: IntoWallet<alloy_network::Ethereum, NetworkWallet: Clone + Unpin + 'static>,
2357 {
2358 let rpc_url = self.ws_url()?;
2359 let provider = ProviderBuilder::new()
2360 .wallet(wallet)
2361 .connect(&rpc_url)
2362 .await
2363 .expect("failed to create ws client");
2364 Some(provider)
2365 }
2366
2367 pub async fn new_ws_provider_for<N>(&self) -> Option<impl Provider<N> + Clone + Unpin + 'static>
2372 where
2373 N: RecommendedFillers<RecommendedFillers: Unpin>,
2374 {
2375 let rpc_url = self.ws_url()?;
2376 let provider = ProviderBuilder::default()
2377 .with_recommended_fillers()
2378 .connect(&rpc_url)
2379 .await
2380 .expect("failed to create ws client");
2381 Some(provider)
2382 }
2383
2384 pub async fn eth_ipc_provider(
2386 &self,
2387 ) -> Option<impl Provider<alloy_network::Ethereum> + Clone + Unpin + 'static> {
2388 self.new_ipc_provider_for().await
2389 }
2390
2391 pub async fn new_ipc_provider_for<N>(
2396 &self,
2397 ) -> Option<impl Provider<N> + Clone + Unpin + 'static>
2398 where
2399 N: RecommendedFillers<RecommendedFillers: Unpin>,
2400 {
2401 let rpc_url = self.ipc_endpoint()?;
2402 let provider = ProviderBuilder::default()
2403 .with_recommended_fillers()
2404 .connect(&rpc_url)
2405 .await
2406 .expect("failed to create ipc client");
2407 Some(provider)
2408 }
2409}
2410
2411#[cfg(test)]
2412mod tests {
2413 use super::*;
2414
2415 #[test]
2416 fn parse_eth_call_bundle_selection() {
2417 let selection = "eth,admin,debug".parse::<RpcModuleSelection>().unwrap();
2418 assert_eq!(
2419 selection,
2420 RpcModuleSelection::Selection(
2421 [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug,].into()
2422 )
2423 );
2424 }
2425
2426 #[test]
2427 fn parse_rpc_module_selection() {
2428 let selection = "all".parse::<RpcModuleSelection>().unwrap();
2429 assert_eq!(selection, RpcModuleSelection::All);
2430 }
2431
2432 #[test]
2433 fn parse_rpc_module_selection_none() {
2434 let selection = "none".parse::<RpcModuleSelection>().unwrap();
2435 assert_eq!(selection, RpcModuleSelection::Selection(Default::default()));
2436 }
2437
2438 #[test]
2439 fn parse_rpc_unique_module_selection() {
2440 let selection = "eth,admin,eth,net".parse::<RpcModuleSelection>().unwrap();
2441 assert_eq!(
2442 selection,
2443 RpcModuleSelection::Selection(
2444 [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Net,].into()
2445 )
2446 );
2447 }
2448
2449 #[test]
2450 fn identical_selection() {
2451 assert!(RpcModuleSelection::are_identical(
2452 Some(&RpcModuleSelection::All),
2453 Some(&RpcModuleSelection::All),
2454 ));
2455 assert!(!RpcModuleSelection::are_identical(
2456 Some(&RpcModuleSelection::All),
2457 Some(&RpcModuleSelection::Standard),
2458 ));
2459 assert!(RpcModuleSelection::are_identical(
2460 Some(&RpcModuleSelection::Selection(RpcModuleSelection::Standard.to_selection())),
2461 Some(&RpcModuleSelection::Standard),
2462 ));
2463 assert!(RpcModuleSelection::are_identical(
2464 Some(&RpcModuleSelection::Selection([RethRpcModule::Eth].into())),
2465 Some(&RpcModuleSelection::Selection([RethRpcModule::Eth].into())),
2466 ));
2467 assert!(RpcModuleSelection::are_identical(
2468 None,
2469 Some(&RpcModuleSelection::Selection(Default::default())),
2470 ));
2471 assert!(RpcModuleSelection::are_identical(
2472 Some(&RpcModuleSelection::Selection(Default::default())),
2473 None,
2474 ));
2475 assert!(RpcModuleSelection::are_identical(None, None));
2476 }
2477
2478 #[test]
2479 fn test_rpc_module_str() {
2480 macro_rules! assert_rpc_module {
2481 ($($s:expr => $v:expr,)*) => {
2482 $(
2483 let val: RethRpcModule = $s.parse().unwrap();
2484 assert_eq!(val, $v);
2485 assert_eq!(val.to_string(), $s);
2486 )*
2487 };
2488 }
2489 assert_rpc_module!
2490 (
2491 "admin" => RethRpcModule::Admin,
2492 "debug" => RethRpcModule::Debug,
2493 "eth" => RethRpcModule::Eth,
2494 "net" => RethRpcModule::Net,
2495 "trace" => RethRpcModule::Trace,
2496 "web3" => RethRpcModule::Web3,
2497 "rpc" => RethRpcModule::Rpc,
2498 "ots" => RethRpcModule::Ots,
2499 "reth" => RethRpcModule::Reth,
2500 );
2501 }
2502
2503 #[test]
2504 fn test_default_selection() {
2505 let selection = RpcModuleSelection::Standard.to_selection();
2506 assert_eq!(selection, [RethRpcModule::Eth, RethRpcModule::Net, RethRpcModule::Web3].into())
2507 }
2508
2509 #[test]
2510 fn test_create_rpc_module_config() {
2511 let selection = vec!["eth", "admin"];
2512 let config = RpcModuleSelection::try_from_selection(selection).unwrap();
2513 assert_eq!(
2514 config,
2515 RpcModuleSelection::Selection([RethRpcModule::Eth, RethRpcModule::Admin].into())
2516 );
2517 }
2518
2519 #[test]
2520 fn test_configure_transport_config() {
2521 let config = TransportRpcModuleConfig::default()
2522 .with_http([RethRpcModule::Eth, RethRpcModule::Admin]);
2523 assert_eq!(
2524 config,
2525 TransportRpcModuleConfig {
2526 http: Some(RpcModuleSelection::Selection(
2527 [RethRpcModule::Eth, RethRpcModule::Admin].into()
2528 )),
2529 ws: None,
2530 ipc: None,
2531 config: None,
2532 }
2533 )
2534 }
2535
2536 #[test]
2537 fn test_configure_transport_config_none() {
2538 let config = TransportRpcModuleConfig::default().with_http(Vec::<RethRpcModule>::new());
2539 assert_eq!(
2540 config,
2541 TransportRpcModuleConfig {
2542 http: Some(RpcModuleSelection::Selection(Default::default())),
2543 ws: None,
2544 ipc: None,
2545 config: None,
2546 }
2547 )
2548 }
2549
2550 fn create_test_module() -> RpcModule<()> {
2551 let mut module = RpcModule::new(());
2552 module.register_method("anything", |_, _| "succeed").unwrap();
2553 module
2554 }
2555
2556 #[test]
2557 fn test_remove_http_method() {
2558 let mut modules =
2559 TransportRpcModules { http: Some(create_test_module()), ..Default::default() };
2560 assert!(modules.remove_http_method("anything"));
2562
2563 assert!(!modules.remove_http_method("non_existent_method"));
2565
2566 assert!(modules.http.as_ref().unwrap().method("anything").is_none());
2568 }
2569
2570 #[test]
2571 fn test_remove_ws_method() {
2572 let mut modules =
2573 TransportRpcModules { ws: Some(create_test_module()), ..Default::default() };
2574
2575 assert!(modules.remove_ws_method("anything"));
2577
2578 assert!(!modules.remove_ws_method("non_existent_method"));
2580
2581 assert!(modules.ws.as_ref().unwrap().method("anything").is_none());
2583 }
2584
2585 #[test]
2586 fn test_remove_ipc_method() {
2587 let mut modules =
2588 TransportRpcModules { ipc: Some(create_test_module()), ..Default::default() };
2589
2590 assert!(modules.remove_ipc_method("anything"));
2592
2593 assert!(!modules.remove_ipc_method("non_existent_method"));
2595
2596 assert!(modules.ipc.as_ref().unwrap().method("anything").is_none());
2598 }
2599
2600 #[test]
2601 fn test_remove_method_from_configured() {
2602 let mut modules = TransportRpcModules {
2603 http: Some(create_test_module()),
2604 ws: Some(create_test_module()),
2605 ipc: Some(create_test_module()),
2606 ..Default::default()
2607 };
2608
2609 assert!(modules.remove_method_from_configured("anything"));
2611
2612 assert!(!modules.remove_method_from_configured("anything"));
2614
2615 assert!(!modules.remove_method_from_configured("non_existent_method"));
2617
2618 assert!(modules.http.as_ref().unwrap().method("anything").is_none());
2620 assert!(modules.ws.as_ref().unwrap().method("anything").is_none());
2621 assert!(modules.ipc.as_ref().unwrap().method("anything").is_none());
2622 }
2623
2624 #[test]
2625 fn test_transport_rpc_module_rename() {
2626 let mut modules = TransportRpcModules {
2627 http: Some(create_test_module()),
2628 ws: Some(create_test_module()),
2629 ipc: Some(create_test_module()),
2630 ..Default::default()
2631 };
2632
2633 assert!(modules.http.as_ref().unwrap().method("anything").is_some());
2635 assert!(modules.ws.as_ref().unwrap().method("anything").is_some());
2636 assert!(modules.ipc.as_ref().unwrap().method("anything").is_some());
2637
2638 assert!(modules.http.as_ref().unwrap().method("something").is_none());
2640 assert!(modules.ws.as_ref().unwrap().method("something").is_none());
2641 assert!(modules.ipc.as_ref().unwrap().method("something").is_none());
2642
2643 let mut other_module = RpcModule::new(());
2645 other_module.register_method("something", |_, _| "fails").unwrap();
2646
2647 modules.rename("anything", other_module).expect("rename failed");
2649
2650 assert!(modules.http.as_ref().unwrap().method("anything").is_none());
2652 assert!(modules.ws.as_ref().unwrap().method("anything").is_none());
2653 assert!(modules.ipc.as_ref().unwrap().method("anything").is_none());
2654
2655 assert!(modules.http.as_ref().unwrap().method("something").is_some());
2657 assert!(modules.ws.as_ref().unwrap().method("something").is_some());
2658 assert!(modules.ipc.as_ref().unwrap().method("something").is_some());
2659 }
2660
2661 #[test]
2662 fn test_replace_http_method() {
2663 let mut modules =
2664 TransportRpcModules { http: Some(create_test_module()), ..Default::default() };
2665
2666 let mut other_module = RpcModule::new(());
2667 other_module.register_method("something", |_, _| "fails").unwrap();
2668
2669 assert!(modules.replace_http(other_module.clone()).unwrap());
2670
2671 assert!(modules.http.as_ref().unwrap().method("something").is_some());
2672
2673 other_module.register_method("anything", |_, _| "fails").unwrap();
2674 assert!(modules.replace_http(other_module.clone()).unwrap());
2675
2676 assert!(modules.http.as_ref().unwrap().method("anything").is_some());
2677 }
2678 #[test]
2679 fn test_replace_ipc_method() {
2680 let mut modules =
2681 TransportRpcModules { ipc: Some(create_test_module()), ..Default::default() };
2682
2683 let mut other_module = RpcModule::new(());
2684 other_module.register_method("something", |_, _| "fails").unwrap();
2685
2686 assert!(modules.replace_ipc(other_module.clone()).unwrap());
2687
2688 assert!(modules.ipc.as_ref().unwrap().method("something").is_some());
2689
2690 other_module.register_method("anything", |_, _| "fails").unwrap();
2691 assert!(modules.replace_ipc(other_module.clone()).unwrap());
2692
2693 assert!(modules.ipc.as_ref().unwrap().method("anything").is_some());
2694 }
2695 #[test]
2696 fn test_replace_ws_method() {
2697 let mut modules =
2698 TransportRpcModules { ws: Some(create_test_module()), ..Default::default() };
2699
2700 let mut other_module = RpcModule::new(());
2701 other_module.register_method("something", |_, _| "fails").unwrap();
2702
2703 assert!(modules.replace_ws(other_module.clone()).unwrap());
2704
2705 assert!(modules.ws.as_ref().unwrap().method("something").is_some());
2706
2707 other_module.register_method("anything", |_, _| "fails").unwrap();
2708 assert!(modules.replace_ws(other_module.clone()).unwrap());
2709
2710 assert!(modules.ws.as_ref().unwrap().method("anything").is_some());
2711 }
2712
2713 #[test]
2714 fn test_replace_configured() {
2715 let mut modules = TransportRpcModules {
2716 http: Some(create_test_module()),
2717 ws: Some(create_test_module()),
2718 ipc: Some(create_test_module()),
2719 ..Default::default()
2720 };
2721 let mut other_module = RpcModule::new(());
2722 other_module.register_method("something", |_, _| "fails").unwrap();
2723
2724 assert!(modules.replace_configured(other_module).unwrap());
2725
2726 assert!(modules.http.as_ref().unwrap().method("something").is_some());
2728 assert!(modules.ipc.as_ref().unwrap().method("something").is_some());
2729 assert!(modules.ws.as_ref().unwrap().method("something").is_some());
2730
2731 assert!(modules.http.as_ref().unwrap().method("anything").is_some());
2732 assert!(modules.ipc.as_ref().unwrap().method("anything").is_some());
2733 assert!(modules.ws.as_ref().unwrap().method("anything").is_some());
2734 }
2735
2736 #[test]
2737 fn test_add_or_replace_if_module_configured() {
2738 let config = TransportRpcModuleConfig::default()
2740 .with_http([RethRpcModule::Eth])
2741 .with_ws([RethRpcModule::Eth]);
2742
2743 let mut http_module = RpcModule::new(());
2745 http_module.register_method("eth_existing", |_, _| "original").unwrap();
2746
2747 let mut ws_module = RpcModule::new(());
2749 ws_module.register_method("eth_existing", |_, _| "original").unwrap();
2750
2751 let ipc_module = RpcModule::new(());
2753
2754 let mut modules = TransportRpcModules {
2756 config,
2757 http: Some(http_module),
2758 ws: Some(ws_module),
2759 ipc: Some(ipc_module),
2760 };
2761
2762 let mut new_module = RpcModule::new(());
2764 new_module.register_method("eth_existing", |_, _| "replaced").unwrap(); new_module.register_method("eth_new", |_, _| "added").unwrap(); let new_methods: Methods = new_module.into();
2767
2768 let result = modules.add_or_replace_if_module_configured(RethRpcModule::Eth, new_methods);
2770 assert!(result.is_ok(), "Function should succeed");
2771
2772 let http = modules.http.as_ref().unwrap();
2774 assert!(http.method("eth_existing").is_some());
2775 assert!(http.method("eth_new").is_some());
2776
2777 let ws = modules.ws.as_ref().unwrap();
2779 assert!(ws.method("eth_existing").is_some());
2780 assert!(ws.method("eth_new").is_some());
2781
2782 let ipc = modules.ipc.as_ref().unwrap();
2784 assert!(ipc.method("eth_existing").is_none());
2785 assert!(ipc.method("eth_new").is_none());
2786 }
2787
2788 #[test]
2789 fn test_merge_if_module_configured_with_lazy_evaluation() {
2790 let config = TransportRpcModuleConfig::default().with_http([RethRpcModule::Eth]);
2792
2793 let mut modules =
2794 TransportRpcModules { config, http: Some(RpcModule::new(())), ws: None, ipc: None };
2795
2796 let mut closure_called = false;
2798
2799 let result = modules.merge_if_module_configured_with(RethRpcModule::Eth, || {
2801 closure_called = true;
2802 let mut methods = RpcModule::new(());
2803 methods.register_method("eth_test", |_, _| "test").unwrap();
2804 methods.into()
2805 });
2806
2807 assert!(result.is_ok());
2808 assert!(closure_called, "Closure should be called when module is configured");
2809 assert!(modules.http.as_ref().unwrap().method("eth_test").is_some());
2810
2811 closure_called = false;
2813 let result = modules.merge_if_module_configured_with(RethRpcModule::Debug, || {
2814 closure_called = true;
2815 RpcModule::new(()).into()
2816 });
2817
2818 assert!(result.is_ok());
2819 assert!(!closure_called, "Closure should NOT be called when module is not configured");
2820 }
2821
2822 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2823 async fn test_stop_rpc_servers() {
2824 let modules = TransportRpcModules::default()
2825 .with_http(create_test_module())
2826 .with_ws(create_test_module());
2827 for config in [
2828 RpcServerConfig::http(Default::default()),
2829 RpcServerConfig::ws(Default::default()),
2830 RpcServerConfig::http(Default::default()).with_ws(Default::default()),
2831 ] {
2832 let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
2833 let handle =
2834 config.with_http_address(addr).with_ws_address(addr).start(&modules).await.unwrap();
2835 let servers = handle.http.iter().chain(handle.ws.iter()).cloned().collect::<Vec<_>>();
2836 let cloned = handle.clone();
2837
2838 handle.stop().unwrap();
2839 for server in servers {
2840 tokio::time::timeout(Duration::from_secs(5), server.stopped()).await.unwrap();
2841 }
2842 assert!(matches!(cloned.stop(), Err(AlreadyStoppedError)));
2843 }
2844 }
2845}