Skip to main content

reth_rpc_builder/
config.rs

1use jsonrpsee::server::ServerConfigBuilder;
2use reth_node_core::{args::RpcServerArgs, utils::get_or_create_jwt_secret_from_path};
3use reth_rpc::ValidationApiConfig;
4use reth_rpc_eth_types::{EthConfig, EthStateCacheConfig, GasPriceOracleConfig};
5use reth_rpc_layer::{JwtError, JwtSecret};
6use reth_rpc_server_types::RpcModuleSelection;
7use std::{net::SocketAddr, path::PathBuf};
8use tower::layer::util::Identity;
9use tracing::{debug, warn};
10
11use crate::{
12    auth::AuthServerConfig, error::RpcError, IpcServerBuilder, RpcModuleConfig, RpcServerConfig,
13    TransportRpcModuleConfig,
14};
15
16/// A trait that provides a configured RPC server.
17///
18/// This provides all basic config values for the RPC server and is implemented by the
19/// [`RpcServerArgs`] type.
20pub trait RethRpcServerConfig {
21    /// Returns whether ipc is enabled.
22    fn is_ipc_enabled(&self) -> bool;
23
24    /// Returns the path to the target ipc socket if enabled.
25    fn ipc_path(&self) -> &str;
26
27    /// The configured ethereum RPC settings.
28    fn eth_config(&self) -> EthConfig;
29
30    /// The configured ethereum RPC settings.
31    fn flashbots_config(&self) -> ValidationApiConfig;
32
33    /// Returns state cache configuration.
34    fn state_cache_config(&self) -> EthStateCacheConfig;
35
36    /// Returns the max request size in bytes.
37    fn rpc_max_request_size_bytes(&self) -> u32;
38
39    /// Returns the max response size in bytes.
40    fn rpc_max_response_size_bytes(&self) -> u32;
41
42    /// Extracts the gas price oracle config from the args.
43    fn gas_price_oracle_config(&self) -> GasPriceOracleConfig;
44
45    /// Creates the [`TransportRpcModuleConfig`] from cli args.
46    ///
47    /// This sets all the api modules, and configures additional settings like gas price oracle
48    /// settings in the [`TransportRpcModuleConfig`].
49    fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig;
50
51    /// Returns the default server config for http/ws
52    fn http_ws_server_builder(&self) -> ServerConfigBuilder;
53
54    /// Returns the default ipc server builder
55    fn ipc_server_builder(&self) -> IpcServerBuilder<Identity>;
56
57    /// Creates the [`RpcServerConfig`] from cli args.
58    fn rpc_server_config(&self) -> RpcServerConfig;
59
60    /// Returns whether built-in RPC request metrics are enabled.
61    fn rpc_metrics_enabled(&self) -> bool;
62
63    /// Creates the [`AuthServerConfig`] from cli args.
64    fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError>;
65
66    /// The execution layer and consensus layer clients SHOULD accept a configuration parameter:
67    /// jwt-secret, which designates a file containing the hex-encoded 256 bit secret key to be used
68    /// for verifying/generating JWT tokens.
69    ///
70    /// If such a parameter is given, but the file cannot be read, or does not contain a hex-encoded
71    /// key of 256 bits, the client SHOULD treat this as an error.
72    ///
73    /// If such a parameter is not given, the client SHOULD generate such a token, valid for the
74    /// duration of the execution, and SHOULD store the hex-encoded secret as a jwt.hex file on
75    /// the filesystem. This file can then be used to provision the counterpart client.
76    ///
77    /// The `default_jwt_path` provided as an argument will be used as the default location for the
78    /// jwt secret in case neither `--authrpc.jwtsecret` nor `--authrpc.jwtsecret-hex` is provided.
79    fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError>;
80
81    /// Returns the configured jwt secret key for the regular rpc servers, if any.
82    ///
83    /// Note: this is not used for the auth server (engine API).
84    fn rpc_secret_key(&self) -> Option<JwtSecret>;
85}
86
87impl RethRpcServerConfig for RpcServerArgs {
88    fn is_ipc_enabled(&self) -> bool {
89        // By default IPC is enabled therefore it is enabled if the `ipcdisable` is false.
90        !self.ipcdisable
91    }
92
93    fn ipc_path(&self) -> &str {
94        self.ipcpath.as_str()
95    }
96
97    fn eth_config(&self) -> EthConfig {
98        EthConfig::default()
99            .max_tracing_requests(self.rpc_max_tracing_requests)
100            .max_blocking_io_requests(self.rpc_max_blocking_io_requests)
101            .max_trace_filter_blocks(self.rpc_max_trace_filter_blocks)
102            .max_blocks_per_filter(self.rpc_max_blocks_per_filter.unwrap_or_max())
103            .max_logs_per_response(self.rpc_max_logs_per_response.unwrap_or_max() as usize)
104            .max_active_filters(
105                self.rpc_max_active_filters.0.map(|max| usize::try_from(max).unwrap_or(usize::MAX)),
106            )
107            .eth_proof_window(self.rpc_eth_proof_window)
108            .rpc_gas_cap(self.rpc_gas_cap)
109            .rpc_max_simulate_blocks(self.rpc_max_simulate_blocks)
110            .rpc_max_trace_bytes(self.max_trace_bytes())
111            .compute_state_root_for_eth_simulate(self.rpc_compute_state_root_for_eth_simulate)
112            .state_cache(self.state_cache_config())
113            .gpo_config(self.gas_price_oracle_config())
114            .proof_permits(self.rpc_proof_permits)
115            .pending_block_kind(self.rpc_pending_block)
116            .raw_tx_forwarder(self.rpc_forwarder.clone())
117            .rpc_evm_memory_limit(self.rpc_evm_memory_limit)
118            .force_blob_sidecar_upcasting(self.rpc_force_blob_sidecar_upcasting)
119            .max_response_size(self.rpc_max_response_size_bytes() as usize)
120    }
121
122    fn flashbots_config(&self) -> ValidationApiConfig {
123        ValidationApiConfig {
124            disallow: self.builder_disallow.clone().unwrap_or_default(),
125            // the proof window defaults to 0, which would reject any submission whose parent is
126            // behind the tip, so it can only widen the default window
127            validation_window: self
128                .rpc_eth_proof_window
129                .max(ValidationApiConfig::DEFAULT_VALIDATION_WINDOW),
130        }
131    }
132
133    fn state_cache_config(&self) -> EthStateCacheConfig {
134        EthStateCacheConfig {
135            max_blocks: self.rpc_state_cache.max_blocks,
136            max_receipts: self.rpc_state_cache.max_receipts,
137            max_bals: self.rpc_state_cache.max_bals,
138            max_blocks_bytes: self.rpc_state_cache.max_blocks_bytes,
139            max_receipts_bytes: self.rpc_state_cache.max_receipts_bytes,
140            max_bals_bytes: self.rpc_state_cache.max_bals_bytes,
141            idle_timeout: self.rpc_state_cache.idle_timeout,
142            cache_computed_bals: self.rpc_state_cache.cache_computed_bals,
143            prewarm_bals: self.rpc_state_cache.prewarm_bals,
144            max_concurrent_db_requests: self.rpc_state_cache.max_concurrent_db_requests,
145            max_cached_tx_hashes: self.rpc_state_cache.max_cached_tx_hashes,
146        }
147    }
148
149    fn rpc_max_request_size_bytes(&self) -> u32 {
150        self.rpc_max_request_size.get().saturating_mul(1024 * 1024)
151    }
152
153    fn rpc_max_response_size_bytes(&self) -> u32 {
154        self.rpc_max_response_size.get().saturating_mul(1024 * 1024)
155    }
156
157    fn gas_price_oracle_config(&self) -> GasPriceOracleConfig {
158        self.gas_price_oracle.gas_price_oracle_config()
159    }
160
161    fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig {
162        let mut config = TransportRpcModuleConfig::default()
163            .with_config(RpcModuleConfig::new(self.eth_config()));
164
165        if self.http {
166            config = config.with_http(
167                self.http_api
168                    .clone()
169                    .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
170            );
171        }
172
173        if self.ws {
174            config = config.with_ws(
175                self.ws_api
176                    .clone()
177                    .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
178            );
179        }
180
181        if self.is_ipc_enabled() {
182            config = config.with_ipc(RpcModuleSelection::default_ipc_modules());
183        }
184
185        config
186    }
187
188    fn http_ws_server_builder(&self) -> ServerConfigBuilder {
189        ServerConfigBuilder::new()
190            .max_connections(self.rpc_max_connections.get())
191            .max_request_body_size(self.rpc_max_request_size_bytes())
192            .max_response_body_size(self.rpc_max_response_size_bytes())
193            .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
194    }
195
196    fn ipc_server_builder(&self) -> IpcServerBuilder<Identity> {
197        IpcServerBuilder::default()
198            .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
199            .max_request_body_size(self.rpc_max_request_size_bytes())
200            .max_response_body_size(self.rpc_max_response_size_bytes())
201            .max_connections(self.rpc_max_connections.get())
202            .set_ipc_socket_permissions(self.ipc_socket_permissions.clone())
203    }
204
205    fn rpc_server_config(&self) -> RpcServerConfig {
206        let mut config = RpcServerConfig::default()
207            .with_jwt_secret(self.rpc_secret_key())
208            .with_rpc_metrics_enabled(self.rpc_metrics_enabled());
209
210        if self.http_api.is_some() && !self.http {
211            warn!(
212                target: "reth::cli",
213                "The --http.api flag is set but --http is not enabled. HTTP RPC API will not be exposed."
214            );
215        }
216
217        if self.ws_api.is_some() && !self.ws {
218            warn!(
219                target: "reth::cli",
220                "The --ws.api flag is set but --ws is not enabled. WS RPC API will not be exposed."
221            );
222        }
223
224        if self.http {
225            let socket_address = SocketAddr::new(self.http_addr, self.http_port);
226            config = config
227                .with_http_address(socket_address)
228                .with_http(self.http_ws_server_builder())
229                .with_http_cors(self.http_corsdomain.clone())
230                .with_http_disable_compression(self.http_disable_compression)
231                .with_http_compression_algorithms(self.http_compression_algorithms.clone())
232                .with_http_decompression(
233                    self.http_decompression_algorithms.clone(),
234                    self.rpc_max_request_size_bytes(),
235                );
236        }
237
238        if self.ws {
239            let socket_address = SocketAddr::new(self.ws_addr, self.ws_port);
240            // Ensure WS CORS is applied regardless of HTTP being enabled
241            config = config
242                .with_ws_address(socket_address)
243                .with_ws(self.http_ws_server_builder())
244                .with_ws_cors(self.ws_allowed_origins.clone());
245        }
246
247        if self.is_ipc_enabled() {
248            config =
249                config.with_ipc(self.ipc_server_builder()).with_ipc_endpoint(self.ipcpath.clone());
250        }
251
252        config
253    }
254
255    fn rpc_metrics_enabled(&self) -> bool {
256        !self.rpc_disable_metrics
257    }
258
259    fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError> {
260        let address = SocketAddr::new(self.auth_addr, self.auth_port);
261
262        let mut builder = AuthServerConfig::builder(jwt_secret).socket_addr(address);
263        if self.auth_ipc {
264            builder = builder
265                .ipc_endpoint(self.auth_ipc_path().to_string())
266                .with_ipc_config(self.ipc_server_builder());
267        }
268        Ok(builder.build())
269    }
270
271    fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError> {
272        if let Some(secret) = self.auth_jwtsecret_hex {
273            debug!(target: "reth::cli", "Using JWT auth secret from hex");
274            Ok(secret)
275        } else {
276            match self.auth_jwtsecret.as_ref() {
277                Some(fpath) => {
278                    debug!(target: "reth::cli", user_path=?fpath, "Reading JWT auth secret file");
279                    JwtSecret::from_file(fpath)
280                }
281                None => get_or_create_jwt_secret_from_path(&default_jwt_path),
282            }
283        }
284    }
285
286    fn rpc_secret_key(&self) -> Option<JwtSecret> {
287        self.rpc_jwtsecret
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use clap::{Args, Parser};
294    use reth_node_core::args::RpcServerArgs;
295    use reth_rpc::ValidationApiConfig;
296    use reth_rpc_eth_types::{EthStateCacheConfig, RPC_DEFAULT_GAS_CAP};
297    use reth_rpc_layer::JwtSecret;
298    use reth_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
299    use std::{
300        net::{Ipv4Addr, SocketAddr, SocketAddrV4},
301        time::Duration,
302    };
303
304    use crate::config::RethRpcServerConfig;
305
306    /// A helper type to parse Args more easily
307    #[derive(Parser)]
308    struct CommandParser<T: Args> {
309        #[command(flatten)]
310        args: T,
311    }
312
313    #[test]
314    fn rpc_cache_limits_reach_eth_config() {
315        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
316        assert_eq!(args.eth_config().cache, EthStateCacheConfig::default());
317
318        for (timeout, expected_timeout) in
319            [("0s", Duration::ZERO), ("2500ms", Duration::from_millis(2500))]
320        {
321            let args = CommandParser::<RpcServerArgs>::parse_from([
322                "reth",
323                "--rpc-cache.max-blocks",
324                "10",
325                "--rpc-cache.max-receipts",
326                "20",
327                "--rpc-cache.max-bals",
328                "30",
329                "--rpc-cache.max-blocks-bytes",
330                "1024",
331                "--rpc-cache.max-receipts-bytes",
332                "0",
333                "--rpc-cache.max-bals-bytes",
334                "4096",
335                "--rpc-cache.idle-timeout",
336                timeout,
337            ])
338            .args;
339            assert_eq!(
340                args.eth_config().cache,
341                EthStateCacheConfig {
342                    max_blocks: 10,
343                    max_receipts: 20,
344                    max_bals: 30,
345                    max_blocks_bytes: 1024,
346                    max_receipts_bytes: 0,
347                    max_bals_bytes: 4096,
348                    idle_timeout: expected_timeout,
349                    ..Default::default()
350                }
351            );
352        }
353    }
354
355    #[test]
356    fn flashbots_validation_window() {
357        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
358        assert_eq!(
359            args.flashbots_config().validation_window,
360            ValidationApiConfig::DEFAULT_VALIDATION_WINDOW
361        );
362
363        let args =
364            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.eth-proof-window", "1"])
365                .args;
366        assert_eq!(
367            args.flashbots_config().validation_window,
368            ValidationApiConfig::DEFAULT_VALIDATION_WINDOW
369        );
370
371        let args =
372            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.eth-proof-window", "100"])
373                .args;
374        assert_eq!(args.flashbots_config().validation_window, 100);
375    }
376
377    #[test]
378    fn test_rpc_gas_cap() {
379        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
380        let config = args.eth_config();
381        assert_eq!(config.rpc_gas_cap, u64::from(RPC_DEFAULT_GAS_CAP));
382
383        let args =
384            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.gascap", "1000"]).args;
385        let config = args.eth_config();
386        assert_eq!(config.rpc_gas_cap, 1000);
387
388        let args = CommandParser::<RpcServerArgs>::try_parse_from(["reth", "--rpc.gascap", "0"]);
389        assert!(args.is_err());
390    }
391
392    #[test]
393    fn test_transport_rpc_module_config() {
394        let args = CommandParser::<RpcServerArgs>::parse_from([
395            "reth",
396            "--http.api",
397            "eth,admin,debug",
398            "--http",
399            "--ws",
400        ])
401        .args;
402        let config = args.transport_rpc_module_config();
403        let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
404        assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
405        assert_eq!(
406            config.ws().cloned().unwrap().into_selection(),
407            RpcModuleSelection::standard_modules()
408        );
409    }
410
411    #[test]
412    fn test_testing_namespace_requires_explicit_selection() {
413        let args = CommandParser::<RpcServerArgs>::parse_from([
414            "reth",
415            "--http",
416            "--http.api",
417            "all",
418            "--ws",
419            "--ws.api",
420            "all",
421        ])
422        .args;
423        let config = args.transport_rpc_module_config();
424        assert!(!config.contains_http(&RethRpcModule::Testing));
425        assert!(!config.contains_ws(&RethRpcModule::Testing));
426        assert!(!config.contains_ipc(&RethRpcModule::Testing));
427
428        let args = CommandParser::<RpcServerArgs>::parse_from([
429            "reth",
430            "--http",
431            "--http.api",
432            "eth,testing",
433            "--ws",
434            "--ws.api",
435            "eth,testing",
436        ])
437        .args;
438        let config = args.transport_rpc_module_config();
439        assert!(config.contains_http(&RethRpcModule::Testing));
440        assert!(config.contains_ws(&RethRpcModule::Testing));
441    }
442
443    #[test]
444    fn test_transport_rpc_module_trim_config() {
445        let args = CommandParser::<RpcServerArgs>::parse_from([
446            "reth",
447            "--http.api",
448            " eth, admin, debug",
449            "--http",
450            "--ws",
451        ])
452        .args;
453        let config = args.transport_rpc_module_config();
454        let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
455        assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
456        assert_eq!(
457            config.ws().cloned().unwrap().into_selection(),
458            RpcModuleSelection::standard_modules()
459        );
460    }
461
462    #[test]
463    fn test_unique_rpc_modules() {
464        let args = CommandParser::<RpcServerArgs>::parse_from([
465            "reth",
466            "--http.api",
467            " eth, admin, debug, eth,admin",
468            "--http",
469            "--ws",
470        ])
471        .args;
472        let config = args.transport_rpc_module_config();
473        let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
474        assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
475        assert_eq!(
476            config.ws().cloned().unwrap().into_selection(),
477            RpcModuleSelection::standard_modules()
478        );
479    }
480
481    #[test]
482    fn test_rpc_server_config() {
483        let args = CommandParser::<RpcServerArgs>::parse_from([
484            "reth",
485            "--http.api",
486            "eth,admin,debug",
487            "--http",
488            "--ws",
489            "--ws.addr",
490            "127.0.0.1",
491            "--ws.port",
492            "8888",
493        ])
494        .args;
495        let config = args.rpc_server_config();
496        assert_eq!(
497            config.http_address().unwrap(),
498            SocketAddr::V4(SocketAddrV4::new(
499                Ipv4Addr::LOCALHOST,
500                constants::DEFAULT_HTTP_RPC_PORT
501            ))
502        );
503        assert_eq!(
504            config.ws_address().unwrap(),
505            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8888))
506        );
507        assert_eq!(config.ipc_endpoint().unwrap(), constants::DEFAULT_IPC_ENDPOINT);
508        assert!(config.rpc_metrics_enabled());
509    }
510
511    #[test]
512    fn test_rpc_server_config_disable_metrics() {
513        let args =
514            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.disable-metrics"]).args;
515        let config = args.rpc_server_config();
516        assert!(!config.rpc_metrics_enabled());
517    }
518
519    #[test]
520    fn test_zero_filter_limits() {
521        let args = CommandParser::<RpcServerArgs>::parse_from([
522            "reth",
523            "--rpc-max-blocks-per-filter",
524            "0",
525            "--rpc-max-logs-per-response",
526            "0",
527            "--rpc-max-active-filters",
528            "0",
529        ])
530        .args;
531
532        let config = args.eth_config().filter_config();
533        assert_eq!(config.max_blocks_per_filter, Some(u64::MAX));
534        assert_eq!(config.max_logs_per_response, Some(usize::MAX));
535        assert_eq!(config.max_active_filters, None);
536    }
537
538    #[test]
539    fn test_custom_filter_limits() {
540        let args = CommandParser::<RpcServerArgs>::parse_from([
541            "reth",
542            "--rpc-max-blocks-per-filter",
543            "100",
544            "--rpc-max-logs-per-response",
545            "200",
546            "--rpc-max-active-filters",
547            "300",
548            "--rpc.max-response-size",
549            "5",
550        ])
551        .args;
552
553        let config = args.eth_config().filter_config();
554        assert_eq!(config.max_blocks_per_filter, Some(100));
555        assert_eq!(config.max_logs_per_response, Some(200));
556        assert_eq!(config.max_active_filters, Some(300));
557        assert_eq!(config.max_response_size, Some(5 * 1024 * 1024));
558    }
559
560    #[test]
561    fn test_auth_jwt_secret_from_hex() {
562        let hex = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
563        let args =
564            CommandParser::<RpcServerArgs>::parse_from(["reth", "--authrpc.jwtsecret-hex", hex])
565                .args;
566
567        let secret = args.auth_jwt_secret(std::env::temp_dir().join("unused.jwt")).unwrap();
568        assert_eq!(secret, JwtSecret::from_hex(hex).unwrap());
569    }
570}