1use std::{
4 collections::HashSet,
5 ffi::OsStr,
6 net::{IpAddr, Ipv4Addr},
7 path::PathBuf,
8};
9
10use alloy_primitives::Address;
11use alloy_rpc_types_engine::JwtSecret;
12use clap::{
13 builder::{PossibleValue, RangedU64ValueParser, TypedValueParser},
14 Arg, Args, Command,
15};
16use rand::Rng;
17use reth_cli_util::parse_ether_value;
18use reth_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
19
20use crate::args::{
21 types::{MaxU32, ZeroAsNoneU64},
22 GasPriceOracleArgs, RpcStateCacheArgs,
23};
24
25use super::types::MaxOr;
26
27pub(crate) const RPC_DEFAULT_MAX_SUBS_PER_CONN: u32 = 1024;
29
30pub(crate) const RPC_DEFAULT_MAX_REQUEST_SIZE_MB: u32 = 15;
32
33pub(crate) const RPC_DEFAULT_MAX_RESPONSE_SIZE_MB: u32 = 160;
37
38pub(crate) const RPC_DEFAULT_MAX_CONNECTIONS: u32 = 500;
40
41#[derive(Debug, Clone, Args, PartialEq, Eq)]
43#[command(next_help_heading = "RPC")]
44pub struct RpcServerArgs {
45 #[arg(long, default_value_if("dev", "true", "true"))]
47 pub http: bool,
48
49 #[arg(long = "http.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
51 pub http_addr: IpAddr,
52
53 #[arg(long = "http.port", default_value_t = constants::DEFAULT_HTTP_RPC_PORT)]
55 pub http_port: u16,
56
57 #[arg(long = "http.api", value_parser = RpcModuleSelectionValueParser::default())]
59 pub http_api: Option<RpcModuleSelection>,
60
61 #[arg(long = "http.corsdomain")]
63 pub http_corsdomain: Option<String>,
64
65 #[arg(long)]
67 pub ws: bool,
68
69 #[arg(long = "ws.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
71 pub ws_addr: IpAddr,
72
73 #[arg(long = "ws.port", default_value_t = constants::DEFAULT_WS_RPC_PORT)]
75 pub ws_port: u16,
76
77 #[arg(id = "ws.origins", long = "ws.origins", alias = "ws.corsdomain")]
79 pub ws_allowed_origins: Option<String>,
80
81 #[arg(long = "ws.api", value_parser = RpcModuleSelectionValueParser::default())]
83 pub ws_api: Option<RpcModuleSelection>,
84
85 #[arg(long)]
87 pub ipcdisable: bool,
88
89 #[arg(long, default_value_t = constants::DEFAULT_IPC_ENDPOINT.to_string())]
91 pub ipcpath: String,
92
93 #[arg(long = "authrpc.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
95 pub auth_addr: IpAddr,
96
97 #[arg(long = "authrpc.port", default_value_t = constants::DEFAULT_AUTH_PORT)]
99 pub auth_port: u16,
100
101 #[arg(long = "authrpc.jwtsecret", value_name = "PATH", global = true, required = false)]
108 pub auth_jwtsecret: Option<PathBuf>,
109
110 #[arg(long)]
112 pub auth_ipc: bool,
113
114 #[arg(long = "auth-ipc.path", default_value_t = constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string())]
116 pub auth_ipc_path: String,
117
118 #[arg(long = "rpc.jwtsecret", value_name = "HEX", global = true, required = false)]
124 pub rpc_jwtsecret: Option<JwtSecret>,
125
126 #[arg(long = "rpc.max-request-size", alias = "rpc-max-request-size", default_value_t = RPC_DEFAULT_MAX_REQUEST_SIZE_MB.into())]
128 pub rpc_max_request_size: MaxU32,
129
130 #[arg(long = "rpc.max-response-size", alias = "rpc-max-response-size", visible_alias = "rpc.returndata.limit", default_value_t = RPC_DEFAULT_MAX_RESPONSE_SIZE_MB.into())]
132 pub rpc_max_response_size: MaxU32,
133
134 #[arg(long = "rpc.max-subscriptions-per-connection", alias = "rpc-max-subscriptions-per-connection", default_value_t = RPC_DEFAULT_MAX_SUBS_PER_CONN.into())]
136 pub rpc_max_subscriptions_per_connection: MaxU32,
137
138 #[arg(long = "rpc.max-connections", alias = "rpc-max-connections", value_name = "COUNT", default_value_t = RPC_DEFAULT_MAX_CONNECTIONS.into())]
140 pub rpc_max_connections: MaxU32,
141
142 #[arg(long = "rpc.max-tracing-requests", alias = "rpc-max-tracing-requests", value_name = "COUNT", default_value_t = constants::default_max_tracing_requests())]
149 pub rpc_max_tracing_requests: usize,
150
151 #[arg(long = "rpc.max-trace-filter-blocks", alias = "rpc-max-trace-filter-blocks", value_name = "COUNT", default_value_t = constants::DEFAULT_MAX_TRACE_FILTER_BLOCKS)]
153 pub rpc_max_trace_filter_blocks: u64,
154
155 #[arg(long = "rpc.max-blocks-per-filter", alias = "rpc-max-blocks-per-filter", value_name = "COUNT", default_value_t = ZeroAsNoneU64::new(constants::DEFAULT_MAX_BLOCKS_PER_FILTER))]
157 pub rpc_max_blocks_per_filter: ZeroAsNoneU64,
158
159 #[arg(long = "rpc.max-logs-per-response", alias = "rpc-max-logs-per-response", value_name = "COUNT", default_value_t = ZeroAsNoneU64::new(constants::DEFAULT_MAX_LOGS_PER_RESPONSE as u64))]
161 pub rpc_max_logs_per_response: ZeroAsNoneU64,
162
163 #[arg(
165 long = "rpc.gascap",
166 alias = "rpc-gascap",
167 value_name = "GAS_CAP",
168 value_parser = MaxOr::new(RangedU64ValueParser::<u64>::new().range(1..)),
169 default_value_t = constants::gas_oracle::RPC_DEFAULT_GAS_CAP
170 )]
171 pub rpc_gas_cap: u64,
172
173 #[arg(
175 long = "rpc.txfeecap",
176 alias = "rpc-txfeecap",
177 value_name = "TX_FEE_CAP",
178 value_parser = parse_ether_value,
179 default_value = "1.0"
180 )]
181 pub rpc_tx_fee_cap: u128,
182
183 #[arg(
185 long = "rpc.max-simulate-blocks",
186 value_name = "BLOCKS_COUNT",
187 default_value_t = constants::DEFAULT_MAX_SIMULATE_BLOCKS
188 )]
189 pub rpc_max_simulate_blocks: u64,
190
191 #[arg(
195 long = "rpc.eth-proof-window",
196 default_value_t = constants::DEFAULT_ETH_PROOF_WINDOW,
197 value_parser = RangedU64ValueParser::<u64>::new().range(..=constants::MAX_ETH_PROOF_WINDOW)
198 )]
199 pub rpc_eth_proof_window: u64,
200
201 #[arg(long = "rpc.proof-permits", alias = "rpc-proof-permits", value_name = "COUNT", default_value_t = constants::DEFAULT_PROOF_PERMITS)]
203 pub rpc_proof_permits: usize,
204
205 #[arg(long = "builder.disallow", value_name = "PATH", value_parser = reth_cli_util::parsers::read_json_from_file::<HashSet<Address>>)]
208 pub builder_disallow: Option<HashSet<Address>>,
209
210 #[command(flatten)]
212 pub rpc_state_cache: RpcStateCacheArgs,
213
214 #[command(flatten)]
216 pub gas_price_oracle: GasPriceOracleArgs,
217}
218
219impl RpcServerArgs {
220 pub const fn with_http(mut self) -> Self {
222 self.http = true;
223 self
224 }
225
226 pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self {
228 self.http_api = Some(http_api);
229 self
230 }
231
232 pub const fn with_ws(mut self) -> Self {
234 self.ws = true;
235 self
236 }
237
238 pub const fn with_auth_ipc(mut self) -> Self {
240 self.auth_ipc = true;
241 self
242 }
243
244 pub fn adjust_instance_ports(&mut self, instance: Option<u16>) {
259 if let Some(instance) = instance {
260 debug_assert_ne!(instance, 0, "instance must be non-zero");
261 self.auth_port += instance * 100 - 100;
263 self.http_port -= instance - 1;
265 self.ws_port += instance * 2 - 2;
267 self.ipcpath = format!("{}-{}", self.ipcpath, instance);
269 }
270 }
271
272 pub const fn with_http_unused_port(mut self) -> Self {
275 self.http_port = 0;
276 self
277 }
278
279 pub const fn with_ws_unused_port(mut self) -> Self {
282 self.ws_port = 0;
283 self
284 }
285
286 pub const fn with_auth_unused_port(mut self) -> Self {
289 self.auth_port = 0;
290 self
291 }
292
293 pub fn with_ipc_random_path(mut self) -> Self {
296 let random_string: String =
297 rand::rng().sample_iter(rand::distr::Alphanumeric).take(8).map(char::from).collect();
298 self.ipcpath = format!("{}-{}", self.ipcpath, random_string);
299 self
300 }
301
302 pub fn with_unused_ports(mut self) -> Self {
305 self = self.with_http_unused_port();
306 self = self.with_ws_unused_port();
307 self = self.with_auth_unused_port();
308 self = self.with_ipc_random_path();
309 self
310 }
311}
312
313impl Default for RpcServerArgs {
314 fn default() -> Self {
315 Self {
316 http: false,
317 http_addr: Ipv4Addr::LOCALHOST.into(),
318 http_port: constants::DEFAULT_HTTP_RPC_PORT,
319 http_api: None,
320 http_corsdomain: None,
321 ws: false,
322 ws_addr: Ipv4Addr::LOCALHOST.into(),
323 ws_port: constants::DEFAULT_WS_RPC_PORT,
324 ws_allowed_origins: None,
325 ws_api: None,
326 ipcdisable: false,
327 ipcpath: constants::DEFAULT_IPC_ENDPOINT.to_string(),
328 auth_addr: Ipv4Addr::LOCALHOST.into(),
329 auth_port: constants::DEFAULT_AUTH_PORT,
330 auth_jwtsecret: None,
331 auth_ipc: false,
332 auth_ipc_path: constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string(),
333 rpc_jwtsecret: None,
334 rpc_max_request_size: RPC_DEFAULT_MAX_REQUEST_SIZE_MB.into(),
335 rpc_max_response_size: RPC_DEFAULT_MAX_RESPONSE_SIZE_MB.into(),
336 rpc_max_subscriptions_per_connection: RPC_DEFAULT_MAX_SUBS_PER_CONN.into(),
337 rpc_max_connections: RPC_DEFAULT_MAX_CONNECTIONS.into(),
338 rpc_max_tracing_requests: constants::default_max_tracing_requests(),
339 rpc_max_trace_filter_blocks: constants::DEFAULT_MAX_TRACE_FILTER_BLOCKS,
340 rpc_max_blocks_per_filter: constants::DEFAULT_MAX_BLOCKS_PER_FILTER.into(),
341 rpc_max_logs_per_response: (constants::DEFAULT_MAX_LOGS_PER_RESPONSE as u64).into(),
342 rpc_gas_cap: constants::gas_oracle::RPC_DEFAULT_GAS_CAP,
343 rpc_tx_fee_cap: constants::DEFAULT_TX_FEE_CAP_WEI,
344 rpc_max_simulate_blocks: constants::DEFAULT_MAX_SIMULATE_BLOCKS,
345 rpc_eth_proof_window: constants::DEFAULT_ETH_PROOF_WINDOW,
346 gas_price_oracle: GasPriceOracleArgs::default(),
347 rpc_state_cache: RpcStateCacheArgs::default(),
348 rpc_proof_permits: constants::DEFAULT_PROOF_PERMITS,
349 builder_disallow: Default::default(),
350 }
351 }
352}
353
354#[derive(Clone, Debug, Default)]
356#[non_exhaustive]
357struct RpcModuleSelectionValueParser;
358
359impl TypedValueParser for RpcModuleSelectionValueParser {
360 type Value = RpcModuleSelection;
361
362 fn parse_ref(
363 &self,
364 _cmd: &Command,
365 arg: Option<&Arg>,
366 value: &OsStr,
367 ) -> Result<Self::Value, clap::Error> {
368 let val =
369 value.to_str().ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?;
370 val.parse::<RpcModuleSelection>().map_err(|err| {
371 let arg = arg.map(|a| a.to_string()).unwrap_or_else(|| "...".to_owned());
372 let possible_values = RethRpcModule::all_variant_names().to_vec().join(",");
373 let msg = format!(
374 "Invalid value '{val}' for {arg}: {err}.\n [possible values: {possible_values}]"
375 );
376 clap::Error::raw(clap::error::ErrorKind::InvalidValue, msg)
377 })
378 }
379
380 fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
381 let values = RethRpcModule::all_variant_names().iter().map(PossibleValue::new);
382 Some(Box::new(values))
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use clap::{Args, Parser};
390
391 #[derive(Parser)]
393 struct CommandParser<T: Args> {
394 #[command(flatten)]
395 args: T,
396 }
397
398 #[test]
399 fn test_rpc_server_args_parser() {
400 let args =
401 CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
402 .args;
403
404 let apis = args.http_api.unwrap();
405 let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
406
407 assert_eq!(apis, expected);
408 }
409
410 #[test]
411 fn test_rpc_server_eth_call_bundle_args() {
412 let args =
413 CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
414 .args;
415
416 let apis = args.http_api.unwrap();
417 let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
418
419 assert_eq!(apis, expected);
420 }
421
422 #[test]
423 fn test_rpc_server_args_parser_none() {
424 let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "none"]).args;
425 let apis = args.http_api.unwrap();
426 let expected = RpcModuleSelection::Selection(Default::default());
427 assert_eq!(apis, expected);
428 }
429
430 #[test]
431 fn rpc_server_args_default_sanity_test() {
432 let default_args = RpcServerArgs::default();
433 let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
434
435 assert_eq!(args, default_args);
436 }
437
438 #[test]
439 fn test_rpc_tx_fee_cap_parse_integer() {
440 let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "2"]).args;
441 let expected = 2_000_000_000_000_000_000u128; assert_eq!(args.rpc_tx_fee_cap, expected);
443 }
444
445 #[test]
446 fn test_rpc_tx_fee_cap_parse_decimal() {
447 let args =
448 CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "1.5"]).args;
449 let expected = 1_500_000_000_000_000_000u128; assert_eq!(args.rpc_tx_fee_cap, expected);
451 }
452
453 #[test]
454 fn test_rpc_tx_fee_cap_parse_zero() {
455 let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "0"]).args;
456 assert_eq!(args.rpc_tx_fee_cap, 0); }
458
459 #[test]
460 fn test_rpc_tx_fee_cap_parse_none() {
461 let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
462 let expected = 1_000_000_000_000_000_000u128;
463 assert_eq!(args.rpc_tx_fee_cap, expected); }
465}