reth_node_core/args/
rpc_server.rs

1//! clap [Args](clap::Args) for RPC related arguments.
2
3use 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
27/// Default max number of subscriptions per connection.
28pub(crate) const RPC_DEFAULT_MAX_SUBS_PER_CONN: u32 = 1024;
29
30/// Default max request size in MB.
31pub(crate) const RPC_DEFAULT_MAX_REQUEST_SIZE_MB: u32 = 15;
32
33/// Default max response size in MB.
34///
35/// This is only relevant for very large trace responses.
36pub(crate) const RPC_DEFAULT_MAX_RESPONSE_SIZE_MB: u32 = 160;
37
38/// Default number of incoming connections.
39pub(crate) const RPC_DEFAULT_MAX_CONNECTIONS: u32 = 500;
40
41/// Parameters for configuring the rpc more granularity via CLI
42#[derive(Debug, Clone, Args, PartialEq, Eq)]
43#[command(next_help_heading = "RPC")]
44pub struct RpcServerArgs {
45    /// Enable the HTTP-RPC server
46    #[arg(long, default_value_if("dev", "true", "true"))]
47    pub http: bool,
48
49    /// Http server address to listen on
50    #[arg(long = "http.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
51    pub http_addr: IpAddr,
52
53    /// Http server port to listen on
54    #[arg(long = "http.port", default_value_t = constants::DEFAULT_HTTP_RPC_PORT)]
55    pub http_port: u16,
56
57    /// Rpc Modules to be configured for the HTTP server
58    #[arg(long = "http.api", value_parser = RpcModuleSelectionValueParser::default())]
59    pub http_api: Option<RpcModuleSelection>,
60
61    /// Http Corsdomain to allow request from
62    #[arg(long = "http.corsdomain")]
63    pub http_corsdomain: Option<String>,
64
65    /// Enable the WS-RPC server
66    #[arg(long)]
67    pub ws: bool,
68
69    /// Ws server address to listen on
70    #[arg(long = "ws.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
71    pub ws_addr: IpAddr,
72
73    /// Ws server port to listen on
74    #[arg(long = "ws.port", default_value_t = constants::DEFAULT_WS_RPC_PORT)]
75    pub ws_port: u16,
76
77    /// Origins from which to accept `WebSocket` requests
78    #[arg(id = "ws.origins", long = "ws.origins", alias = "ws.corsdomain")]
79    pub ws_allowed_origins: Option<String>,
80
81    /// Rpc Modules to be configured for the WS server
82    #[arg(long = "ws.api", value_parser = RpcModuleSelectionValueParser::default())]
83    pub ws_api: Option<RpcModuleSelection>,
84
85    /// Disable the IPC-RPC server
86    #[arg(long)]
87    pub ipcdisable: bool,
88
89    /// Filename for IPC socket/pipe within the datadir
90    #[arg(long, default_value_t = constants::DEFAULT_IPC_ENDPOINT.to_string())]
91    pub ipcpath: String,
92
93    /// Auth server address to listen on
94    #[arg(long = "authrpc.addr", default_value_t = IpAddr::V4(Ipv4Addr::LOCALHOST))]
95    pub auth_addr: IpAddr,
96
97    /// Auth server port to listen on
98    #[arg(long = "authrpc.port", default_value_t = constants::DEFAULT_AUTH_PORT)]
99    pub auth_port: u16,
100
101    /// Path to a JWT secret to use for the authenticated engine-API RPC server.
102    ///
103    /// This will enforce JWT authentication for all requests coming from the consensus layer.
104    ///
105    /// If no path is provided, a secret will be generated and stored in the datadir under
106    /// `<DIR>/<CHAIN_ID>/jwt.hex`. For mainnet this would be `~/.reth/mainnet/jwt.hex` by default.
107    #[arg(long = "authrpc.jwtsecret", value_name = "PATH", global = true, required = false)]
108    pub auth_jwtsecret: Option<PathBuf>,
109
110    /// Enable auth engine API over IPC
111    #[arg(long)]
112    pub auth_ipc: bool,
113
114    /// Filename for auth IPC socket/pipe within the datadir
115    #[arg(long = "auth-ipc.path", default_value_t = constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string())]
116    pub auth_ipc_path: String,
117
118    /// Hex encoded JWT secret to authenticate the regular RPC server(s), see `--http.api` and
119    /// `--ws.api`.
120    ///
121    /// This is __not__ used for the authenticated engine-API RPC server, see
122    /// `--authrpc.jwtsecret`.
123    #[arg(long = "rpc.jwtsecret", value_name = "HEX", global = true, required = false)]
124    pub rpc_jwtsecret: Option<JwtSecret>,
125
126    /// Set the maximum RPC request payload size for both HTTP and WS in megabytes.
127    #[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    /// Set the maximum RPC response payload size for both HTTP and WS in megabytes.
131    #[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    /// Set the maximum concurrent subscriptions per connection.
135    #[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    /// Maximum number of RPC server connections.
139    #[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    /// Maximum number of concurrent tracing requests.
143    ///
144    /// By default this chooses a sensible value based on the number of available cores.
145    /// Tracing requests are generally CPU bound.
146    /// Choosing a value that is higher than the available CPU cores can have a negative impact on
147    /// the performance of the node and affect the node's ability to maintain sync.
148    #[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    /// Maximum number of blocks for `trace_filter` requests.
152    #[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    /// Maximum number of blocks that could be scanned per filter request. (0 = entire chain)
156    #[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    /// Maximum number of logs that can be returned in a single response. (0 = no limit)
160    #[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    /// Maximum gas limit for `eth_call` and call tracing RPC methods.
164    #[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    /// Maximum eth transaction fee that can be sent via the RPC APIs (0 = no cap)
174    #[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    /// Maximum number of blocks for `eth_simulateV1` call.
184    #[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    /// The maximum proof window for historical proof generation.
192    /// This value allows for generating historical proofs up to
193    /// configured number of blocks from current tip (up to `tip - window`).
194    #[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    /// Maximum number of concurrent getproof requests.
202    #[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    /// Path to file containing disallowed addresses, json-encoded list of strings. Block
206    /// validation API will reject blocks containing transactions from these addresses.
207    #[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    /// State cache configuration.
211    #[command(flatten)]
212    pub rpc_state_cache: RpcStateCacheArgs,
213
214    /// Gas price oracle configuration.
215    #[command(flatten)]
216    pub gas_price_oracle: GasPriceOracleArgs,
217}
218
219impl RpcServerArgs {
220    /// Enables the HTTP-RPC server.
221    pub const fn with_http(mut self) -> Self {
222        self.http = true;
223        self
224    }
225
226    /// Configures modules for the HTTP-RPC server.
227    pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self {
228        self.http_api = Some(http_api);
229        self
230    }
231
232    /// Enables the WS-RPC server.
233    pub const fn with_ws(mut self) -> Self {
234        self.ws = true;
235        self
236    }
237
238    /// Enables the Auth IPC
239    pub const fn with_auth_ipc(mut self) -> Self {
240        self.auth_ipc = true;
241        self
242    }
243
244    /// Change rpc port numbers based on the instance number, if provided.
245    /// * The `auth_port` is scaled by a factor of `instance * 100`
246    /// * The `http_port` is scaled by a factor of `-instance`
247    /// * The `ws_port` is scaled by a factor of `instance * 2`
248    /// * The `ipcpath` is appended with the instance number: `/tmp/reth.ipc-<instance>`
249    ///
250    /// # Panics
251    /// Warning: if `instance` is zero in debug mode, this will panic.
252    ///
253    /// This will also panic in debug mode if either:
254    /// * `instance` is greater than `655` (scaling would overflow `u16`)
255    /// * `self.auth_port / 100 + (instance - 1)` would overflow `u16`
256    ///
257    /// In release mode, this will silently wrap around.
258    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            // auth port is scaled by a factor of instance * 100
262            self.auth_port += instance * 100 - 100;
263            // http port is scaled by a factor of -instance
264            self.http_port -= instance - 1;
265            // ws port is scaled by a factor of instance * 2
266            self.ws_port += instance * 2 - 2;
267            // append instance file to ipc path
268            self.ipcpath = format!("{}-{}", self.ipcpath, instance);
269        }
270    }
271
272    /// Set the http port to zero, to allow the OS to assign a random unused port when the rpc
273    /// server binds to a socket.
274    pub const fn with_http_unused_port(mut self) -> Self {
275        self.http_port = 0;
276        self
277    }
278
279    /// Set the ws port to zero, to allow the OS to assign a random unused port when the rpc
280    /// server binds to a socket.
281    pub const fn with_ws_unused_port(mut self) -> Self {
282        self.ws_port = 0;
283        self
284    }
285
286    /// Set the auth port to zero, to allow the OS to assign a random unused port when the rpc
287    /// server binds to a socket.
288    pub const fn with_auth_unused_port(mut self) -> Self {
289        self.auth_port = 0;
290        self
291    }
292
293    /// Append a random string to the ipc path, to prevent possible collisions when multiple nodes
294    /// are being run on the same machine.
295    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    /// Configure all ports to be set to a random unused port when bound, and set the IPC path to a
303    /// random path.
304    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/// clap value parser for [`RpcModuleSelection`].
355#[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    /// A helper type to parse Args more easily
392    #[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; // 2 ETH in wei
442        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; // 1.5 ETH in wei
450        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); // 0 = no cap
457    }
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); // 1 ETH default cap
464    }
465}