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_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
18
19use crate::args::{
20 types::{MaxU32, ZeroAsNoneU64},
21 GasPriceOracleArgs, RpcStateCacheArgs,
22};
23
24pub(crate) const RPC_DEFAULT_MAX_SUBS_PER_CONN: u32 = 1024;
26
27pub(crate) const RPC_DEFAULT_MAX_REQUEST_SIZE_MB: u32 = 15;
29
30pub(crate) const RPC_DEFAULT_MAX_RESPONSE_SIZE_MB: u32 = 160;
34
35pub(crate) const RPC_DEFAULT_MAX_CONNECTIONS: u32 = 500;
37
38#[derive(Debug, Clone, Args, PartialEq, Eq)]
40#[command(next_help_heading = "RPC")]
41pub struct RpcServerArgs {
42 #[arg(long, default_value_if("dev", "true", "true"))]
44 pub http: bool,
45
46 #[arg(long = "http.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
48 pub http_addr: IpAddr,
49
50 #[arg(long = "http.port", default_value_t = constants::DEFAULT_HTTP_RPC_PORT)]
52 pub http_port: u16,
53
54 #[arg(long = "http.api", value_parser = RpcModuleSelectionValueParser::default())]
56 pub http_api: Option<RpcModuleSelection>,
57
58 #[arg(long = "http.corsdomain")]
60 pub http_corsdomain: Option<String>,
61
62 #[arg(long)]
64 pub ws: bool,
65
66 #[arg(long = "ws.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
68 pub ws_addr: IpAddr,
69
70 #[arg(long = "ws.port", default_value_t = constants::DEFAULT_WS_RPC_PORT)]
72 pub ws_port: u16,
73
74 #[arg(id = "ws.origins", long = "ws.origins")]
76 pub ws_allowed_origins: Option<String>,
77
78 #[arg(long = "ws.api", value_parser = RpcModuleSelectionValueParser::default())]
80 pub ws_api: Option<RpcModuleSelection>,
81
82 #[arg(long)]
84 pub ipcdisable: bool,
85
86 #[arg(long, default_value_t = constants::DEFAULT_IPC_ENDPOINT.to_string())]
88 pub ipcpath: String,
89
90 #[arg(long = "authrpc.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
92 pub auth_addr: IpAddr,
93
94 #[arg(long = "authrpc.port", default_value_t = constants::DEFAULT_AUTH_PORT)]
96 pub auth_port: u16,
97
98 #[arg(long = "authrpc.jwtsecret", value_name = "PATH", global = true, required = false)]
105 pub auth_jwtsecret: Option<PathBuf>,
106
107 #[arg(long)]
109 pub auth_ipc: bool,
110
111 #[arg(long = "auth-ipc.path", default_value_t = constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string())]
113 pub auth_ipc_path: String,
114
115 #[arg(long = "rpc.jwtsecret", value_name = "HEX", global = true, required = false)]
121 pub rpc_jwtsecret: Option<JwtSecret>,
122
123 #[arg(long = "rpc.max-request-size", alias = "rpc-max-request-size", default_value_t = RPC_DEFAULT_MAX_REQUEST_SIZE_MB.into())]
125 pub rpc_max_request_size: MaxU32,
126
127 #[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())]
129 pub rpc_max_response_size: MaxU32,
130
131 #[arg(long = "rpc.max-subscriptions-per-connection", alias = "rpc-max-subscriptions-per-connection", default_value_t = RPC_DEFAULT_MAX_SUBS_PER_CONN.into())]
133 pub rpc_max_subscriptions_per_connection: MaxU32,
134
135 #[arg(long = "rpc.max-connections", alias = "rpc-max-connections", value_name = "COUNT", default_value_t = RPC_DEFAULT_MAX_CONNECTIONS.into())]
137 pub rpc_max_connections: MaxU32,
138
139 #[arg(long = "rpc.max-tracing-requests", alias = "rpc-max-tracing-requests", value_name = "COUNT", default_value_t = constants::default_max_tracing_requests())]
146 pub rpc_max_tracing_requests: usize,
147
148 #[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))]
150 pub rpc_max_blocks_per_filter: ZeroAsNoneU64,
151
152 #[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))]
154 pub rpc_max_logs_per_response: ZeroAsNoneU64,
155
156 #[arg(
158 long = "rpc.gascap",
159 alias = "rpc-gascap",
160 value_name = "GAS_CAP",
161 value_parser = RangedU64ValueParser::<u64>::new().range(1..),
162 default_value_t = constants::gas_oracle::RPC_DEFAULT_GAS_CAP
163 )]
164 pub rpc_gas_cap: u64,
165
166 #[arg(
168 long = "rpc.max-simulate-blocks",
169 value_name = "BLOCKS_COUNT",
170 default_value_t = constants::DEFAULT_MAX_SIMULATE_BLOCKS
171 )]
172 pub rpc_max_simulate_blocks: u64,
173
174 #[arg(
178 long = "rpc.eth-proof-window",
179 default_value_t = constants::DEFAULT_ETH_PROOF_WINDOW,
180 value_parser = RangedU64ValueParser::<u64>::new().range(..=constants::MAX_ETH_PROOF_WINDOW)
181 )]
182 pub rpc_eth_proof_window: u64,
183
184 #[arg(long = "rpc.proof-permits", alias = "rpc-proof-permits", value_name = "COUNT", default_value_t = constants::DEFAULT_PROOF_PERMITS)]
186 pub rpc_proof_permits: usize,
187
188 #[arg(long = "builder.disallow", value_name = "PATH", value_parser = reth_cli_util::parsers::read_json_from_file::<HashSet<Address>>)]
191 pub builder_disallow: Option<HashSet<Address>>,
192
193 #[command(flatten)]
195 pub rpc_state_cache: RpcStateCacheArgs,
196
197 #[command(flatten)]
199 pub gas_price_oracle: GasPriceOracleArgs,
200}
201
202impl RpcServerArgs {
203 pub const fn with_http(mut self) -> Self {
205 self.http = true;
206 self
207 }
208
209 pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self {
211 self.http_api = Some(http_api);
212 self
213 }
214
215 pub const fn with_ws(mut self) -> Self {
217 self.ws = true;
218 self
219 }
220
221 pub const fn with_auth_ipc(mut self) -> Self {
223 self.auth_ipc = true;
224 self
225 }
226
227 pub fn adjust_instance_ports(&mut self, instance: u16) {
242 debug_assert_ne!(instance, 0, "instance must be non-zero");
243 self.auth_port += instance * 100 - 100;
245 self.http_port -= instance - 1;
247 self.ws_port += instance * 2 - 2;
249
250 if instance > 1 {
252 self.ipcpath = format!("{}-{}", self.ipcpath, instance);
253 }
254 }
255
256 pub const fn with_http_unused_port(mut self) -> Self {
259 self.http_port = 0;
260 self
261 }
262
263 pub const fn with_ws_unused_port(mut self) -> Self {
266 self.ws_port = 0;
267 self
268 }
269
270 pub const fn with_auth_unused_port(mut self) -> Self {
273 self.auth_port = 0;
274 self
275 }
276
277 pub fn with_ipc_random_path(mut self) -> Self {
280 let random_string: String = rand::thread_rng()
281 .sample_iter(rand::distributions::Alphanumeric)
282 .take(8)
283 .map(char::from)
284 .collect();
285 self.ipcpath = format!("{}-{}", self.ipcpath, random_string);
286 self
287 }
288
289 pub fn with_unused_ports(mut self) -> Self {
292 self = self.with_http_unused_port();
293 self = self.with_ws_unused_port();
294 self = self.with_auth_unused_port();
295 self = self.with_ipc_random_path();
296 self
297 }
298}
299
300impl Default for RpcServerArgs {
301 fn default() -> Self {
302 Self {
303 http: false,
304 http_addr: Ipv4Addr::LOCALHOST.into(),
305 http_port: constants::DEFAULT_HTTP_RPC_PORT,
306 http_api: None,
307 http_corsdomain: None,
308 ws: false,
309 ws_addr: Ipv4Addr::LOCALHOST.into(),
310 ws_port: constants::DEFAULT_WS_RPC_PORT,
311 ws_allowed_origins: None,
312 ws_api: None,
313 ipcdisable: false,
314 ipcpath: constants::DEFAULT_IPC_ENDPOINT.to_string(),
315 auth_addr: Ipv4Addr::LOCALHOST.into(),
316 auth_port: constants::DEFAULT_AUTH_PORT,
317 auth_jwtsecret: None,
318 auth_ipc: false,
319 auth_ipc_path: constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string(),
320 rpc_jwtsecret: None,
321 rpc_max_request_size: RPC_DEFAULT_MAX_REQUEST_SIZE_MB.into(),
322 rpc_max_response_size: RPC_DEFAULT_MAX_RESPONSE_SIZE_MB.into(),
323 rpc_max_subscriptions_per_connection: RPC_DEFAULT_MAX_SUBS_PER_CONN.into(),
324 rpc_max_connections: RPC_DEFAULT_MAX_CONNECTIONS.into(),
325 rpc_max_tracing_requests: constants::default_max_tracing_requests(),
326 rpc_max_blocks_per_filter: constants::DEFAULT_MAX_BLOCKS_PER_FILTER.into(),
327 rpc_max_logs_per_response: (constants::DEFAULT_MAX_LOGS_PER_RESPONSE as u64).into(),
328 rpc_gas_cap: constants::gas_oracle::RPC_DEFAULT_GAS_CAP,
329 rpc_max_simulate_blocks: constants::DEFAULT_MAX_SIMULATE_BLOCKS,
330 rpc_eth_proof_window: constants::DEFAULT_ETH_PROOF_WINDOW,
331 gas_price_oracle: GasPriceOracleArgs::default(),
332 rpc_state_cache: RpcStateCacheArgs::default(),
333 rpc_proof_permits: constants::DEFAULT_PROOF_PERMITS,
334 builder_disallow: Default::default(),
335 }
336 }
337}
338
339#[derive(Clone, Debug, Default)]
341#[non_exhaustive]
342struct RpcModuleSelectionValueParser;
343
344impl TypedValueParser for RpcModuleSelectionValueParser {
345 type Value = RpcModuleSelection;
346
347 fn parse_ref(
348 &self,
349 _cmd: &Command,
350 arg: Option<&Arg>,
351 value: &OsStr,
352 ) -> Result<Self::Value, clap::Error> {
353 let val =
354 value.to_str().ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?;
355 val.parse::<RpcModuleSelection>().map_err(|err| {
356 let arg = arg.map(|a| a.to_string()).unwrap_or_else(|| "...".to_owned());
357 let possible_values = RethRpcModule::all_variant_names().to_vec().join(",");
358 let msg = format!(
359 "Invalid value '{val}' for {arg}: {err}.\n [possible values: {possible_values}]"
360 );
361 clap::Error::raw(clap::error::ErrorKind::InvalidValue, msg)
362 })
363 }
364
365 fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
366 let values = RethRpcModule::all_variant_names().iter().map(PossibleValue::new);
367 Some(Box::new(values))
368 }
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374 use clap::{Args, Parser};
375
376 #[derive(Parser)]
378 struct CommandParser<T: Args> {
379 #[command(flatten)]
380 args: T,
381 }
382
383 #[test]
384 fn test_rpc_server_args_parser() {
385 let args =
386 CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
387 .args;
388
389 let apis = args.http_api.unwrap();
390 let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
391
392 assert_eq!(apis, expected);
393 }
394
395 #[test]
396 fn test_rpc_server_eth_call_bundle_args() {
397 let args =
398 CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
399 .args;
400
401 let apis = args.http_api.unwrap();
402 let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
403
404 assert_eq!(apis, expected);
405 }
406
407 #[test]
408 fn test_rpc_server_args_parser_none() {
409 let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "none"]).args;
410 let apis = args.http_api.unwrap();
411 let expected = RpcModuleSelection::Selection(Default::default());
412 assert_eq!(apis, expected);
413 }
414
415 #[test]
416 fn rpc_server_args_default_sanity_test() {
417 let default_args = RpcServerArgs::default();
418 let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
419
420 assert_eq!(args, default_args);
421 }
422}