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
16pub trait RethRpcServerConfig {
21 fn is_ipc_enabled(&self) -> bool;
23
24 fn ipc_path(&self) -> &str;
26
27 fn eth_config(&self) -> EthConfig;
29
30 fn flashbots_config(&self) -> ValidationApiConfig;
32
33 fn state_cache_config(&self) -> EthStateCacheConfig;
35
36 fn rpc_max_request_size_bytes(&self) -> u32;
38
39 fn rpc_max_response_size_bytes(&self) -> u32;
41
42 fn gas_price_oracle_config(&self) -> GasPriceOracleConfig;
44
45 fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig;
50
51 fn http_ws_server_builder(&self) -> ServerConfigBuilder;
53
54 fn ipc_server_builder(&self) -> IpcServerBuilder<Identity, Identity>;
56
57 fn rpc_server_config(&self) -> RpcServerConfig;
59
60 fn rpc_metrics_enabled(&self) -> bool;
62
63 fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError>;
65
66 fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError>;
80
81 fn rpc_secret_key(&self) -> Option<JwtSecret>;
85}
86
87impl RethRpcServerConfig for RpcServerArgs {
88 fn is_ipc_enabled(&self) -> bool {
89 !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 .eth_proof_window(self.rpc_eth_proof_window)
105 .rpc_gas_cap(self.rpc_gas_cap)
106 .rpc_max_simulate_blocks(self.rpc_max_simulate_blocks)
107 .compute_state_root_for_eth_simulate(self.rpc_compute_state_root_for_eth_simulate)
108 .state_cache(self.state_cache_config())
109 .gpo_config(self.gas_price_oracle_config())
110 .proof_permits(self.rpc_proof_permits)
111 .pending_block_kind(self.rpc_pending_block)
112 .raw_tx_forwarder(self.rpc_forwarder.clone())
113 .rpc_evm_memory_limit(self.rpc_evm_memory_limit)
114 .force_blob_sidecar_upcasting(self.rpc_force_blob_sidecar_upcasting)
115 }
116
117 fn flashbots_config(&self) -> ValidationApiConfig {
118 ValidationApiConfig {
119 disallow: self.builder_disallow.clone().unwrap_or_default(),
120 validation_window: self.rpc_eth_proof_window,
121 }
122 }
123
124 fn state_cache_config(&self) -> EthStateCacheConfig {
125 EthStateCacheConfig {
126 max_blocks: self.rpc_state_cache.max_blocks,
127 max_receipts: self.rpc_state_cache.max_receipts,
128 max_headers: self.rpc_state_cache.max_headers,
129 max_bals: self.rpc_state_cache.max_bals,
130 max_concurrent_db_requests: self.rpc_state_cache.max_concurrent_db_requests,
131 max_cached_tx_hashes: self.rpc_state_cache.max_cached_tx_hashes,
132 }
133 }
134
135 fn rpc_max_request_size_bytes(&self) -> u32 {
136 self.rpc_max_request_size.get().saturating_mul(1024 * 1024)
137 }
138
139 fn rpc_max_response_size_bytes(&self) -> u32 {
140 self.rpc_max_response_size.get().saturating_mul(1024 * 1024)
141 }
142
143 fn gas_price_oracle_config(&self) -> GasPriceOracleConfig {
144 self.gas_price_oracle.gas_price_oracle_config()
145 }
146
147 fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig {
148 let mut config = TransportRpcModuleConfig::default()
149 .with_config(RpcModuleConfig::new(self.eth_config()));
150
151 if self.http {
152 config = config.with_http(
153 self.http_api
154 .clone()
155 .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
156 );
157 }
158
159 if self.ws {
160 config = config.with_ws(
161 self.ws_api
162 .clone()
163 .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
164 );
165 }
166
167 if self.is_ipc_enabled() {
168 config = config.with_ipc(RpcModuleSelection::default_ipc_modules());
169 }
170
171 config
172 }
173
174 fn http_ws_server_builder(&self) -> ServerConfigBuilder {
175 ServerConfigBuilder::new()
176 .max_connections(self.rpc_max_connections.get())
177 .max_request_body_size(self.rpc_max_request_size_bytes())
178 .max_response_body_size(self.rpc_max_response_size_bytes())
179 .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
180 }
181
182 fn ipc_server_builder(&self) -> IpcServerBuilder<Identity, Identity> {
183 IpcServerBuilder::default()
184 .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
185 .max_request_body_size(self.rpc_max_request_size_bytes())
186 .max_response_body_size(self.rpc_max_response_size_bytes())
187 .max_connections(self.rpc_max_connections.get())
188 .set_ipc_socket_permissions(self.ipc_socket_permissions.clone())
189 }
190
191 fn rpc_server_config(&self) -> RpcServerConfig {
192 let mut config = RpcServerConfig::default()
193 .with_jwt_secret(self.rpc_secret_key())
194 .with_rpc_metrics_enabled(self.rpc_metrics_enabled());
195
196 if self.http_api.is_some() && !self.http {
197 warn!(
198 target: "reth::cli",
199 "The --http.api flag is set but --http is not enabled. HTTP RPC API will not be exposed."
200 );
201 }
202
203 if self.ws_api.is_some() && !self.ws {
204 warn!(
205 target: "reth::cli",
206 "The --ws.api flag is set but --ws is not enabled. WS RPC API will not be exposed."
207 );
208 }
209
210 if self.http {
211 let socket_address = SocketAddr::new(self.http_addr, self.http_port);
212 config = config
213 .with_http_address(socket_address)
214 .with_http(self.http_ws_server_builder())
215 .with_http_cors(self.http_corsdomain.clone())
216 .with_http_disable_compression(self.http_disable_compression)
217 .with_http_compression_algorithms(self.http_compression_algorithms.clone())
218 .with_http_decompression(
219 self.http_decompression_algorithms.clone(),
220 self.rpc_max_request_size_bytes(),
221 );
222 }
223
224 if self.ws {
225 let socket_address = SocketAddr::new(self.ws_addr, self.ws_port);
226 config = config
228 .with_ws_address(socket_address)
229 .with_ws(self.http_ws_server_builder())
230 .with_ws_cors(self.ws_allowed_origins.clone());
231 }
232
233 if self.is_ipc_enabled() {
234 config =
235 config.with_ipc(self.ipc_server_builder()).with_ipc_endpoint(self.ipcpath.clone());
236 }
237
238 config
239 }
240
241 fn rpc_metrics_enabled(&self) -> bool {
242 !self.rpc_disable_metrics
243 }
244
245 fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError> {
246 let address = SocketAddr::new(self.auth_addr, self.auth_port);
247
248 let mut builder = AuthServerConfig::builder(jwt_secret).socket_addr(address);
249 if self.auth_ipc {
250 builder = builder
251 .ipc_endpoint(self.auth_ipc_path.clone())
252 .with_ipc_config(self.ipc_server_builder());
253 }
254 Ok(builder.build())
255 }
256
257 fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError> {
258 match self.auth_jwtsecret.as_ref() {
259 Some(fpath) => {
260 debug!(target: "reth::cli", user_path=?fpath, "Reading JWT auth secret file");
261 JwtSecret::from_file(fpath)
262 }
263 None => get_or_create_jwt_secret_from_path(&default_jwt_path),
264 }
265 }
266
267 fn rpc_secret_key(&self) -> Option<JwtSecret> {
268 self.rpc_jwtsecret
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use clap::{Args, Parser};
275 use reth_node_core::args::RpcServerArgs;
276 use reth_rpc_eth_types::RPC_DEFAULT_GAS_CAP;
277 use reth_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
278 use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
279
280 use crate::config::RethRpcServerConfig;
281
282 #[derive(Parser)]
284 struct CommandParser<T: Args> {
285 #[command(flatten)]
286 args: T,
287 }
288
289 #[test]
290 fn test_rpc_gas_cap() {
291 let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
292 let config = args.eth_config();
293 assert_eq!(config.rpc_gas_cap, u64::from(RPC_DEFAULT_GAS_CAP));
294
295 let args =
296 CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.gascap", "1000"]).args;
297 let config = args.eth_config();
298 assert_eq!(config.rpc_gas_cap, 1000);
299
300 let args = CommandParser::<RpcServerArgs>::try_parse_from(["reth", "--rpc.gascap", "0"]);
301 assert!(args.is_err());
302 }
303
304 #[test]
305 fn test_transport_rpc_module_config() {
306 let args = CommandParser::<RpcServerArgs>::parse_from([
307 "reth",
308 "--http.api",
309 "eth,admin,debug",
310 "--http",
311 "--ws",
312 ])
313 .args;
314 let config = args.transport_rpc_module_config();
315 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
316 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
317 assert_eq!(
318 config.ws().cloned().unwrap().into_selection(),
319 RpcModuleSelection::standard_modules()
320 );
321 }
322
323 #[test]
324 fn test_transport_rpc_module_trim_config() {
325 let args = CommandParser::<RpcServerArgs>::parse_from([
326 "reth",
327 "--http.api",
328 " eth, admin, debug",
329 "--http",
330 "--ws",
331 ])
332 .args;
333 let config = args.transport_rpc_module_config();
334 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
335 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
336 assert_eq!(
337 config.ws().cloned().unwrap().into_selection(),
338 RpcModuleSelection::standard_modules()
339 );
340 }
341
342 #[test]
343 fn test_unique_rpc_modules() {
344 let args = CommandParser::<RpcServerArgs>::parse_from([
345 "reth",
346 "--http.api",
347 " eth, admin, debug, eth,admin",
348 "--http",
349 "--ws",
350 ])
351 .args;
352 let config = args.transport_rpc_module_config();
353 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
354 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
355 assert_eq!(
356 config.ws().cloned().unwrap().into_selection(),
357 RpcModuleSelection::standard_modules()
358 );
359 }
360
361 #[test]
362 fn test_rpc_server_config() {
363 let args = CommandParser::<RpcServerArgs>::parse_from([
364 "reth",
365 "--http.api",
366 "eth,admin,debug",
367 "--http",
368 "--ws",
369 "--ws.addr",
370 "127.0.0.1",
371 "--ws.port",
372 "8888",
373 ])
374 .args;
375 let config = args.rpc_server_config();
376 assert_eq!(
377 config.http_address().unwrap(),
378 SocketAddr::V4(SocketAddrV4::new(
379 Ipv4Addr::LOCALHOST,
380 constants::DEFAULT_HTTP_RPC_PORT
381 ))
382 );
383 assert_eq!(
384 config.ws_address().unwrap(),
385 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8888))
386 );
387 assert_eq!(config.ipc_endpoint().unwrap(), constants::DEFAULT_IPC_ENDPOINT);
388 assert!(config.rpc_metrics_enabled());
389 }
390
391 #[test]
392 fn test_rpc_server_config_disable_metrics() {
393 let args =
394 CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.disable-metrics"]).args;
395 let config = args.rpc_server_config();
396 assert!(!config.rpc_metrics_enabled());
397 }
398
399 #[test]
400 fn test_zero_filter_limits() {
401 let args = CommandParser::<RpcServerArgs>::parse_from([
402 "reth",
403 "--rpc-max-blocks-per-filter",
404 "0",
405 "--rpc-max-logs-per-response",
406 "0",
407 ])
408 .args;
409
410 let config = args.eth_config().filter_config();
411 assert_eq!(config.max_blocks_per_filter, Some(u64::MAX));
412 assert_eq!(config.max_logs_per_response, Some(usize::MAX));
413 }
414
415 #[test]
416 fn test_custom_filter_limits() {
417 let args = CommandParser::<RpcServerArgs>::parse_from([
418 "reth",
419 "--rpc-max-blocks-per-filter",
420 "100",
421 "--rpc-max-logs-per-response",
422 "200",
423 ])
424 .args;
425
426 let config = args.eth_config().filter_config();
427 assert_eq!(config.max_blocks_per_filter, Some(100));
428 assert_eq!(config.max_logs_per_response, Some(200));
429 }
430}