Skip to main content

reth_rpc_builder/
lib.rs

1//! Configure reth RPC.
2//!
3//! This crate contains several builder and config types that allow to configure the selection of
4//! [`RethRpcModule`] specific to transports (ws, http, ipc).
5//!
6//! The [`RpcModuleBuilder`] is the main entrypoint for configuring all reth modules. It takes
7//! instances of components required to start the servers, such as provider impls, network and
8//! transaction pool. [`RpcModuleBuilder::build`] returns a [`TransportRpcModules`] which contains
9//! the transport specific config (what APIs are available via this transport).
10//!
11//! The [`RpcServerConfig`] is used to assemble and start the http server, ws server, ipc servers,
12//! it requires the [`TransportRpcModules`] so it can start the servers with the configured modules.
13
14#![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
78// re-export for convenience
79pub 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
87/// Auth server utilities.
88pub mod auth;
89
90/// RPC server utilities.
91pub mod config;
92
93/// Utils for installing Rpc middleware
94pub mod middleware;
95
96/// Cors utilities.
97mod cors;
98
99/// Rpc error utilities.
100pub mod error;
101
102/// Eth utils
103pub mod eth;
104pub use eth::EthHandlers;
105
106// Rpc server metrics
107mod 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
115// Rpc rate limiter
116pub mod rate_limiter;
117
118/// A builder type to configure the RPC module: See [`RpcModule`]
119///
120/// This is the main entrypoint and the easiest way to configure an RPC server.
121#[derive(Debug, Clone)]
122pub struct RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, Consensus> {
123    /// The Provider type to when creating all rpc handlers
124    provider: Provider,
125    /// The Pool type to when creating all rpc handlers
126    pool: Pool,
127    /// The Network type to when creating all rpc handlers
128    network: Network,
129    /// How additional tasks are spawned, for example in the eth pubsub namespace
130    executor: Option<Runtime>,
131    /// Defines how the EVM should be configured before execution.
132    evm_config: EvmConfig,
133    /// The consensus implementation.
134    consensus: Consensus,
135    /// Node data primitives.
136    _primitives: PhantomData<N>,
137}
138
139// === impl RpcBuilder ===
140
141impl<N, Provider, Pool, Network, EvmConfig, Consensus>
142    RpcModuleBuilder<N, Provider, Pool, Network, EvmConfig, Consensus>
143{
144    /// Create a new instance of the builder
145    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    /// Configure the provider instance.
165    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    /// Configure the transaction pool instance.
174    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    /// Configure a [`NoopTransactionPool`] instance.
183    ///
184    /// Caution: This will configure a pool API that does absolutely nothing.
185    /// This is only intended for allow easier setup of namespaces that depend on the
186    /// [`EthApi`] which requires a [`TransactionPool`] implementation.
187    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    /// Configure the network instance.
203    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    /// Configure a [`NoopNetwork`] instance.
212    ///
213    /// Caution: This will configure a network API that does absolutely nothing.
214    /// This is only intended for allow easier setup of namespaces that depend on the
215    /// [`EthApi`] which requires a [`NetworkInfo`] implementation.
216    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    /// Configure the task executor to use for additional tasks.
232    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    /// Configure the evm configuration type
246    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    /// Configure the consensus implementation.
255    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    /// Instantiates a new [`EthApiBuilder`] from the configured components.
264    #[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    /// Initializes a new [`EthApiServer`] with the configured components and default settings.
288    ///
289    /// Note: This spawns all necessary tasks.
290    ///
291    /// See also [`EthApiBuilder`].
292    #[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    /// Configures all [`RpcModule`]s specific to the given [`TransportRpcModuleConfig`] which can
329    /// be used to start the transport server(s).
330    ///
331    /// This behaves exactly as [`RpcModuleBuilder::build`] for the [`TransportRpcModules`], but
332    /// also configures the auth (engine api) server, which exposes a subset of the `eth_`
333    /// namespace.
334    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    /// Converts the builder into a [`RpcRegistryInner`] which can be used to create all
360    /// components.
361    ///
362    /// This is useful for getting access to API handlers directly
363    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    /// Configures all [`RpcModule`]s specific to the given [`TransportRpcModuleConfig`] which can
389    /// be used to start the transport server(s).
390    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/// Bundles settings for modules
424#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
425pub struct RpcModuleConfig {
426    /// `eth` namespace settings
427    eth: EthConfig,
428}
429
430// === impl RpcModuleConfig ===
431
432impl RpcModuleConfig {
433    /// Convenience method to create a new [`RpcModuleConfigBuilder`]
434    pub fn builder() -> RpcModuleConfigBuilder {
435        RpcModuleConfigBuilder::default()
436    }
437
438    /// Returns a new RPC module config given the eth namespace config
439    pub const fn new(eth: EthConfig) -> Self {
440        Self { eth }
441    }
442
443    /// Get a reference to the eth namespace config
444    pub const fn eth(&self) -> &EthConfig {
445        &self.eth
446    }
447
448    /// Get a mutable reference to the eth namespace config
449    pub const fn eth_mut(&mut self) -> &mut EthConfig {
450        &mut self.eth
451    }
452}
453
454/// Configures [`RpcModuleConfig`]
455#[derive(Clone, Debug, Default)]
456pub struct RpcModuleConfigBuilder {
457    eth: Option<EthConfig>,
458}
459
460// === impl RpcModuleConfigBuilder ===
461
462impl RpcModuleConfigBuilder {
463    /// Configures a custom eth namespace config
464    pub fn eth(mut self, eth: EthConfig) -> Self {
465        self.eth = Some(eth);
466        self
467    }
468
469    /// Consumes the type and creates the [`RpcModuleConfig`]
470    pub fn build(self) -> RpcModuleConfig {
471        let Self { eth } = self;
472        RpcModuleConfig { eth: eth.unwrap_or_default() }
473    }
474
475    /// Get a reference to the eth namespace config, if any
476    pub const fn get_eth(&self) -> Option<&EthConfig> {
477        self.eth.as_ref()
478    }
479
480    /// Get a mutable reference to the eth namespace config, if any
481    pub const fn eth_mut(&mut self) -> &mut Option<EthConfig> {
482        &mut self.eth
483    }
484
485    /// Get the eth namespace config, creating a default if none is set
486    pub fn eth_mut_or_default(&mut self) -> &mut EthConfig {
487        self.eth.get_or_insert_with(EthConfig::default)
488    }
489}
490
491/// A Helper type the holds instances of the configured modules.
492#[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    /// Holds all `eth_` namespace handlers
501    eth: EthHandlers<EthApi>,
502    /// to put trace calls behind semaphore
503    blocking_pool_guard: BlockingTaskGuard,
504    /// Contains the [Methods] of a module
505    modules: HashMap<RethRpcModule, Methods>,
506    /// eth config settings
507    eth_config: EthConfig,
508    /// Notification channel for engine API events
509    engine_events:
510        EventSender<ConsensusEngineEvent<<EthApi::RpcConvert as RpcConvert>::Primitives>>,
511}
512
513// === impl RpcRegistryInner ===
514
515impl<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    /// Creates a new, empty instance.
531    #[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    /// Returns a reference to the installed [`EthApi`].
574    pub const fn eth_api(&self) -> &EthApi {
575        &self.eth.api
576    }
577
578    /// Returns a reference to the installed [`EthHandlers`].
579    pub const fn eth_handlers(&self) -> &EthHandlers<EthApi> {
580        &self.eth
581    }
582
583    /// Returns a reference to the pool
584    pub const fn pool(&self) -> &Pool {
585        &self.pool
586    }
587
588    /// Returns a reference to the tasks type
589    pub const fn tasks(&self) -> &Runtime {
590        &self.executor
591    }
592
593    /// Returns a reference to the provider
594    pub const fn provider(&self) -> &Provider {
595        &self.provider
596    }
597
598    /// Returns a reference to the evm config
599    pub const fn evm_config(&self) -> &Evm {
600        &self.evm_config
601    }
602
603    /// Returns all installed methods
604    pub fn methods(&self) -> Vec<Methods> {
605        self.modules.values().cloned().collect()
606    }
607
608    /// Returns a merged `RpcModule`
609    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    /// Instantiates `AdminApi`
627    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    /// Instantiates `Web3Api`
636    pub fn web3_api(&self) -> Web3Api<Network> {
637        Web3Api::new(self.network.clone())
638    }
639
640    /// Register Admin Namespace
641    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    /// Register Web3 Namespace
652    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    /// Register Eth Namespace
684    ///
685    /// # Panics
686    ///
687    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
688    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    /// Registers the Otterscan namespace using the eth block and receipt helpers.
695    ///
696    /// # Panics
697    ///
698    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
699    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    /// Register Debug Namespace
709    ///
710    /// # Panics
711    ///
712    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
713    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    /// Register Trace Namespace
723    ///
724    /// # Panics
725    ///
726    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
727    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    /// Register Net Namespace
737    ///
738    /// See also [`Self::eth_api`]
739    ///
740    /// # Panics
741    ///
742    /// If called outside of the tokio runtime.
743    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    /// Register Reth namespace
753    ///
754    /// See also [`Self::eth_api`]
755    ///
756    /// # Panics
757    ///
758    /// If called outside of the tokio runtime.
759    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    /// Instantiates `OtterscanApi`
766    ///
767    /// # Panics
768    ///
769    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
770    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    /// Instantiates `TraceApi`
791    ///
792    /// # Panics
793    ///
794    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
795    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    /// Instantiates [`EthBundle`] Api
804    ///
805    /// # Panics
806    ///
807    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
808    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    /// Instantiates `DebugApi`
817    ///
818    /// # Panics
819    ///
820    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
821    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    /// Instantiates `NetApi`
834    ///
835    /// # Panics
836    ///
837    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
838    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    /// Instantiates `RethApi`
847    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    /// Configures the auth module that includes the
873    ///   * `engine_` namespace
874    ///   * `reth_` namespace
875    ///   * `api_` namespace
876    ///
877    /// Note: This does _not_ register the `engine_` in this registry.
878    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        // Merge reth_* endpoints
889        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        // also merge a subset of `eth_` handlers
895        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    /// Helper function to create a [`RpcModule`] if it's not `None`
904    fn maybe_module(&mut self, config: Option<&RpcModuleSelection>) -> Option<RpcModule<()>> {
905        config.map(|config| self.module_for(config))
906    }
907
908    /// Configure a [`TransportRpcModules`] using the current registry. This
909    /// creates [`RpcModule`] instances for the modules selected by the
910    /// `config`.
911    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    /// Populates a new [`RpcModule`] based on the selected [`RethRpcModule`]s in the given
928    /// [`RpcModuleSelection`]
929    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    /// Returns the [Methods] for the given [`RethRpcModule`]
939    ///
940    /// If this is the first time the namespace is requested, a new instance of API implementation
941    /// will be created.
942    ///
943    /// # Panics
944    ///
945    /// If called outside of the tokio runtime. See also [`Self::eth_api`]
946    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        // Create a copy, so we can list out all the methods for rpc_ api
954        let namespaces: Vec<_> = namespaces.collect();
955        namespaces
956            .iter()
957            .map(|namespace| {
958                // `rpc` lists the namespaces of the transport it is built for, so it can't be
959                // cached in `self.modules`
960                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                            // merge all eth handlers
991                            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                        // `rpc` is built above, the others are implementation specific and need
1039                        // to be handled during initialization and should be registered via
1040                        // extend_rpc_modules in the nodebuilder rpc addon stack
1041                        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/// A builder type for configuring and launching the servers that will handle RPC requests.
1080///
1081/// Supported server transports are:
1082///    - http
1083///    - ws
1084///    - ipc
1085///
1086/// Http and WS share the same settings: [`ServerBuilder`].
1087///
1088/// Once the [`RpcModule`] is built via [`RpcModuleBuilder`] the servers can be started, See also
1089/// [`ServerBuilder::build`] and [`Server::start`](jsonrpsee::server::Server::start).
1090#[derive(Debug)]
1091pub struct RpcServerConfig<RpcMiddleware = Identity> {
1092    /// Configs for JSON-RPC Http.
1093    http_server_config: Option<ServerConfigBuilder>,
1094    /// Allowed CORS Domains for http
1095    http_cors_domains: Option<String>,
1096    /// Address where to bind the http server to
1097    http_addr: Option<SocketAddr>,
1098    /// Control whether http responses should be compressed
1099    http_disable_compression: bool,
1100    /// Allowed compression algorithms for HTTP responses.
1101    ///
1102    /// If `None`, all supported algorithms are enabled.
1103    http_compression_algorithms: Option<Vec<String>>,
1104    /// Allowed decompression algorithms for HTTP requests.
1105    ///
1106    /// If `None`, request decompression is disabled.
1107    http_decompression_algorithms: Option<Vec<String>>,
1108    /// Maximum allowed HTTP request body size in bytes (decompressed).
1109    http_max_request_body_size: Option<u32>,
1110    /// Configs for WS server
1111    ws_server_config: Option<ServerConfigBuilder>,
1112    /// Allowed CORS Domains for ws.
1113    ws_cors_domains: Option<String>,
1114    /// Address where to bind the ws server to
1115    ws_addr: Option<SocketAddr>,
1116    /// Configs for JSON-RPC IPC server
1117    ipc_server_config: Option<IpcServerBuilder<Identity>>,
1118    /// The Endpoint where to launch the ipc server
1119    ipc_endpoint: Option<String>,
1120    /// JWT secret for authentication
1121    jwt_secret: Option<JwtSecret>,
1122    /// Whether RPC request metrics are enabled.
1123    rpc_metrics_enabled: bool,
1124    /// Configurable RPC middleware
1125    rpc_middleware: RpcMiddleware,
1126}
1127
1128// === impl RpcServerConfig ===
1129
1130impl Default for RpcServerConfig<Identity> {
1131    /// Create a new config instance
1132    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    /// Creates a new config with only http set
1155    pub fn http(config: ServerConfigBuilder) -> Self {
1156        Self::default().with_http(config)
1157    }
1158
1159    /// Creates a new config with only ws set
1160    pub fn ws(config: ServerConfigBuilder) -> Self {
1161        Self::default().with_ws(config)
1162    }
1163
1164    /// Creates a new config with only ipc set
1165    pub fn ipc(config: IpcServerBuilder<Identity>) -> Self {
1166        Self::default().with_ipc(config)
1167    }
1168
1169    /// Configures the http server
1170    ///
1171    /// Note: this always configures an [`EthSubscriptionIdProvider`] [`IdProvider`] for
1172    /// convenience. To set a custom [`IdProvider`], please use [`Self::with_id_provider`].
1173    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    /// Configures the ws server
1180    ///
1181    /// Note: this always configures an [`EthSubscriptionIdProvider`] [`IdProvider`] for
1182    /// convenience. To set a custom [`IdProvider`], please use [`Self::with_id_provider`].
1183    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    /// Configures the ipc server
1189    ///
1190    /// Note: this always configures an [`EthSubscriptionIdProvider`] [`IdProvider`] for
1191    /// convenience. To set a custom [`IdProvider`], please use [`Self::with_id_provider`].
1192    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    /// Configure rpc middleware
1200    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    /// Configures whether the built-in RPC request metrics layer is enabled.
1221    pub const fn with_rpc_metrics_enabled(mut self, enabled: bool) -> Self {
1222        self.rpc_metrics_enabled = enabled;
1223        self
1224    }
1225
1226    /// Configure the cors domains for http _and_ ws
1227    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    /// Configure the cors domains for WS
1232    pub fn with_ws_cors(mut self, cors_domain: Option<String>) -> Self {
1233        self.ws_cors_domains = cors_domain;
1234        self
1235    }
1236
1237    /// Configure the cors domains for HTTP
1238    pub fn with_http_cors(mut self, cors_domain: Option<String>) -> Self {
1239        self.http_cors_domains = cors_domain;
1240        self
1241    }
1242
1243    /// Configure whether HTTP responses should be compressed
1244    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    /// Configure the allowed compression algorithms for HTTP responses.
1250    ///
1251    /// If `None`, all supported algorithms are enabled. See
1252    /// [`CompressionLayer::with_algorithms`] for how the algorithms are applied.
1253    pub fn with_http_compression_algorithms(mut self, algos: Option<Vec<String>>) -> Self {
1254        self.http_compression_algorithms = algos;
1255        self
1256    }
1257
1258    /// Configure decompression for HTTP requests.
1259    ///
1260    /// If `algos` is `None`, request decompression is disabled.
1261    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    /// Configures the [`SocketAddr`] of the http server
1268    ///
1269    /// Default is [`Ipv4Addr::LOCALHOST`] and
1270    /// [`reth_rpc_server_types::constants::DEFAULT_HTTP_RPC_PORT`]
1271    pub const fn with_http_address(mut self, addr: SocketAddr) -> Self {
1272        self.http_addr = Some(addr);
1273        self
1274    }
1275
1276    /// Configures the [`SocketAddr`] of the ws server
1277    ///
1278    /// Default is [`Ipv4Addr::LOCALHOST`] and
1279    /// [`reth_rpc_server_types::constants::DEFAULT_WS_RPC_PORT`]
1280    pub const fn with_ws_address(mut self, addr: SocketAddr) -> Self {
1281        self.ws_addr = Some(addr);
1282        self
1283    }
1284
1285    /// Sets a custom [`IdProvider`] for all configured transports.
1286    ///
1287    /// By default all transports use [`EthSubscriptionIdProvider`]
1288    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    /// Configures the endpoint of the ipc server
1306    ///
1307    /// Default is [`reth_rpc_server_types::constants::DEFAULT_IPC_ENDPOINT`]
1308    pub fn with_ipc_endpoint(mut self, path: impl Into<String>) -> Self {
1309        self.ipc_endpoint = Some(path.into());
1310        self
1311    }
1312
1313    /// Configures the JWT secret for authentication.
1314    pub const fn with_jwt_secret(mut self, secret: Option<JwtSecret>) -> Self {
1315        self.jwt_secret = secret;
1316        self
1317    }
1318
1319    /// Configures a custom tokio runtime for the rpc server.
1320    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    /// Returns true if any server is configured.
1337    ///
1338    /// If no server is configured, no server will be launched on [`RpcServerConfig::start`].
1339    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    /// Returns the [`SocketAddr`] of the http server
1346    pub const fn http_address(&self) -> Option<SocketAddr> {
1347        self.http_addr
1348    }
1349
1350    /// Returns the [`SocketAddr`] of the ws server
1351    pub const fn ws_address(&self) -> Option<SocketAddr> {
1352        self.ws_addr
1353    }
1354
1355    /// Returns the endpoint of the ipc server
1356    pub fn ipc_endpoint(&self) -> Option<String> {
1357        self.ipc_endpoint.clone()
1358    }
1359
1360    /// Returns whether the built-in RPC request metrics layer is enabled.
1361    pub const fn rpc_metrics_enabled(&self) -> bool {
1362        self.rpc_metrics_enabled
1363    }
1364
1365    /// Creates the [`CorsLayer`] if any
1366    fn maybe_cors_layer(cors: Option<String>) -> Result<Option<CorsLayer>, CorsDomainError> {
1367        cors.as_deref().map(cors::create_cors_layer).transpose()
1368    }
1369
1370    /// Creates the [`AuthLayer`] if any
1371    fn maybe_jwt_layer(jwt_secret: Option<JwtSecret>) -> Option<AuthLayer<JwtAuthValidator>> {
1372        jwt_secret.map(|secret| AuthLayer::new(JwtAuthValidator::new(secret)))
1373    }
1374
1375    /// Returns a [`CompressionLayer`] that adds compression support (gzip, deflate, brotli, zstd)
1376    /// based on the client's `Accept-Encoding` header.
1377    ///
1378    /// Servers listening on a loopback address only serve local clients, which gain nothing from
1379    /// compression, so they get no compression layer.
1380    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                // All supported algorithms are enabled when none are specified
1390                None => Some(CompressionLayer::new()),
1391                Some(algos) => Some(CompressionLayer::with_algorithms(algos)),
1392            }
1393        }
1394    }
1395
1396    /// Returns a [`DecompressionLayer`] that allows decompression of incoming requests
1397    /// based on the `Content-Encoding` request header.
1398    ///
1399    /// Decompression is disabled by default, and only enabled when algorithms are explicitly
1400    /// specified via the `algos` parameter.
1401    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    /// Builds and starts the configured server(s): http, ws, ipc.
1415    ///
1416    /// If both http and ws are on the same port, they are combined into one server.
1417    ///
1418    /// Returns the [`RpcServerHandle`] with the handle to the started servers.
1419    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 both are configured on the same port, we combine them into one server.
1455        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            // we merge this into one server using the http setup
1475            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                    // Both transports share one server, so only keep one shutdown handle.
1522                    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/// Holds modules to be installed per transport type
1626///
1627/// # Example
1628///
1629/// Configure a http transport only
1630///
1631/// ```
1632/// use reth_rpc_builder::{RethRpcModule, TransportRpcModuleConfig};
1633/// let config =
1634///     TransportRpcModuleConfig::default().with_http([RethRpcModule::Eth, RethRpcModule::Admin]);
1635/// ```
1636#[derive(Debug, Clone, Default, Eq, PartialEq)]
1637pub struct TransportRpcModuleConfig {
1638    /// http module configuration
1639    http: Option<RpcModuleSelection>,
1640    /// ws module configuration
1641    ws: Option<RpcModuleSelection>,
1642    /// ipc module configuration
1643    ipc: Option<RpcModuleSelection>,
1644    /// Config for the modules
1645    config: Option<RpcModuleConfig>,
1646}
1647
1648// === impl TransportRpcModuleConfig ===
1649
1650impl TransportRpcModuleConfig {
1651    /// Creates a new config with only http set
1652    pub fn set_http(http: impl Into<RpcModuleSelection>) -> Self {
1653        Self::default().with_http(http)
1654    }
1655
1656    /// Creates a new config with only ws set
1657    pub fn set_ws(ws: impl Into<RpcModuleSelection>) -> Self {
1658        Self::default().with_ws(ws)
1659    }
1660
1661    /// Creates a new config with only ipc set
1662    pub fn set_ipc(ipc: impl Into<RpcModuleSelection>) -> Self {
1663        Self::default().with_ipc(ipc)
1664    }
1665
1666    /// Sets the [`RpcModuleSelection`] for the http transport.
1667    pub fn with_http(mut self, http: impl Into<RpcModuleSelection>) -> Self {
1668        self.http = Some(http.into());
1669        self
1670    }
1671
1672    /// Sets the [`RpcModuleSelection`] for the ws transport.
1673    pub fn with_ws(mut self, ws: impl Into<RpcModuleSelection>) -> Self {
1674        self.ws = Some(ws.into());
1675        self
1676    }
1677
1678    /// Sets the [`RpcModuleSelection`] for the ipc transport.
1679    pub fn with_ipc(mut self, ipc: impl Into<RpcModuleSelection>) -> Self {
1680        self.ipc = Some(ipc.into());
1681        self
1682    }
1683
1684    /// Sets a custom [`RpcModuleConfig`] for the configured modules.
1685    pub fn with_config(mut self, config: RpcModuleConfig) -> Self {
1686        self.config = Some(config);
1687        self
1688    }
1689
1690    /// Get a mutable reference to the http module configuration.
1691    pub const fn http_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1692        &mut self.http
1693    }
1694
1695    /// Get a mutable reference to the ws module configuration.
1696    pub const fn ws_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1697        &mut self.ws
1698    }
1699
1700    /// Get a mutable reference to the ipc module configuration.
1701    pub const fn ipc_mut(&mut self) -> &mut Option<RpcModuleSelection> {
1702        &mut self.ipc
1703    }
1704
1705    /// Get a mutable reference to the rpc module configuration.
1706    pub const fn config_mut(&mut self) -> &mut Option<RpcModuleConfig> {
1707        &mut self.config
1708    }
1709
1710    /// Returns true if no transports are configured
1711    pub const fn is_empty(&self) -> bool {
1712        self.http.is_none() && self.ws.is_none() && self.ipc.is_none()
1713    }
1714
1715    /// Returns the [`RpcModuleSelection`] for the http transport
1716    pub const fn http(&self) -> Option<&RpcModuleSelection> {
1717        self.http.as_ref()
1718    }
1719
1720    /// Returns the [`RpcModuleSelection`] for the ws transport
1721    pub const fn ws(&self) -> Option<&RpcModuleSelection> {
1722        self.ws.as_ref()
1723    }
1724
1725    /// Returns the [`RpcModuleSelection`] for the ipc transport
1726    pub const fn ipc(&self) -> Option<&RpcModuleSelection> {
1727        self.ipc.as_ref()
1728    }
1729
1730    /// Returns the [`RpcModuleConfig`] for the configured modules
1731    pub const fn config(&self) -> Option<&RpcModuleConfig> {
1732        self.config.as_ref()
1733    }
1734
1735    /// Returns true if the given module is configured for any transport.
1736    pub fn contains_any(&self, module: &RethRpcModule) -> bool {
1737        self.contains_http(module) || self.contains_ws(module) || self.contains_ipc(module)
1738    }
1739
1740    /// Returns true if the given module is configured for the http transport.
1741    pub fn contains_http(&self, module: &RethRpcModule) -> bool {
1742        self.http.as_ref().is_some_and(|http| http.contains(module))
1743    }
1744
1745    /// Returns true if the given module is configured for the ws transport.
1746    pub fn contains_ws(&self, module: &RethRpcModule) -> bool {
1747        self.ws.as_ref().is_some_and(|ws| ws.contains(module))
1748    }
1749
1750    /// Returns true if the given module is configured for the ipc transport.
1751    pub fn contains_ipc(&self, module: &RethRpcModule) -> bool {
1752        self.ipc.as_ref().is_some_and(|ipc| ipc.contains(module))
1753    }
1754
1755    /// Ensures that both http and ws are configured and that they are configured to use the same
1756    /// port.
1757    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/// Holds installed modules per transport type.
1780#[derive(Debug, Clone, Default)]
1781pub struct TransportRpcModules<Context = ()> {
1782    /// The original config
1783    config: TransportRpcModuleConfig,
1784    /// rpcs module for http
1785    http: Option<RpcModule<Context>>,
1786    /// rpcs module for ws
1787    ws: Option<RpcModule<Context>>,
1788    /// rpcs module for ipc
1789    ipc: Option<RpcModule<Context>>,
1790}
1791
1792// === impl TransportRpcModules ===
1793
1794impl TransportRpcModules {
1795    /// Sets a custom [`TransportRpcModuleConfig`] for the configured modules.
1796    /// This will overwrite current configuration, if any.
1797    pub fn with_config(mut self, config: TransportRpcModuleConfig) -> Self {
1798        self.config = config;
1799        self
1800    }
1801
1802    /// Sets the [`RpcModule`] for the http transport.
1803    /// This will overwrite current module, if any.
1804    pub fn with_http(mut self, http: RpcModule<()>) -> Self {
1805        self.http = Some(http);
1806        self
1807    }
1808
1809    /// Sets the [`RpcModule`] for the ws transport.
1810    /// This will overwrite current module, if any.
1811    pub fn with_ws(mut self, ws: RpcModule<()>) -> Self {
1812        self.ws = Some(ws);
1813        self
1814    }
1815
1816    /// Sets the [`RpcModule`] for the ipc transport.
1817    /// This will overwrite current module, if any.
1818    pub fn with_ipc(mut self, ipc: RpcModule<()>) -> Self {
1819        self.ipc = Some(ipc);
1820        self
1821    }
1822
1823    /// Returns the [`TransportRpcModuleConfig`] used to configure this instance.
1824    pub const fn module_config(&self) -> &TransportRpcModuleConfig {
1825        &self.config
1826    }
1827
1828    /// Merge the given [`Methods`] in all configured transport modules if the given
1829    /// [`RethRpcModule`] is configured for the transport.
1830    ///
1831    /// Fails if any of the methods in other is present already.
1832    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    /// Merge the given [`Methods`] in all configured transport modules if the given
1852    /// [`RethRpcModule`] is configured for the transport, using a closure to lazily
1853    /// create the methods only when needed.
1854    ///
1855    /// The closure is only called if at least one transport has the module configured.
1856    /// Fails if any of the methods in the closure result is present already.
1857    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        // Early return if module not configured for any transport
1866        if !self.module_config().contains_any(&module) {
1867            return Ok(());
1868        }
1869        self.merge_if_module_configured(module, f())
1870    }
1871
1872    /// Merge the given [Methods] in the configured http methods.
1873    ///
1874    /// Fails if any of the methods in other is present already.
1875    ///
1876    /// Returns [Ok(false)] if no http transport is configured.
1877    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    /// Merge the given [Methods] in the configured ws methods.
1885    ///
1886    /// Fails if any of the methods in other is present already.
1887    ///
1888    /// Returns [Ok(false)] if no ws transport is configured.
1889    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    /// Merge the given [Methods] in the configured ipc methods.
1897    ///
1898    /// Fails if any of the methods in other is present already.
1899    ///
1900    /// Returns [Ok(false)] if no ipc transport is configured.
1901    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    /// Merge the given [`Methods`] in all configured methods.
1909    ///
1910    /// Fails if any of the methods in other is present already.
1911    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    /// Returns all unique endpoints installed for the given module.
1923    ///
1924    /// Note: In case of duplicate method names this only record the first occurrence.
1925    pub fn methods_by_module(&self, module: RethRpcModule) -> Methods {
1926        self.methods_by(|name| name.starts_with(module.as_str()))
1927    }
1928
1929    /// Returns all unique endpoints installed in any of the configured modules.
1930    ///
1931    /// Note: In case of duplicate method names this only record the first occurrence.
1932    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        // filter that matches the given filter and also removes duplicates we already have
1939        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    /// Returns all [`Methods`] installed for the http server based in the given closure.
1955    ///
1956    /// Returns `None` if no http support is configured.
1957    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    /// Returns all [`Methods`] installed for the ws server based in the given closure.
1965    ///
1966    /// Returns `None` if no ws support is configured.
1967    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    /// Returns all [`Methods`] installed for the ipc server based in the given closure.
1975    ///
1976    /// Returns `None` if no ipc support is configured.
1977    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    /// Removes the method with the given name from the configured http methods.
1985    ///
1986    /// Returns `true` if the method was found and removed, `false` otherwise.
1987    ///
1988    /// Be aware that a subscription consist of two methods, `subscribe` and `unsubscribe` and
1989    /// it's the caller responsibility to remove both `subscribe` and `unsubscribe` methods for
1990    /// subscriptions.
1991    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    /// Removes the given methods from the configured http methods.
1996    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    /// Removes the method with the given name from the configured ws methods.
2003    ///
2004    /// Returns `true` if the method was found and removed, `false` otherwise.
2005    ///
2006    /// Be aware that a subscription consist of two methods, `subscribe` and `unsubscribe` and
2007    /// it's the caller responsibility to remove both `subscribe` and `unsubscribe` methods for
2008    /// subscriptions.
2009    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    /// Removes the given methods from the configured ws methods.
2014    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    /// Removes the method with the given name from the configured ipc methods.
2021    ///
2022    /// Returns `true` if the method was found and removed, `false` otherwise.
2023    ///
2024    /// Be aware that a subscription consist of two methods, `subscribe` and `unsubscribe` and
2025    /// it's the caller responsibility to remove both `subscribe` and `unsubscribe` methods for
2026    /// subscriptions.
2027    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    /// Removes the given methods from the configured ipc methods.
2032    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    /// Removes the method with the given name from all configured transports.
2039    ///
2040    /// Returns `true` if the method was found and removed, `false` otherwise.
2041    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    /// Renames a method in all configured transports by:
2050    /// 1. Removing the old method name.
2051    /// 2. Adding the new method.
2052    pub fn rename(
2053        &mut self,
2054        old_name: &'static str,
2055        new_method: impl Into<Methods>,
2056    ) -> Result<(), RegisterMethodError> {
2057        // Remove the old method from all configured transports
2058        self.remove_method_from_configured(old_name);
2059
2060        // Merge the new method into the configured transports
2061        self.merge_configured(new_method)
2062    }
2063
2064    /// Replace the given [`Methods`] in the configured http methods.
2065    ///
2066    /// Fails if any of the methods in other is present already or if the method being removed is
2067    /// not present
2068    ///
2069    /// Returns [Ok(false)] if no http transport is configured.
2070    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    /// Replace the given [Methods] in the configured ipc methods.
2077    ///
2078    /// Fails if any of the methods in other is present already or if the method being removed is
2079    /// not present
2080    ///
2081    /// Returns [Ok(false)] if no ipc transport is configured.
2082    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    /// Replace the given [Methods] in the configured ws methods.
2089    ///
2090    /// Fails if any of the methods in other is present already or if the method being removed is
2091    /// not present
2092    ///
2093    /// Returns [Ok(false)] if no ws transport is configured.
2094    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    /// Replaces the method with the given name from all configured transports.
2101    ///
2102    /// Returns `true` if the method was found and replaced, `false` otherwise
2103    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    /// Adds or replaces given [`Methods`] in http module.
2115    ///
2116    /// Returns `true` if the methods were replaced or added, `false` otherwise.
2117    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    /// Adds or replaces given [`Methods`] in ws module.
2127    ///
2128    /// Returns `true` if the methods were replaced or added, `false` otherwise.
2129    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    /// Adds or replaces given [`Methods`] in ipc module.
2139    ///
2140    /// Returns `true` if the methods were replaced or added, `false` otherwise.
2141    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    /// Adds or replaces given [`Methods`] in all configured network modules.
2151    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    /// Adds or replaces the given [`Methods`] in the transport modules where the specified
2162    /// [`RethRpcModule`] is configured.
2163    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
2182/// Returns the methods installed in the given module that match the given filter.
2183fn 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/// A handle to the spawned servers.
2200///
2201/// When this type is dropped or [`RpcServerHandle::stop`] has been called the server will be
2202/// stopped.
2203#[derive(Clone, Debug)]
2204#[must_use = "Server stops if dropped"]
2205pub struct RpcServerHandle {
2206    /// The address of the http/ws server
2207    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
2216// === impl RpcServerHandle ===
2217
2218impl RpcServerHandle {
2219    /// Configures the JWT secret for authentication.
2220    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    /// Returns the [`SocketAddr`] of the http server if started.
2236    pub const fn http_local_addr(&self) -> Option<SocketAddr> {
2237        self.http_local_addr
2238    }
2239
2240    /// Returns the [`SocketAddr`] of the ws server if started.
2241    pub const fn ws_local_addr(&self) -> Option<SocketAddr> {
2242        self.ws_local_addr
2243    }
2244
2245    /// Tell the server to stop without waiting for the server to stop.
2246    pub fn stop(self) -> Result<(), AlreadyStoppedError> {
2247        // HTTP and WS share one server, and one stop handle, when they use the same address.
2248        // Stopping it twice would race with the server shutting down after the first stop.
2249        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    /// Returns the endpoint of the launched IPC server, if any
2268    pub fn ipc_endpoint(&self) -> Option<String> {
2269        self.ipc_endpoint.clone()
2270    }
2271
2272    /// Returns the url to the http server
2273    pub fn http_url(&self) -> Option<String> {
2274        self.http_local_addr.map(|addr| format!("http://{addr}"))
2275    }
2276
2277    /// Returns the url to the ws server
2278    pub fn ws_url(&self) -> Option<String> {
2279        self.ws_local_addr.map(|addr| format!("ws://{addr}"))
2280    }
2281
2282    /// Returns a http client connected to the server.
2283    ///
2284    /// The client authenticates every request with a fresh JWT if the server has a secret.
2285    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    /// Returns a ws client connected to the server.
2295    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    /// Returns a new [`alloy_network::Ethereum`] http provider with its recommended fillers.
2306    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    /// Returns a new [`alloy_network::Ethereum`] http provider with its recommended fillers and
2313    /// installed wallet.
2314    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    /// Returns an http provider from the rpc server handle for the
2328    /// specified [`alloy_network::Network`].
2329    ///
2330    /// This installs the recommended fillers: [`RecommendedFillers`]
2331    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    /// Returns a new [`alloy_network::Ethereum`] websocket provider with its recommended fillers.
2343    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    /// Returns a new [`alloy_network::Ethereum`] ws provider with its recommended fillers and
2350    /// installed wallet.
2351    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    /// Returns an ws provider from the rpc server handle for the
2368    /// specified [`alloy_network::Network`].
2369    ///
2370    /// This installs the recommended fillers: [`RecommendedFillers`]
2371    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    /// Returns a new [`alloy_network::Ethereum`] ipc provider with its recommended fillers.
2385    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    /// Returns an ipc provider from the rpc server handle for the
2392    /// specified [`alloy_network::Network`].
2393    ///
2394    /// This installs the recommended fillers: [`RecommendedFillers`]
2395    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        // Remove a method that exists
2561        assert!(modules.remove_http_method("anything"));
2562
2563        // Remove a method that does not exist
2564        assert!(!modules.remove_http_method("non_existent_method"));
2565
2566        // Verify that the method was removed
2567        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        // Remove a method that exists
2576        assert!(modules.remove_ws_method("anything"));
2577
2578        // Remove a method that does not exist
2579        assert!(!modules.remove_ws_method("non_existent_method"));
2580
2581        // Verify that the method was removed
2582        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        // Remove a method that exists
2591        assert!(modules.remove_ipc_method("anything"));
2592
2593        // Remove a method that does not exist
2594        assert!(!modules.remove_ipc_method("non_existent_method"));
2595
2596        // Verify that the method was removed
2597        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        // Remove a method that exists
2610        assert!(modules.remove_method_from_configured("anything"));
2611
2612        // Remove a method that was just removed (it does not exist anymore)
2613        assert!(!modules.remove_method_from_configured("anything"));
2614
2615        // Remove a method that does not exist
2616        assert!(!modules.remove_method_from_configured("non_existent_method"));
2617
2618        // Verify that the method was removed from all transports
2619        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        // Verify that the old we want to rename exists at the start
2634        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        // Verify that the new method does not exist at the start
2639        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        // Create another module
2644        let mut other_module = RpcModule::new(());
2645        other_module.register_method("something", |_, _| "fails").unwrap();
2646
2647        // Rename the method
2648        modules.rename("anything", other_module).expect("rename failed");
2649
2650        // Verify that the old method was removed from all transports
2651        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        // Verify that the new method was added to all transports
2656        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        // Verify that the other_method was added
2727        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        // Create a config that enables RethRpcModule::Eth for HTTP and WS, but NOT IPC
2739        let config = TransportRpcModuleConfig::default()
2740            .with_http([RethRpcModule::Eth])
2741            .with_ws([RethRpcModule::Eth]);
2742
2743        // Create HTTP module with an existing method (to test "replace")
2744        let mut http_module = RpcModule::new(());
2745        http_module.register_method("eth_existing", |_, _| "original").unwrap();
2746
2747        // Create WS module with the same existing method
2748        let mut ws_module = RpcModule::new(());
2749        ws_module.register_method("eth_existing", |_, _| "original").unwrap();
2750
2751        // Create IPC module (empty, to ensure no changes)
2752        let ipc_module = RpcModule::new(());
2753
2754        // Set up TransportRpcModules with the config and modules
2755        let mut modules = TransportRpcModules {
2756            config,
2757            http: Some(http_module),
2758            ws: Some(ws_module),
2759            ipc: Some(ipc_module),
2760        };
2761
2762        // Create new methods: one to replace an existing method, one to add a new one
2763        let mut new_module = RpcModule::new(());
2764        new_module.register_method("eth_existing", |_, _| "replaced").unwrap(); // Replace
2765        new_module.register_method("eth_new", |_, _| "added").unwrap(); // Add
2766        let new_methods: Methods = new_module.into();
2767
2768        // Call the function for RethRpcModule::Eth
2769        let result = modules.add_or_replace_if_module_configured(RethRpcModule::Eth, new_methods);
2770        assert!(result.is_ok(), "Function should succeed");
2771
2772        // Verify HTTP: existing method still exists (replaced), new method added
2773        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        // Verify WS: existing method still exists (replaced), new method added
2778        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        // Verify IPC: no changes (Eth not configured for IPC)
2783        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        // Create a config that enables RethRpcModule::Eth for HTTP only
2791        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        // Track whether closure was called
2797        let mut closure_called = false;
2798
2799        // Test with configured module - closure should be called
2800        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        // Reset and test with unconfigured module - closure should NOT be called
2812        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}