1use std::{net::SocketAddr, path::PathBuf};
2
3use jsonrpsee::server::ServerBuilder;
4use reth_node_core::{args::RpcServerArgs, utils::get_or_create_jwt_secret_from_path};
5use reth_rpc::ValidationApiConfig;
6use reth_rpc_eth_types::{EthConfig, EthStateCacheConfig, GasPriceOracleConfig};
7use reth_rpc_layer::{JwtError, JwtSecret};
8use reth_rpc_server_types::RpcModuleSelection;
9use tower::layer::util::Identity;
10use tracing::{debug, warn};
11
12use crate::{
13 auth::AuthServerConfig, error::RpcError, IpcServerBuilder, RpcModuleConfig, RpcServerConfig,
14 TransportRpcModuleConfig,
15};
16
17pub trait RethRpcServerConfig {
22 fn is_ipc_enabled(&self) -> bool;
24
25 fn ipc_path(&self) -> &str;
27
28 fn eth_config(&self) -> EthConfig;
30
31 fn flashbots_config(&self) -> ValidationApiConfig;
33
34 fn state_cache_config(&self) -> EthStateCacheConfig;
36
37 fn rpc_max_request_size_bytes(&self) -> u32;
39
40 fn rpc_max_response_size_bytes(&self) -> u32;
42
43 fn gas_price_oracle_config(&self) -> GasPriceOracleConfig;
45
46 fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig;
51
52 fn http_ws_server_builder(&self) -> ServerBuilder<Identity, Identity>;
54
55 fn ipc_server_builder(&self) -> IpcServerBuilder<Identity, Identity>;
57
58 fn rpc_server_config(&self) -> RpcServerConfig;
60
61 fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError>;
63
64 fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError>;
78
79 fn rpc_secret_key(&self) -> Option<JwtSecret>;
83}
84
85impl RethRpcServerConfig for RpcServerArgs {
86 fn is_ipc_enabled(&self) -> bool {
87 !self.ipcdisable
89 }
90
91 fn ipc_path(&self) -> &str {
92 self.ipcpath.as_str()
93 }
94
95 fn eth_config(&self) -> EthConfig {
96 EthConfig::default()
97 .max_tracing_requests(self.rpc_max_tracing_requests)
98 .max_trace_filter_blocks(self.rpc_max_trace_filter_blocks)
99 .max_blocks_per_filter(self.rpc_max_blocks_per_filter.unwrap_or_max())
100 .max_logs_per_response(self.rpc_max_logs_per_response.unwrap_or_max() as usize)
101 .eth_proof_window(self.rpc_eth_proof_window)
102 .rpc_gas_cap(self.rpc_gas_cap)
103 .rpc_max_simulate_blocks(self.rpc_max_simulate_blocks)
104 .state_cache(self.state_cache_config())
105 .gpo_config(self.gas_price_oracle_config())
106 .proof_permits(self.rpc_proof_permits)
107 }
108
109 fn flashbots_config(&self) -> ValidationApiConfig {
110 ValidationApiConfig {
111 disallow: self.builder_disallow.clone().unwrap_or_default(),
112 validation_window: self.rpc_eth_proof_window,
113 }
114 }
115
116 fn state_cache_config(&self) -> EthStateCacheConfig {
117 EthStateCacheConfig {
118 max_blocks: self.rpc_state_cache.max_blocks,
119 max_receipts: self.rpc_state_cache.max_receipts,
120 max_headers: self.rpc_state_cache.max_headers,
121 max_concurrent_db_requests: self.rpc_state_cache.max_concurrent_db_requests,
122 }
123 }
124
125 fn rpc_max_request_size_bytes(&self) -> u32 {
126 self.rpc_max_request_size.get().saturating_mul(1024 * 1024)
127 }
128
129 fn rpc_max_response_size_bytes(&self) -> u32 {
130 self.rpc_max_response_size.get().saturating_mul(1024 * 1024)
131 }
132
133 fn gas_price_oracle_config(&self) -> GasPriceOracleConfig {
134 self.gas_price_oracle.gas_price_oracle_config()
135 }
136
137 fn transport_rpc_module_config(&self) -> TransportRpcModuleConfig {
138 let mut config = TransportRpcModuleConfig::default()
139 .with_config(RpcModuleConfig::new(self.eth_config(), self.flashbots_config()));
140
141 if self.http {
142 config = config.with_http(
143 self.http_api
144 .clone()
145 .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
146 );
147 }
148
149 if self.ws {
150 config = config.with_ws(
151 self.ws_api
152 .clone()
153 .unwrap_or_else(|| RpcModuleSelection::standard_modules().into()),
154 );
155 }
156
157 if self.is_ipc_enabled() {
158 config = config.with_ipc(RpcModuleSelection::default_ipc_modules());
159 }
160
161 config
162 }
163
164 fn http_ws_server_builder(&self) -> ServerBuilder<Identity, Identity> {
165 ServerBuilder::new()
166 .max_connections(self.rpc_max_connections.get())
167 .max_request_body_size(self.rpc_max_request_size_bytes())
168 .max_response_body_size(self.rpc_max_response_size_bytes())
169 .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
170 }
171
172 fn ipc_server_builder(&self) -> IpcServerBuilder<Identity, Identity> {
173 IpcServerBuilder::default()
174 .max_subscriptions_per_connection(self.rpc_max_subscriptions_per_connection.get())
175 .max_request_body_size(self.rpc_max_request_size_bytes())
176 .max_response_body_size(self.rpc_max_response_size_bytes())
177 .max_connections(self.rpc_max_connections.get())
178 }
179
180 fn rpc_server_config(&self) -> RpcServerConfig {
181 let mut config = RpcServerConfig::default().with_jwt_secret(self.rpc_secret_key());
182
183 if self.http_api.is_some() && !self.http {
184 warn!(
185 target: "reth::cli",
186 "The --http.api flag is set but --http is not enabled. HTTP RPC API will not be exposed."
187 );
188 }
189
190 if self.http {
191 let socket_address = SocketAddr::new(self.http_addr, self.http_port);
192 config = config
193 .with_http_address(socket_address)
194 .with_http(self.http_ws_server_builder())
195 .with_http_cors(self.http_corsdomain.clone())
196 .with_ws_cors(self.ws_allowed_origins.clone());
197 }
198
199 if self.ws {
200 let socket_address = SocketAddr::new(self.ws_addr, self.ws_port);
201 config = config.with_ws_address(socket_address).with_ws(self.http_ws_server_builder());
202 }
203
204 if self.is_ipc_enabled() {
205 config =
206 config.with_ipc(self.ipc_server_builder()).with_ipc_endpoint(self.ipcpath.clone());
207 }
208
209 config
210 }
211
212 fn auth_server_config(&self, jwt_secret: JwtSecret) -> Result<AuthServerConfig, RpcError> {
213 let address = SocketAddr::new(self.auth_addr, self.auth_port);
214
215 let mut builder = AuthServerConfig::builder(jwt_secret).socket_addr(address);
216 if self.auth_ipc {
217 builder = builder
218 .ipc_endpoint(self.auth_ipc_path.clone())
219 .with_ipc_config(self.ipc_server_builder());
220 }
221 Ok(builder.build())
222 }
223
224 fn auth_jwt_secret(&self, default_jwt_path: PathBuf) -> Result<JwtSecret, JwtError> {
225 match self.auth_jwtsecret.as_ref() {
226 Some(fpath) => {
227 debug!(target: "reth::cli", user_path=?fpath, "Reading JWT auth secret file");
228 JwtSecret::from_file(fpath)
229 }
230 None => get_or_create_jwt_secret_from_path(&default_jwt_path),
231 }
232 }
233
234 fn rpc_secret_key(&self) -> Option<JwtSecret> {
235 self.rpc_jwtsecret
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use clap::{Args, Parser};
242 use reth_node_core::args::RpcServerArgs;
243 use reth_rpc_eth_types::RPC_DEFAULT_GAS_CAP;
244 use reth_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
245 use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
246
247 use crate::config::RethRpcServerConfig;
248
249 #[derive(Parser)]
251 struct CommandParser<T: Args> {
252 #[command(flatten)]
253 args: T,
254 }
255
256 #[test]
257 fn test_rpc_gas_cap() {
258 let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
259 let config = args.eth_config();
260 assert_eq!(config.rpc_gas_cap, u64::from(RPC_DEFAULT_GAS_CAP));
261
262 let args =
263 CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.gascap", "1000"]).args;
264 let config = args.eth_config();
265 assert_eq!(config.rpc_gas_cap, 1000);
266
267 let args = CommandParser::<RpcServerArgs>::try_parse_from(["reth", "--rpc.gascap", "0"]);
268 assert!(args.is_err());
269 }
270
271 #[test]
272 fn test_transport_rpc_module_config() {
273 let args = CommandParser::<RpcServerArgs>::parse_from([
274 "reth",
275 "--http.api",
276 "eth,admin,debug",
277 "--http",
278 "--ws",
279 ])
280 .args;
281 let config = args.transport_rpc_module_config();
282 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
283 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
284 assert_eq!(
285 config.ws().cloned().unwrap().into_selection(),
286 RpcModuleSelection::standard_modules()
287 );
288 }
289
290 #[test]
291 fn test_transport_rpc_module_trim_config() {
292 let args = CommandParser::<RpcServerArgs>::parse_from([
293 "reth",
294 "--http.api",
295 " eth, admin, debug",
296 "--http",
297 "--ws",
298 ])
299 .args;
300 let config = args.transport_rpc_module_config();
301 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
302 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
303 assert_eq!(
304 config.ws().cloned().unwrap().into_selection(),
305 RpcModuleSelection::standard_modules()
306 );
307 }
308
309 #[test]
310 fn test_unique_rpc_modules() {
311 let args = CommandParser::<RpcServerArgs>::parse_from([
312 "reth",
313 "--http.api",
314 " eth, admin, debug, eth,admin",
315 "--http",
316 "--ws",
317 ])
318 .args;
319 let config = args.transport_rpc_module_config();
320 let expected = [RethRpcModule::Eth, RethRpcModule::Admin, RethRpcModule::Debug];
321 assert_eq!(config.http().cloned().unwrap().into_selection(), expected.into());
322 assert_eq!(
323 config.ws().cloned().unwrap().into_selection(),
324 RpcModuleSelection::standard_modules()
325 );
326 }
327
328 #[test]
329 fn test_rpc_server_config() {
330 let args = CommandParser::<RpcServerArgs>::parse_from([
331 "reth",
332 "--http.api",
333 "eth,admin,debug",
334 "--http",
335 "--ws",
336 "--ws.addr",
337 "127.0.0.1",
338 "--ws.port",
339 "8888",
340 ])
341 .args;
342 let config = args.rpc_server_config();
343 assert_eq!(
344 config.http_address().unwrap(),
345 SocketAddr::V4(SocketAddrV4::new(
346 Ipv4Addr::LOCALHOST,
347 constants::DEFAULT_HTTP_RPC_PORT
348 ))
349 );
350 assert_eq!(
351 config.ws_address().unwrap(),
352 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8888))
353 );
354 assert_eq!(config.ipc_endpoint().unwrap(), constants::DEFAULT_IPC_ENDPOINT);
355 }
356
357 #[test]
358 fn test_zero_filter_limits() {
359 let args = CommandParser::<RpcServerArgs>::parse_from([
360 "reth",
361 "--rpc-max-blocks-per-filter",
362 "0",
363 "--rpc-max-logs-per-response",
364 "0",
365 ])
366 .args;
367
368 let config = args.eth_config().filter_config();
369 assert_eq!(config.max_blocks_per_filter, Some(u64::MAX));
370 assert_eq!(config.max_logs_per_response, Some(usize::MAX));
371 }
372
373 #[test]
374 fn test_custom_filter_limits() {
375 let args = CommandParser::<RpcServerArgs>::parse_from([
376 "reth",
377 "--rpc-max-blocks-per-filter",
378 "100",
379 "--rpc-max-logs-per-response",
380 "200",
381 ])
382 .args;
383
384 let config = args.eth_config().filter_config();
385 assert_eq!(config.max_blocks_per_filter, Some(100));
386 assert_eq!(config.max_logs_per_response, Some(200));
387 }
388}