Skip to main content

reth_node_core/args/
rpc_server.rs

1//! clap [`Args`] for RPC related arguments.
2
3// The clap `Args` derive builds every flag in one `augment_args` function, which needs about
4// 540 KB of stack in unoptimized builds. It runs once at startup on the main thread, and
5// splitting the struct would change field paths used by downstream nodes. Item-level lint
6// attributes on the struct do not reach the generated impl.
7#![allow(clippy::large_unopt_stack_frames)]
8
9use crate::args::{
10    types::{MaxU32, ZeroAsNoneU64},
11    GasPriceOracleArgs, RpcStateCacheArgs,
12};
13use alloy_primitives::{map::AddressSet, utils::format_ether};
14use alloy_rpc_types_engine::JwtSecret;
15use clap::{
16    builder::{PossibleValue, RangedU64ValueParser, Resettable, TypedValueParser},
17    parser::ValueSource,
18    Arg, Args, Command,
19};
20use rand::Rng;
21use reth_cli_util::{
22    parse_duration_from_secs_or_ms, parse_ether_value, parsers::format_duration_as_secs_or_ms,
23};
24use reth_rpc_eth_types::builder::config::PendingBlockKind;
25use reth_rpc_server_types::{constants, RethRpcModule, RpcModuleSelection};
26use std::{
27    ffi::OsStr,
28    net::{IpAddr, Ipv4Addr},
29    path::PathBuf,
30    sync::OnceLock,
31    time::Duration,
32};
33use url::Url;
34
35use super::types::MaxOr;
36
37/// Global static RPC server defaults
38static RPC_SERVER_DEFAULTS: OnceLock<DefaultRpcServerArgs> = OnceLock::new();
39
40/// Default max number of subscriptions per connection.
41pub(crate) const RPC_DEFAULT_MAX_SUBS_PER_CONN: u32 = 1024;
42
43/// Default max request size in MB.
44pub(crate) const RPC_DEFAULT_MAX_REQUEST_SIZE_MB: u32 = 15;
45
46/// Default max response size in MB.
47///
48/// This is only relevant for very large trace responses.
49pub(crate) const RPC_DEFAULT_MAX_RESPONSE_SIZE_MB: u32 = 160;
50
51/// Default trace byte limit per byte of the response limit.
52///
53/// `vmTrace` records about 1.5-5x its JSON size, since a 32-byte stack word serializes as short
54/// hex. Twice the response limit passes every mainnet block whose traces fit in the response, while
55/// keeping a block trace's memory bounded. The default struct logger records its JSON, so the
56/// response limit itself bounds it.
57const RPC_TRACE_BYTES_PER_RESPONSE_BYTE: u64 = 2;
58
59/// Default number of incoming connections.
60///
61/// This restricts how many active connections (http, ws) the server accepts.
62/// Once exceeded, the server can reject new connections.
63pub(crate) const RPC_DEFAULT_MAX_CONNECTIONS: u32 = 500;
64
65/// Default values for RPC server that can be customized
66///
67/// Global defaults can be set via [`DefaultRpcServerArgs::try_init`].
68#[derive(Debug, Clone)]
69pub struct DefaultRpcServerArgs {
70    http: bool,
71    http_addr: IpAddr,
72    http_port: u16,
73    http_disable_compression: bool,
74    http_compression_algorithms: Option<Vec<String>>,
75    http_decompression_algorithms: Option<Vec<String>>,
76    http_api: Option<RpcModuleSelection>,
77    http_corsdomain: Option<String>,
78    ws: bool,
79    ws_addr: IpAddr,
80    ws_port: u16,
81    ws_allowed_origins: Option<String>,
82    ws_api: Option<RpcModuleSelection>,
83    ipcdisable: bool,
84    ipcpath: String,
85    ipc_socket_permissions: Option<String>,
86    auth_addr: IpAddr,
87    auth_port: u16,
88    auth_jwtsecret: Option<PathBuf>,
89    auth_ipc: bool,
90    auth_ipc_path: String,
91    disable_auth_server: bool,
92    rpc_jwtsecret: Option<JwtSecret>,
93    rpc_disable_metrics: bool,
94    rpc_max_request_size: MaxU32,
95    rpc_max_response_size: MaxU32,
96    rpc_max_subscriptions_per_connection: MaxU32,
97    rpc_max_connections: MaxU32,
98    rpc_max_tracing_requests: usize,
99    rpc_max_blocking_io_requests: usize,
100    rpc_max_trace_filter_blocks: u64,
101    rpc_max_blocks_per_filter: ZeroAsNoneU64,
102    rpc_max_logs_per_response: ZeroAsNoneU64,
103    rpc_max_active_filters: ZeroAsNoneU64,
104    rpc_gas_cap: u64,
105    rpc_evm_memory_limit: u64,
106    rpc_tx_fee_cap: u128,
107    rpc_max_simulate_blocks: u64,
108    rpc_max_trace_bytes: Option<usize>,
109    rpc_compute_state_root_for_eth_simulate: bool,
110    rpc_eth_proof_window: u64,
111    rpc_proof_permits: usize,
112    rpc_pending_block: PendingBlockKind,
113    rpc_forwarder: Option<Url>,
114    builder_disallow: Option<AddressSet>,
115    pub(super) rpc_state_cache: RpcStateCacheArgs,
116    pub(super) gas_price_oracle: GasPriceOracleArgs,
117    rpc_send_raw_transaction_sync_timeout: Duration,
118}
119
120impl DefaultRpcServerArgs {
121    /// Initialize the global RPC server defaults with this configuration
122    pub fn try_init(self) -> Result<(), Self> {
123        RPC_SERVER_DEFAULTS.set(self)
124    }
125
126    /// Get a reference to the global RPC server defaults
127    pub fn get_global() -> &'static Self {
128        RPC_SERVER_DEFAULTS.get_or_init(Self::default)
129    }
130
131    /// Set the default HTTP enabled state
132    pub const fn with_http(mut self, v: bool) -> Self {
133        self.http = v;
134        self
135    }
136
137    /// Set the default HTTP address
138    pub const fn with_http_addr(mut self, v: IpAddr) -> Self {
139        self.http_addr = v;
140        self
141    }
142
143    /// Set the default HTTP port
144    pub const fn with_http_port(mut self, v: u16) -> Self {
145        self.http_port = v;
146        self
147    }
148
149    /// Set whether to disable HTTP compression by default
150    pub const fn with_http_disable_compression(mut self, v: bool) -> Self {
151        self.http_disable_compression = v;
152        self
153    }
154
155    /// Set the default allowed HTTP response compression algorithms
156    pub fn with_http_compression_algorithms(mut self, v: Option<Vec<String>>) -> Self {
157        self.http_compression_algorithms = v;
158        self
159    }
160
161    /// Set the default allowed HTTP request decompression algorithms
162    pub fn with_http_decompression_algorithms(mut self, v: Option<Vec<String>>) -> Self {
163        self.http_decompression_algorithms = v;
164        self
165    }
166
167    /// Set the default HTTP API modules
168    pub fn with_http_api(mut self, v: Option<RpcModuleSelection>) -> Self {
169        self.http_api = v;
170        self
171    }
172
173    /// Set the default HTTP CORS domain
174    pub fn with_http_corsdomain(mut self, v: Option<String>) -> Self {
175        self.http_corsdomain = v;
176        self
177    }
178
179    /// Set the default WS enabled state
180    pub const fn with_ws(mut self, v: bool) -> Self {
181        self.ws = v;
182        self
183    }
184
185    /// Set the default WS address
186    pub const fn with_ws_addr(mut self, v: IpAddr) -> Self {
187        self.ws_addr = v;
188        self
189    }
190
191    /// Set the default WS port
192    pub const fn with_ws_port(mut self, v: u16) -> Self {
193        self.ws_port = v;
194        self
195    }
196
197    /// Set the default WS allowed origins
198    pub fn with_ws_allowed_origins(mut self, v: Option<String>) -> Self {
199        self.ws_allowed_origins = v;
200        self
201    }
202
203    /// Set the default WS API modules
204    pub fn with_ws_api(mut self, v: Option<RpcModuleSelection>) -> Self {
205        self.ws_api = v;
206        self
207    }
208
209    /// Set whether to disable IPC by default
210    pub const fn with_ipcdisable(mut self, v: bool) -> Self {
211        self.ipcdisable = v;
212        self
213    }
214
215    /// Set the default IPC path
216    pub fn with_ipcpath(mut self, v: String) -> Self {
217        self.ipcpath = v;
218        self
219    }
220
221    /// Set the default IPC socket permissions
222    pub fn with_ipc_socket_permissions(mut self, v: Option<String>) -> Self {
223        self.ipc_socket_permissions = v;
224        self
225    }
226
227    /// Set the default auth server address
228    pub const fn with_auth_addr(mut self, v: IpAddr) -> Self {
229        self.auth_addr = v;
230        self
231    }
232
233    /// Set the default auth server port
234    pub const fn with_auth_port(mut self, v: u16) -> Self {
235        self.auth_port = v;
236        self
237    }
238
239    /// Set the default auth JWT secret path
240    pub fn with_auth_jwtsecret(mut self, v: Option<PathBuf>) -> Self {
241        self.auth_jwtsecret = v;
242        self
243    }
244
245    /// Set the default auth IPC enabled state
246    pub const fn with_auth_ipc(mut self, v: bool) -> Self {
247        self.auth_ipc = v;
248        self
249    }
250
251    /// Set the default auth IPC path
252    pub fn with_auth_ipc_path(mut self, v: String) -> Self {
253        self.auth_ipc_path = v;
254        self
255    }
256
257    /// Set whether to disable the auth server by default
258    pub const fn with_disable_auth_server(mut self, v: bool) -> Self {
259        self.disable_auth_server = v;
260        self
261    }
262
263    /// Set the default RPC JWT secret
264    pub const fn with_rpc_jwtsecret(mut self, v: Option<JwtSecret>) -> Self {
265        self.rpc_jwtsecret = v;
266        self
267    }
268
269    /// Set whether to disable RPC request metrics by default
270    pub const fn with_rpc_disable_metrics(mut self, v: bool) -> Self {
271        self.rpc_disable_metrics = v;
272        self
273    }
274
275    /// Set the default max request size
276    pub const fn with_rpc_max_request_size(mut self, v: MaxU32) -> Self {
277        self.rpc_max_request_size = v;
278        self
279    }
280
281    /// Set the default max response size
282    pub const fn with_rpc_max_response_size(mut self, v: MaxU32) -> Self {
283        self.rpc_max_response_size = v;
284        self
285    }
286
287    /// Set the default max subscriptions per connection
288    pub const fn with_rpc_max_subscriptions_per_connection(mut self, v: MaxU32) -> Self {
289        self.rpc_max_subscriptions_per_connection = v;
290        self
291    }
292
293    /// Set the default max connections
294    pub const fn with_rpc_max_connections(mut self, v: MaxU32) -> Self {
295        self.rpc_max_connections = v;
296        self
297    }
298
299    /// Set the default max tracing requests
300    pub const fn with_rpc_max_tracing_requests(mut self, v: usize) -> Self {
301        self.rpc_max_tracing_requests = v;
302        self
303    }
304
305    /// Set the default max blocking IO requests
306    pub const fn with_rpc_max_blocking_io_requests(mut self, v: usize) -> Self {
307        self.rpc_max_blocking_io_requests = v;
308        self
309    }
310
311    /// Set the default max trace filter blocks
312    pub const fn with_rpc_max_trace_filter_blocks(mut self, v: u64) -> Self {
313        self.rpc_max_trace_filter_blocks = v;
314        self
315    }
316
317    /// Set the default max blocks per filter
318    pub const fn with_rpc_max_blocks_per_filter(mut self, v: ZeroAsNoneU64) -> Self {
319        self.rpc_max_blocks_per_filter = v;
320        self
321    }
322
323    /// Set the default max logs per response
324    pub const fn with_rpc_max_logs_per_response(mut self, v: ZeroAsNoneU64) -> Self {
325        self.rpc_max_logs_per_response = v;
326        self
327    }
328
329    /// Set the default max active filters
330    pub const fn with_rpc_max_active_filters(mut self, v: ZeroAsNoneU64) -> Self {
331        self.rpc_max_active_filters = v;
332        self
333    }
334
335    /// Set the default gas cap
336    pub const fn with_rpc_gas_cap(mut self, v: u64) -> Self {
337        self.rpc_gas_cap = v;
338        self
339    }
340
341    /// Set the default EVM memory limit
342    pub const fn with_rpc_evm_memory_limit(mut self, v: u64) -> Self {
343        self.rpc_evm_memory_limit = v;
344        self
345    }
346
347    /// Set the default tx fee cap
348    pub const fn with_rpc_tx_fee_cap(mut self, v: u128) -> Self {
349        self.rpc_tx_fee_cap = v;
350        self
351    }
352
353    /// Set the default max simulate blocks
354    pub const fn with_rpc_max_simulate_blocks(mut self, v: u64) -> Self {
355        self.rpc_max_simulate_blocks = v;
356        self
357    }
358
359    /// Set the default maximum bytes a single trace may record
360    pub const fn with_rpc_max_trace_bytes(mut self, v: Option<usize>) -> Self {
361        self.rpc_max_trace_bytes = v;
362        self
363    }
364
365    /// Set whether to compute state roots for `eth_simulateV1` responses by default.
366    pub const fn with_rpc_compute_state_root_for_eth_simulate(mut self, v: bool) -> Self {
367        self.rpc_compute_state_root_for_eth_simulate = v;
368        self
369    }
370
371    /// Set the default eth proof window
372    pub const fn with_rpc_eth_proof_window(mut self, v: u64) -> Self {
373        self.rpc_eth_proof_window = v;
374        self
375    }
376
377    /// Set the default proof permits
378    pub const fn with_rpc_proof_permits(mut self, v: usize) -> Self {
379        self.rpc_proof_permits = v;
380        self
381    }
382
383    /// Set the default pending block kind
384    pub const fn with_rpc_pending_block(mut self, v: PendingBlockKind) -> Self {
385        self.rpc_pending_block = v;
386        self
387    }
388
389    /// Set the default RPC forwarder
390    pub fn with_rpc_forwarder(mut self, v: Option<Url>) -> Self {
391        self.rpc_forwarder = v;
392        self
393    }
394
395    /// Set the default builder disallow addresses
396    pub fn with_builder_disallow(mut self, v: Option<AddressSet>) -> Self {
397        self.builder_disallow = v;
398        self
399    }
400
401    /// Set the default RPC state cache args
402    pub const fn with_rpc_state_cache(mut self, v: RpcStateCacheArgs) -> Self {
403        self.rpc_state_cache = v;
404        self
405    }
406
407    /// Set the default gas price oracle args
408    pub const fn with_gas_price_oracle(mut self, v: GasPriceOracleArgs) -> Self {
409        self.gas_price_oracle = v;
410        self
411    }
412
413    /// Set the default send raw transaction sync timeout
414    pub const fn with_rpc_send_raw_transaction_sync_timeout(mut self, v: Duration) -> Self {
415        self.rpc_send_raw_transaction_sync_timeout = v;
416        self
417    }
418}
419
420impl Default for DefaultRpcServerArgs {
421    fn default() -> Self {
422        Self {
423            http: false,
424            http_addr: Ipv4Addr::LOCALHOST.into(),
425            http_port: constants::DEFAULT_HTTP_RPC_PORT,
426            http_disable_compression: false,
427            http_compression_algorithms: None,
428            http_decompression_algorithms: None,
429            http_api: None,
430            http_corsdomain: None,
431            ws: false,
432            ws_addr: Ipv4Addr::LOCALHOST.into(),
433            ws_port: constants::DEFAULT_WS_RPC_PORT,
434            ws_allowed_origins: None,
435            ws_api: None,
436            ipcdisable: false,
437            ipcpath: constants::DEFAULT_IPC_ENDPOINT.to_string(),
438            ipc_socket_permissions: None,
439            auth_addr: Ipv4Addr::LOCALHOST.into(),
440            auth_port: constants::DEFAULT_AUTH_PORT,
441            auth_jwtsecret: None,
442            auth_ipc: false,
443            auth_ipc_path: constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string(),
444            disable_auth_server: false,
445            rpc_jwtsecret: None,
446            rpc_disable_metrics: false,
447            rpc_max_request_size: RPC_DEFAULT_MAX_REQUEST_SIZE_MB.into(),
448            rpc_max_response_size: RPC_DEFAULT_MAX_RESPONSE_SIZE_MB.into(),
449            rpc_max_subscriptions_per_connection: RPC_DEFAULT_MAX_SUBS_PER_CONN.into(),
450            rpc_max_connections: RPC_DEFAULT_MAX_CONNECTIONS.into(),
451            rpc_max_tracing_requests: constants::default_max_tracing_requests(),
452            rpc_max_blocking_io_requests: constants::DEFAULT_MAX_BLOCKING_IO_REQUEST,
453            rpc_max_trace_filter_blocks: constants::DEFAULT_MAX_TRACE_FILTER_BLOCKS,
454            rpc_max_blocks_per_filter: constants::DEFAULT_MAX_BLOCKS_PER_FILTER.into(),
455            rpc_max_logs_per_response: (constants::DEFAULT_MAX_LOGS_PER_RESPONSE as u64).into(),
456            rpc_max_active_filters: (constants::DEFAULT_MAX_ACTIVE_FILTERS as u64).into(),
457            rpc_gas_cap: constants::gas_oracle::RPC_DEFAULT_GAS_CAP,
458            rpc_evm_memory_limit: 100 * 1024 * 1024,
459            rpc_tx_fee_cap: constants::DEFAULT_TX_FEE_CAP_WEI,
460            rpc_max_simulate_blocks: constants::DEFAULT_MAX_SIMULATE_BLOCKS,
461            rpc_max_trace_bytes: None,
462            rpc_compute_state_root_for_eth_simulate: false,
463            rpc_eth_proof_window: constants::DEFAULT_ETH_PROOF_WINDOW,
464            rpc_proof_permits: constants::DEFAULT_PROOF_PERMITS,
465            rpc_pending_block: PendingBlockKind::Full,
466            rpc_forwarder: None,
467            builder_disallow: None,
468            rpc_state_cache: RpcStateCacheArgs::default(),
469            gas_price_oracle: GasPriceOracleArgs::default(),
470            rpc_send_raw_transaction_sync_timeout:
471                constants::RPC_DEFAULT_SEND_RAW_TX_SYNC_TIMEOUT_SECS,
472        }
473    }
474}
475
476/// Parameters for configuring the rpc more granularity via CLI
477#[derive(Debug, Clone, Args, PartialEq, Eq)]
478#[command(next_help_heading = "RPC")]
479pub struct RpcServerArgs {
480    /// Enable the HTTP-RPC server
481    #[arg(long, default_value_if("dev", "true", "true"), default_value_t = DefaultRpcServerArgs::get_global().http)]
482    pub http: bool,
483
484    /// Http server address to listen on
485    #[arg(long = "http.addr", default_value_t = DefaultRpcServerArgs::get_global().http_addr)]
486    pub http_addr: IpAddr,
487
488    /// Http server port to listen on
489    #[arg(long = "http.port", default_value_t = DefaultRpcServerArgs::get_global().http_port)]
490    pub http_port: u16,
491
492    /// Disable compression for HTTP responses.
493    ///
494    /// Servers listening on a loopback address never compress responses.
495    #[arg(long = "http.disable-compression", default_value_t = DefaultRpcServerArgs::get_global().http_disable_compression)]
496    pub http_disable_compression: bool,
497
498    /// Comma-separated list of allowed compression algorithms for HTTP responses.
499    ///
500    /// If not specified, all supported algorithms are enabled.
501    ///
502    /// Client `Accept-Encoding` quality values select among allowed algorithms; ties prefer
503    /// zstd > br > gzip > deflate. Omitted quality values default to 1; without an acceptable
504    /// allowed algorithm, the response is uncompressed. List order is ignored.
505    #[arg(
506        long = "http.compression",
507        value_name = "ALGOS",
508        value_delimiter = ',',
509        value_parser = ["zstd", "gzip", "deflate", "br"],
510        default_value = Resettable::from(DefaultRpcServerArgs::get_global().http_compression_algorithms.as_ref().map(|v| v.join(",").into()))
511    )]
512    pub http_compression_algorithms: Option<Vec<String>>,
513
514    /// Comma-separated list of allowed decompression algorithms for HTTP requests.
515    ///
516    /// Request decompression is disabled when not specified.
517    #[arg(
518        long = "http.decompression",
519        value_name = "ALGOS",
520        value_delimiter = ',',
521        value_parser = ["zstd", "gzip", "deflate", "br"],
522        default_value = Resettable::from(DefaultRpcServerArgs::get_global().http_decompression_algorithms.as_ref().map(|v| v.join(",").into()))
523    )]
524    pub http_decompression_algorithms: Option<Vec<String>>,
525
526    /// Rpc Modules to be configured for the HTTP server
527    #[arg(
528        long = "http.api",
529        value_parser = DefaultValueParser {
530            inner: RpcModuleSelectionValueParser::default(),
531            default: &DefaultRpcServerArgs::get_global().http_api,
532            to_default: RpcModuleSelection::to_string,
533        },
534        default_value = Resettable::from(DefaultRpcServerArgs::get_global().http_api.as_ref().map(|v| v.to_string().into())),
535    )]
536    pub http_api: Option<RpcModuleSelection>,
537
538    /// Http Corsdomain to allow request from
539    #[arg(long = "http.corsdomain", default_value = Resettable::from(DefaultRpcServerArgs::get_global().http_corsdomain.as_ref().map(|v| v.to_string().into())))]
540    pub http_corsdomain: Option<String>,
541
542    /// Enable the WS-RPC server
543    #[arg(long, default_value_t = DefaultRpcServerArgs::get_global().ws)]
544    pub ws: bool,
545
546    /// Ws server address to listen on
547    #[arg(long = "ws.addr", default_value_t = DefaultRpcServerArgs::get_global().ws_addr)]
548    pub ws_addr: IpAddr,
549
550    /// Ws server port to listen on
551    #[arg(long = "ws.port", default_value_t = DefaultRpcServerArgs::get_global().ws_port)]
552    pub ws_port: u16,
553
554    /// Allowed `WebSocket` origins. Defaults to HTTP(S) origins on `localhost`, `127.0.0.1`, or
555    /// `[::1]` at any port. Use `*` to allow any origin.
556    ///
557    /// When HTTP and `WebSocket` share a listener, either `--http.corsdomain` or `--ws.origins`
558    /// sets the allowed origins for both. If both flags are set, their values must match.
559    #[arg(id = "ws.origins", long = "ws.origins", alias = "ws.corsdomain", default_value = Resettable::from(DefaultRpcServerArgs::get_global().ws_allowed_origins.as_ref().map(|v| v.to_string().into())))]
560    pub ws_allowed_origins: Option<String>,
561
562    /// Rpc Modules to be configured for the WS server
563    #[arg(
564        long = "ws.api",
565        value_parser = DefaultValueParser {
566            inner: RpcModuleSelectionValueParser::default(),
567            default: &DefaultRpcServerArgs::get_global().ws_api,
568            to_default: RpcModuleSelection::to_string,
569        },
570        default_value = Resettable::from(DefaultRpcServerArgs::get_global().ws_api.as_ref().map(|v| v.to_string().into())),
571    )]
572    pub ws_api: Option<RpcModuleSelection>,
573
574    /// Disable the IPC-RPC server
575    #[arg(long, default_value_t = DefaultRpcServerArgs::get_global().ipcdisable)]
576    pub ipcdisable: bool,
577
578    /// Filename for IPC socket/pipe within the datadir
579    #[arg(long, default_value_t = DefaultRpcServerArgs::get_global().ipcpath.clone())]
580    pub ipcpath: String,
581
582    /// Set the permissions for the IPC socket file, in octal format.
583    ///
584    /// Accepts modes up to `0o7777`, with an optional `0o` prefix. If not specified, the
585    /// permissions will be set by the system's umask.
586    ///
587    /// Startup fails if the mode is invalid or the platform cannot apply it before binding the
588    /// socket, which includes macOS.
589    #[arg(long = "ipc.permissions", default_value = Resettable::from(DefaultRpcServerArgs::get_global().ipc_socket_permissions.as_ref().map(|v| v.to_string().into())))]
590    pub ipc_socket_permissions: Option<String>,
591
592    /// Auth server address to listen on
593    #[arg(long = "authrpc.addr", default_value_t = DefaultRpcServerArgs::get_global().auth_addr)]
594    pub auth_addr: IpAddr,
595
596    /// Auth server port to listen on
597    #[arg(long = "authrpc.port", default_value_t = DefaultRpcServerArgs::get_global().auth_port)]
598    pub auth_port: u16,
599
600    /// Path to a JWT secret to use for the authenticated engine-API RPC server.
601    ///
602    /// This will enforce JWT authentication for all requests coming from the consensus layer.
603    ///
604    /// If no path is provided, a secret will be generated and stored in the datadir under
605    /// `<DIR>/<CHAIN_ID>/jwt.hex`. For mainnet this would be `~/.local/share/reth/mainnet/jwt.hex`
606    /// by default.
607    #[arg(long = "authrpc.jwtsecret", value_name = "PATH", global = true, required = false, conflicts_with = "auth_jwtsecret_hex", default_value = Resettable::from(DefaultRpcServerArgs::get_global().auth_jwtsecret.as_ref().map(|v| v.to_string_lossy().into())))]
608    pub auth_jwtsecret: Option<PathBuf>,
609
610    /// Hex encoded JWT secret to use for the authenticated engine-API RPC server.
611    ///
612    /// This will enforce JWT authentication for all requests coming from the consensus layer.
613    /// Cannot be used together with `--authrpc.jwtsecret`.
614    #[arg(
615        long = "authrpc.jwtsecret-hex",
616        value_name = "HEX",
617        global = true,
618        required = false,
619        conflicts_with = "auth_jwtsecret"
620    )]
621    pub auth_jwtsecret_hex: Option<JwtSecret>,
622
623    /// Enable auth engine API over IPC
624    #[arg(long, default_value_t = DefaultRpcServerArgs::get_global().auth_ipc)]
625    pub auth_ipc: bool,
626
627    /// Path for the auth IPC socket/pipe. Explicit paths are used unchanged.
628    ///
629    /// If omitted, uses `/tmp/reth_engine_api.ipc`, with `-<instance>` appended when
630    /// `--instance` is set. Applications can override this default via `DefaultRpcServerArgs`.
631    #[arg(long = "auth-ipc.path")]
632    pub auth_ipc_path: Option<String>,
633
634    /// Disable the auth/engine API server.
635    ///
636    /// This will prevent the authenticated engine-API server from starting. Use this if you're
637    /// running a node that doesn't need to serve engine API requests.
638    #[arg(long = "disable-auth-server", alias = "disable-engine-api", default_value_t = DefaultRpcServerArgs::get_global().disable_auth_server)]
639    pub disable_auth_server: bool,
640
641    /// Hex encoded JWT secret to authenticate the regular RPC server(s), see `--http.api` and
642    /// `--ws.api`.
643    ///
644    /// This is __not__ used for the authenticated engine-API RPC server, see
645    /// `--authrpc.jwtsecret`.
646    #[arg(
647        long = "rpc.jwtsecret",
648        value_name = "HEX",
649        global = true,
650        required = false,
651        value_parser = DefaultValueParser {
652            inner: |value: &str| JwtSecret::from_hex(value),
653            default: &DefaultRpcServerArgs::get_global().rpc_jwtsecret,
654            to_default: configured_default,
655        },
656        default_value = Resettable::from(DefaultRpcServerArgs::get_global().rpc_jwtsecret.as_ref().map(|v| configured_default(v).into())),
657        hide_default_value = true,
658    )]
659    pub rpc_jwtsecret: Option<JwtSecret>,
660
661    /// Disable built-in RPC request metrics.
662    #[arg(long = "rpc.disable-metrics", default_value_t = DefaultRpcServerArgs::get_global().rpc_disable_metrics)]
663    pub rpc_disable_metrics: bool,
664
665    /// Set the maximum RPC request payload size for both HTTP and WS in megabytes.
666    ///
667    /// For compressed HTTP requests, this limit applies to both the compressed and decompressed
668    /// payloads.
669    #[arg(long = "rpc.max-request-size", alias = "rpc-max-request-size", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_request_size)]
670    pub rpc_max_request_size: MaxU32,
671
672    /// Set the maximum RPC response payload size for both HTTP and WS in megabytes.
673    #[arg(long = "rpc.max-response-size", alias = "rpc-max-response-size", visible_alias = "rpc.returndata.limit", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_response_size)]
674    pub rpc_max_response_size: MaxU32,
675
676    /// Set the maximum concurrent subscriptions per connection.
677    #[arg(long = "rpc.max-subscriptions-per-connection", alias = "rpc-max-subscriptions-per-connection", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_subscriptions_per_connection)]
678    pub rpc_max_subscriptions_per_connection: MaxU32,
679
680    /// Maximum number of RPC server connections.
681    #[arg(long = "rpc.max-connections", alias = "rpc-max-connections", value_name = "COUNT", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_connections)]
682    pub rpc_max_connections: MaxU32,
683
684    /// Maximum number of concurrent tracing requests.
685    ///
686    /// By default this chooses a sensible value based on the number of available cores.
687    /// Tracing requests are generally CPU bound.
688    /// Choosing a value that is higher than the available CPU cores can have a negative impact on
689    /// the performance of the node and affect the node's ability to maintain sync.
690    #[arg(long = "rpc.max-tracing-requests", alias = "rpc-max-tracing-requests", value_name = "COUNT", value_parser = RangedU64ValueParser::<usize>::new().range(1..), default_value_t = DefaultRpcServerArgs::get_global().rpc_max_tracing_requests)]
691    pub rpc_max_tracing_requests: usize,
692
693    /// Maximum number of concurrent blocking IO requests.
694    ///
695    /// Blocking IO requests include `eth_call`, `eth_estimateGas`, and similar methods that
696    /// require EVM execution. These are spawned as blocking tasks to avoid blocking the async
697    /// runtime.
698    #[arg(long = "rpc.max-blocking-io-requests", alias = "rpc-max-blocking-io-requests", value_name = "COUNT", value_parser = RangedU64ValueParser::<usize>::new().range(1..), default_value_t = DefaultRpcServerArgs::get_global().rpc_max_blocking_io_requests)]
699    pub rpc_max_blocking_io_requests: usize,
700
701    /// Maximum number of blocks for `trace_filter` requests.
702    #[arg(long = "rpc.max-trace-filter-blocks", alias = "rpc-max-trace-filter-blocks", value_name = "COUNT", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_trace_filter_blocks)]
703    pub rpc_max_trace_filter_blocks: u64,
704
705    /// Maximum number of blocks that could be scanned per filter request. (0 = entire chain)
706    #[arg(long = "rpc.max-blocks-per-filter", alias = "rpc-max-blocks-per-filter", value_name = "COUNT", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_blocks_per_filter)]
707    pub rpc_max_blocks_per_filter: ZeroAsNoneU64,
708
709    /// Maximum number of logs that can be returned in a single response. (0 = no limit)
710    #[arg(long = "rpc.max-logs-per-response", alias = "rpc-max-logs-per-response", value_name = "COUNT", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_logs_per_response)]
711    pub rpc_max_logs_per_response: ZeroAsNoneU64,
712
713    /// Maximum number of filters that can be installed at the same time, across all
714    /// `eth_newFilter`, `eth_newBlockFilter` and `eth_newPendingTransactionFilter` filters. (0 =
715    /// no limit)
716    #[arg(long = "rpc.max-active-filters", alias = "rpc-max-active-filters", value_name = "COUNT", default_value_t = DefaultRpcServerArgs::get_global().rpc_max_active_filters)]
717    pub rpc_max_active_filters: ZeroAsNoneU64,
718
719    /// Maximum gas limit for `eth_call`, `eth_estimateGas`, and call tracing RPC methods.
720    ///
721    /// The calls of an `eth_callMany`, `trace_callMany` or `debug_traceCallMany` request share it.
722    #[arg(
723        long = "rpc.gascap",
724        alias = "rpc-gascap",
725        value_name = "GAS_CAP",
726        value_parser = MaxOr::new(RangedU64ValueParser::<u64>::new().range(1..)),
727        default_value_t = DefaultRpcServerArgs::get_global().rpc_gas_cap
728    )]
729    pub rpc_gas_cap: u64,
730
731    /// Maximum memory the EVM can allocate per call frame in an RPC request.
732    #[arg(
733        long = "rpc.evm-memory-limit",
734        alias = "rpc-evm-memory-limit",
735        value_name = "MEMORY_LIMIT",
736        value_parser = MaxOr::new(RangedU64ValueParser::<u64>::new().range(1..)),
737        default_value_t = DefaultRpcServerArgs::get_global().rpc_evm_memory_limit
738    )]
739    pub rpc_evm_memory_limit: u64,
740
741    /// Maximum eth transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap)
742    #[arg(
743        long = "rpc.txfeecap",
744        alias = "rpc-txfeecap",
745        value_name = "TX_FEE_CAP",
746        value_parser = parse_ether_value,
747        default_value = format_tx_fee_cap(DefaultRpcServerArgs::get_global().rpc_tx_fee_cap)
748    )]
749    pub rpc_tx_fee_cap: u128,
750
751    /// Maximum number of blocks for `eth_simulateV1` call.
752    #[arg(
753        long = "rpc.max-simulate-blocks",
754        value_name = "BLOCKS_COUNT",
755        default_value_t = DefaultRpcServerArgs::get_global().rpc_max_simulate_blocks
756    )]
757    pub rpc_max_simulate_blocks: u64,
758
759    /// Max bytes a traced tx may record, defaults to 2x `--rpc.max-response-size`, 0 is unlimited.
760    ///
761    /// The default struct logs of a debug trace response are limited to `--rpc.max-response-size`
762    /// as well, whatever this value is.
763    #[arg(
764        long = "rpc.max-trace-bytes",
765        value_name = "BYTES",
766        default_value = Resettable::from(DefaultRpcServerArgs::get_global().rpc_max_trace_bytes.map(|v| v.to_string().into()))
767    )]
768    pub rpc_max_trace_bytes: Option<usize>,
769
770    /// Compute state roots for `eth_simulateV1` responses.
771    #[arg(
772        long = "rpc.compute-state-root-for-eth-simulate",
773        env = "RETH_RPC_COMPUTE_STATE_ROOT_FOR_ETH_SIMULATE",
774        default_value_t = DefaultRpcServerArgs::get_global().rpc_compute_state_root_for_eth_simulate
775    )]
776    pub rpc_compute_state_root_for_eth_simulate: bool,
777
778    /// The maximum proof window for historical proof generation.
779    /// This value allows for generating historical proofs up to
780    /// configured number of blocks from current tip (up to `tip - window`).
781    #[arg(
782        long = "rpc.eth-proof-window",
783        default_value_t = DefaultRpcServerArgs::get_global().rpc_eth_proof_window,
784        value_parser = RangedU64ValueParser::<u64>::new().range(..=constants::MAX_ETH_PROOF_WINDOW)
785    )]
786    pub rpc_eth_proof_window: u64,
787
788    /// Maximum number of concurrent getproof requests.
789    #[arg(long = "rpc.proof-permits", alias = "rpc-proof-permits", value_name = "COUNT", value_parser = RangedU64ValueParser::<usize>::new().range(1..), default_value_t = DefaultRpcServerArgs::get_global().rpc_proof_permits)]
790    pub rpc_proof_permits: usize,
791
792    /// Configures the pending block behavior for RPC responses.
793    ///
794    /// Options: full (include all transactions), empty (header only), none (disable pending
795    /// blocks).
796    #[arg(
797        long = "rpc.pending-block",
798        default_value = match DefaultRpcServerArgs::get_global().rpc_pending_block {
799            PendingBlockKind::Empty => "empty",
800            PendingBlockKind::None => "none",
801            PendingBlockKind::Full => "full",
802        },
803        value_name = "KIND",
804    )]
805    pub rpc_pending_block: PendingBlockKind,
806
807    /// Endpoint to forward transactions to.
808    #[arg(
809        long = "rpc.forwarder",
810        alias = "rpc-forwarder",
811        value_name = "FORWARDER",
812        value_parser = DefaultValueParser {
813            inner: Url::parse,
814            default: &DefaultRpcServerArgs::get_global().rpc_forwarder,
815            to_default: configured_default,
816        },
817        default_value = Resettable::from(DefaultRpcServerArgs::get_global().rpc_forwarder.as_ref().map(|v| configured_default(v).into())),
818        hide_default_value = true,
819    )]
820    pub rpc_forwarder: Option<Url>,
821
822    /// Path to file containing disallowed addresses, json-encoded list of strings. Block
823    /// validation API will reject blocks containing transactions from these addresses.
824    #[arg(
825        long = "builder.disallow",
826        value_name = "PATH",
827        value_parser = DefaultValueParser {
828            inner: reth_cli_util::parsers::read_json_from_file::<AddressSet>,
829            default: &DefaultRpcServerArgs::get_global().builder_disallow,
830            to_default: configured_default,
831        },
832        default_value = Resettable::from(DefaultRpcServerArgs::get_global().builder_disallow.as_ref().map(|v| configured_default(v).into())),
833        hide_default_value = true,
834    )]
835    pub builder_disallow: Option<AddressSet>,
836
837    /// State cache configuration.
838    #[command(flatten)]
839    pub rpc_state_cache: RpcStateCacheArgs,
840
841    /// Gas price oracle configuration.
842    #[command(flatten)]
843    pub gas_price_oracle: GasPriceOracleArgs,
844
845    /// Timeout for `send_raw_transaction_sync` RPC method.
846    #[arg(
847        long = "rpc.send-raw-transaction-sync-timeout",
848        value_name = "SECONDS",
849        default_value = format_duration_as_secs_or_ms(DefaultRpcServerArgs::get_global().rpc_send_raw_transaction_sync_timeout),
850        value_parser = parse_duration_from_secs_or_ms,
851    )]
852    pub rpc_send_raw_transaction_sync_timeout: Duration,
853
854    /// Skip invalid transactions in `testing_buildBlockV1` instead of failing.
855    ///
856    /// When enabled, transactions that fail execution will be skipped, and all subsequent
857    /// transactions from the same sender will also be skipped.
858    #[arg(long = "testing.skip-invalid-transactions", default_value_t = false)]
859    pub testing_skip_invalid_transactions: bool,
860
861    /// Override the gas limit used by `testing_buildBlockV1`.
862    ///
863    /// When set, `testing_buildBlockV1` will use this exact value instead of moving toward the
864    /// payload builder's configured gas limit. Accepts short notation: K for thousand, M for
865    /// million, G for billion (e.g., 1G = 1 billion).
866    #[arg(long = "testing.gas-limit", value_name = "GAS_LIMIT", hide = true)]
867    pub testing_gas_limit: Option<u64>,
868
869    /// Force upcasting EIP-4844 blob sidecars to EIP-7594 format when Osaka is active.
870    ///
871    /// When enabled, blob transactions submitted via `eth_sendRawTransaction` with EIP-4844
872    /// sidecars will be automatically converted to EIP-7594 format if the next block is Osaka.
873    /// By default this is disabled, meaning transactions are submitted as-is.
874    #[arg(long = "rpc.force-blob-sidecar-upcasting", default_value_t = false)]
875    pub rpc_force_blob_sidecar_upcasting: bool,
876}
877
878impl RpcServerArgs {
879    /// Enables the HTTP-RPC server.
880    pub const fn with_http(mut self) -> Self {
881        self.http = true;
882        self
883    }
884
885    /// Configures modules for the HTTP-RPC server.
886    pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self {
887        self.http_api = Some(http_api);
888        self
889    }
890
891    /// Enables the WS-RPC server.
892    pub const fn with_ws(mut self) -> Self {
893        self.ws = true;
894        self
895    }
896
897    /// Configures modules for WS-RPC server.
898    pub fn with_ws_api(mut self, ws_api: RpcModuleSelection) -> Self {
899        self.ws_api = Some(ws_api);
900        self
901    }
902
903    /// Enables the Auth IPC
904    pub const fn with_auth_ipc(mut self) -> Self {
905        self.auth_ipc = true;
906        self
907    }
908
909    /// Configures modules for both the HTTP-RPC server and WS-RPC server.
910    ///
911    /// This is the same as calling both [`Self::with_http_api`] and [`Self::with_ws_api`].
912    pub fn with_api(self, api: RpcModuleSelection) -> Self {
913        self.with_http_api(api.clone()).with_ws_api(api)
914    }
915
916    /// Change rpc port numbers based on the instance number, if provided.
917    /// * The `auth_port` is scaled by a factor of `instance * 100`
918    /// * The `http_port` is scaled by a factor of `-instance`
919    /// * The `ws_port` is scaled by a factor of `instance * 2`
920    /// * The `ipcpath` is appended with the instance number: `/tmp/reth.ipc-<instance>`
921    /// * If `auth_ipc_path` is `None`, the default auth IPC path is appended with the instance
922    ///   number: `/tmp/reth_engine_api.ipc-<instance>`. Explicit paths are left unchanged.
923    ///
924    /// # Panics
925    /// Warning: if `instance` is zero in debug mode, this will panic.
926    ///
927    /// This will also panic in debug mode if either:
928    /// * `instance` is greater than `655` (scaling would overflow `u16`)
929    /// * `self.auth_port / 100 + (instance - 1)` would overflow `u16`
930    ///
931    /// In release mode, this will silently wrap around.
932    pub fn adjust_instance_ports(&mut self, instance: Option<u16>) {
933        if let Some(instance) = instance {
934            debug_assert_ne!(instance, 0, "instance must be non-zero");
935            // auth port is scaled by a factor of instance * 100
936            self.auth_port += instance * 100 - 100;
937            // http port is scaled by a factor of -instance
938            self.http_port -= instance - 1;
939            // ws port is scaled by a factor of instance * 2
940            self.ws_port += instance * 2 - 2;
941            // append instance file to ipc path
942            self.ipcpath = format!("{}-{}", self.ipcpath, instance);
943            if self.auth_ipc_path.is_none() {
944                self.auth_ipc_path = Some(format!("{}-{instance}", self.auth_ipc_path()));
945            }
946        }
947    }
948
949    /// Set the http port to zero, to allow the OS to assign a random unused port when the rpc
950    /// server binds to a socket.
951    pub const fn with_http_unused_port(mut self) -> Self {
952        self.http_port = 0;
953        self
954    }
955
956    /// Set the ws port to zero, to allow the OS to assign a random unused port when the rpc
957    /// server binds to a socket.
958    pub const fn with_ws_unused_port(mut self) -> Self {
959        self.ws_port = 0;
960        self
961    }
962
963    /// Set the auth port to zero, to allow the OS to assign a random unused port when the rpc
964    /// server binds to a socket.
965    pub const fn with_auth_unused_port(mut self) -> Self {
966        self.auth_port = 0;
967        self
968    }
969
970    /// Append a random string to the ipc path, to prevent possible collisions when multiple nodes
971    /// are being run on the same machine.
972    pub fn with_ipc_random_path(mut self) -> Self {
973        let random_string: String =
974            rand::rng().sample_iter(rand::distr::Alphanumeric).take(8).map(char::from).collect();
975        self.ipcpath = format!("{}-{}", self.ipcpath, random_string);
976        self
977    }
978
979    /// Configure all ports to be set to a random unused port when bound, and set the IPC path to a
980    /// random path.
981    pub fn with_unused_ports(mut self) -> Self {
982        self = self.with_http_unused_port();
983        self = self.with_ws_unused_port();
984        self = self.with_auth_unused_port();
985        self = self.with_ipc_random_path();
986        self
987    }
988
989    /// Apply a function to the args.
990    pub fn apply<F>(self, f: F) -> Self
991    where
992        F: FnOnce(Self) -> Self,
993    {
994        f(self)
995    }
996
997    /// Configures the timeout for send raw transaction sync.
998    pub const fn with_send_raw_transaction_sync_timeout(mut self, timeout: Duration) -> Self {
999        self.rpc_send_raw_transaction_sync_timeout = timeout;
1000        self
1001    }
1002
1003    /// Returns `true` if the given RPC namespace is enabled on any transport.
1004    pub fn is_namespace_enabled(&self, ns: RethRpcModule) -> bool {
1005        if self.http &&
1006            self.http_api.as_ref().unwrap_or(&RpcModuleSelection::Standard).contains(&ns)
1007        {
1008            return true;
1009        }
1010        if self.ws && self.ws_api.as_ref().unwrap_or(&RpcModuleSelection::Standard).contains(&ns) {
1011            return true;
1012        }
1013        !self.ipcdisable && RpcModuleSelection::default_ipc_modules().contains(&ns)
1014    }
1015
1016    /// Enables forced blob sidecar upcasting from EIP-4844 to EIP-7594 format.
1017    pub const fn with_force_blob_sidecar_upcasting(mut self) -> Self {
1018        self.rpc_force_blob_sidecar_upcasting = true;
1019        self
1020    }
1021
1022    /// Returns the auth IPC endpoint to bind after instance adjustment.
1023    ///
1024    /// If no explicit or instance-adjusted path is set, returns the global default.
1025    pub fn auth_ipc_path(&self) -> &str {
1026        self.auth_ipc_path
1027            .as_deref()
1028            .unwrap_or_else(|| &DefaultRpcServerArgs::get_global().auth_ipc_path)
1029    }
1030
1031    /// Returns the trace byte limit, `None` when `--rpc.max-trace-bytes 0` disables it.
1032    ///
1033    /// By default, a trace may record up to twice the configured RPC response size limit.
1034    pub fn max_trace_bytes(&self) -> Option<usize> {
1035        match self.rpc_max_trace_bytes {
1036            Some(0) => None,
1037            Some(bytes) => Some(bytes),
1038            None => Some(
1039                (u64::from(self.rpc_max_response_size.get()) * 1024 * 1024)
1040                    .saturating_mul(RPC_TRACE_BYTES_PER_RESPONSE_BYTE)
1041                    .try_into()
1042                    .unwrap_or(usize::MAX),
1043            ),
1044        }
1045    }
1046}
1047
1048impl Default for RpcServerArgs {
1049    fn default() -> Self {
1050        let DefaultRpcServerArgs {
1051            http,
1052            http_addr,
1053            http_port,
1054            http_disable_compression,
1055            http_compression_algorithms,
1056            http_decompression_algorithms,
1057            http_api,
1058            http_corsdomain,
1059            ws,
1060            ws_addr,
1061            ws_port,
1062            ws_allowed_origins,
1063            ws_api,
1064            ipcdisable,
1065            ipcpath,
1066            ipc_socket_permissions,
1067            auth_addr,
1068            auth_port,
1069            auth_jwtsecret,
1070            auth_ipc,
1071            auth_ipc_path: _,
1072            disable_auth_server,
1073            rpc_jwtsecret,
1074            rpc_disable_metrics,
1075            rpc_max_request_size,
1076            rpc_max_response_size,
1077            rpc_max_subscriptions_per_connection,
1078            rpc_max_connections,
1079            rpc_max_tracing_requests,
1080            rpc_max_blocking_io_requests,
1081            rpc_max_trace_filter_blocks,
1082            rpc_max_blocks_per_filter,
1083            rpc_max_logs_per_response,
1084            rpc_max_active_filters,
1085            rpc_gas_cap,
1086            rpc_evm_memory_limit,
1087            rpc_tx_fee_cap,
1088            rpc_max_simulate_blocks,
1089            rpc_max_trace_bytes,
1090            rpc_compute_state_root_for_eth_simulate,
1091            rpc_eth_proof_window,
1092            rpc_proof_permits,
1093            rpc_pending_block,
1094            rpc_forwarder,
1095            builder_disallow,
1096            rpc_state_cache,
1097            gas_price_oracle,
1098            rpc_send_raw_transaction_sync_timeout,
1099        } = DefaultRpcServerArgs::get_global().clone();
1100        Self {
1101            http,
1102            http_addr,
1103            http_port,
1104            http_disable_compression,
1105            http_compression_algorithms,
1106            http_decompression_algorithms,
1107            http_api,
1108            http_corsdomain,
1109            ws,
1110            ws_addr,
1111            ws_port,
1112            ws_allowed_origins,
1113            ws_api,
1114            ipcdisable,
1115            ipcpath,
1116            ipc_socket_permissions,
1117            auth_addr,
1118            auth_port,
1119            auth_jwtsecret,
1120            auth_jwtsecret_hex: None,
1121            auth_ipc,
1122            auth_ipc_path: None,
1123            disable_auth_server,
1124            rpc_jwtsecret,
1125            rpc_disable_metrics,
1126            rpc_max_request_size,
1127            rpc_max_response_size,
1128            rpc_max_subscriptions_per_connection,
1129            rpc_max_connections,
1130            rpc_max_tracing_requests,
1131            rpc_max_blocking_io_requests,
1132            rpc_max_trace_filter_blocks,
1133            rpc_max_blocks_per_filter,
1134            rpc_max_logs_per_response,
1135            rpc_max_active_filters,
1136            rpc_gas_cap,
1137            rpc_evm_memory_limit,
1138            rpc_tx_fee_cap,
1139            rpc_max_simulate_blocks,
1140            rpc_max_trace_bytes,
1141            rpc_compute_state_root_for_eth_simulate,
1142            rpc_eth_proof_window,
1143            rpc_proof_permits,
1144            rpc_pending_block,
1145            rpc_forwarder,
1146            builder_disallow,
1147            rpc_state_cache,
1148            gas_price_oracle,
1149            rpc_send_raw_transaction_sync_timeout,
1150            testing_skip_invalid_transactions: false,
1151            testing_gas_limit: None,
1152            rpc_force_blob_sidecar_upcasting: false,
1153        }
1154    }
1155}
1156
1157/// Formats a wei amount as the ether string `--rpc.txfeecap` parses, without trailing zeros.
1158fn format_tx_fee_cap(wei: u128) -> String {
1159    format_ether(wei).trim_end_matches('0').trim_end_matches('.').to_string()
1160}
1161
1162/// clap value parser for [`RpcModuleSelection`] with configurable validation.
1163#[derive(Clone, Debug, Default)]
1164#[non_exhaustive]
1165struct RpcModuleSelectionValueParser;
1166
1167impl TypedValueParser for RpcModuleSelectionValueParser {
1168    type Value = RpcModuleSelection;
1169
1170    fn parse_ref(
1171        &self,
1172        _cmd: &Command,
1173        arg: Option<&Arg>,
1174        value: &OsStr,
1175    ) -> Result<Self::Value, clap::Error> {
1176        let val =
1177            value.to_str().ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?;
1178        let arg = arg.map(ToString::to_string).unwrap_or_else(|| "...".to_owned());
1179        // This accepts any module name, creating Other(name) for unknowns, but rejects the `all`
1180        // and `none` keywords mixed with other modules.
1181        val.parse::<RpcModuleSelection>().map_err(|_| {
1182            clap::Error::raw(
1183                clap::error::ErrorKind::ValueValidation,
1184                format!("invalid value '{val}' for '{arg}': `all` and `none` cannot be combined with other modules\n"),
1185            )
1186        })
1187    }
1188
1189    fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
1190        // Only show standard modules in help text (excludes "other")
1191        let values = RethRpcModule::standard_variant_names().map(PossibleValue::new);
1192        Some(Box::new(values))
1193    }
1194}
1195
1196/// Default value string for args whose typed default must not be serialized.
1197fn configured_default<T>(_: &T) -> String {
1198    "configured".to_string()
1199}
1200
1201/// Uses a typed default without serializing secrets or treating address sets as file paths.
1202#[derive(Clone)]
1203struct DefaultValueParser<P: TypedValueParser>
1204where
1205    P::Value: 'static,
1206{
1207    inner: P,
1208    default: &'static Option<P::Value>,
1209    /// Formats `default` as the arg's `default_value`, so a different default set by an embedding
1210    /// command, such as through `Command::mut_arg`, is parsed instead of replaced.
1211    to_default: fn(&P::Value) -> String,
1212}
1213
1214impl<P: TypedValueParser> TypedValueParser for DefaultValueParser<P>
1215where
1216    P::Value: 'static,
1217{
1218    type Value = P::Value;
1219
1220    fn parse_ref(
1221        &self,
1222        cmd: &Command,
1223        arg: Option<&Arg>,
1224        value: &OsStr,
1225    ) -> Result<Self::Value, clap::Error> {
1226        self.inner.parse_ref(cmd, arg, value)
1227    }
1228
1229    fn parse_ref_(
1230        &self,
1231        cmd: &Command,
1232        arg: Option<&Arg>,
1233        value: &OsStr,
1234        source: ValueSource,
1235    ) -> Result<Self::Value, clap::Error> {
1236        if source == ValueSource::DefaultValue &&
1237            let Some(default) = self.default &&
1238            value == (self.to_default)(default).as_str()
1239        {
1240            Ok(default.clone())
1241        } else {
1242            self.inner.parse_ref_(cmd, arg, value, source)
1243        }
1244    }
1245
1246    fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
1247        self.inner.possible_values()
1248    }
1249}
1250
1251#[cfg(test)]
1252mod tests {
1253    use super::*;
1254    use clap::{Args, Parser};
1255
1256    /// A helper type to parse Args more easily
1257    #[derive(Parser)]
1258    struct CommandParser<T: Args> {
1259        #[command(flatten)]
1260        args: T,
1261    }
1262
1263    #[test]
1264    fn parse_bal_cache_modes() {
1265        for (flag, cache_computed, prewarm) in [
1266            ("--rpc-cache.cache-computed-bals", true, None),
1267            ("--rpc-cache.prewarm-bals", false, Some(0)),
1268            ("--rpc-cache.prewarm-bals=10", false, Some(10)),
1269        ] {
1270            let args = CommandParser::<RpcServerArgs>::parse_from(["reth", flag]).args;
1271            assert_eq!(args.rpc_state_cache.cache_computed_bals, cache_computed);
1272            assert_eq!(args.rpc_state_cache.prewarm_bals, prewarm);
1273        }
1274    }
1275
1276    #[test]
1277    fn test_rpc_server_args_parser() {
1278        let args =
1279            CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
1280                .args;
1281
1282        let apis = args.http_api.unwrap();
1283        let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
1284
1285        assert_eq!(apis, expected);
1286    }
1287
1288    #[test]
1289    fn test_rpc_server_eth_call_bundle_args() {
1290        let args =
1291            CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "eth,admin,debug"])
1292                .args;
1293
1294        let apis = args.http_api.unwrap();
1295        let expected = RpcModuleSelection::try_from_selection(["eth", "admin", "debug"]).unwrap();
1296
1297        assert_eq!(apis, expected);
1298    }
1299
1300    #[test]
1301    fn test_rpc_server_args_parser_none() {
1302        let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--http.api", "none"]).args;
1303        let apis = args.http_api.unwrap();
1304        let expected = RpcModuleSelection::Selection(Default::default());
1305        assert_eq!(apis, expected);
1306    }
1307
1308    #[test]
1309    fn test_rpc_server_args_parser_rejects_mixed_keywords() {
1310        for flag in ["--http.api", "--ws.api"] {
1311            for api in ["all,testing", "eth,all", "none,eth"] {
1312                let Err(err) = CommandParser::<RpcServerArgs>::try_parse_from(["reth", flag, api])
1313                else {
1314                    panic!("{flag} {api} should be rejected")
1315                };
1316                assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "{flag} {api}");
1317                assert!(err.to_string().contains(flag), "{err}");
1318            }
1319        }
1320    }
1321
1322    #[test]
1323    fn rpc_concurrency_limits_reject_zero() {
1324        for flag in
1325            ["--rpc.max-tracing-requests", "--rpc.max-blocking-io-requests", "--rpc.proof-permits"]
1326        {
1327            let result = CommandParser::<RpcServerArgs>::try_parse_from(["reth", flag, "0"]);
1328            assert!(result.is_err(), "{flag} should reject zero");
1329        }
1330
1331        let args = CommandParser::<RpcServerArgs>::parse_from([
1332            "reth",
1333            "--rpc.max-tracing-requests",
1334            "1",
1335            "--rpc.max-blocking-io-requests",
1336            "2",
1337            "--rpc.proof-permits",
1338            "3",
1339        ])
1340        .args;
1341        assert_eq!(args.rpc_max_tracing_requests, 1);
1342        assert_eq!(args.rpc_max_blocking_io_requests, 2);
1343        assert_eq!(args.rpc_proof_permits, 3);
1344    }
1345
1346    #[test]
1347    fn http_compression_algorithms_are_optional() {
1348        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1349        assert!(args.http_compression_algorithms.is_none());
1350
1351        let args = CommandParser::<RpcServerArgs>::parse_from([
1352            "reth",
1353            "--http.compression",
1354            "zstd,gzip,deflate,br",
1355        ])
1356        .args;
1357        assert_eq!(
1358            args.http_compression_algorithms.as_deref().unwrap(),
1359            ["zstd", "gzip", "deflate", "br"]
1360        );
1361
1362        let result =
1363            CommandParser::<RpcServerArgs>::try_parse_from(["reth", "--http.compression", "gizp"]);
1364        assert!(result.is_err());
1365    }
1366
1367    #[test]
1368    fn rpc_server_args_default_sanity_test() {
1369        let default_args = RpcServerArgs::default();
1370        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1371
1372        assert_eq!(args, default_args);
1373    }
1374
1375    #[test]
1376    fn http_request_decompression_is_opt_in() {
1377        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1378        assert!(args.http_decompression_algorithms.is_none());
1379
1380        let args = CommandParser::<RpcServerArgs>::parse_from([
1381            "reth",
1382            "--http.decompression",
1383            "zstd,gzip,deflate,br",
1384        ])
1385        .args;
1386        assert_eq!(
1387            args.http_decompression_algorithms.as_deref().unwrap(),
1388            ["zstd", "gzip", "deflate", "br"]
1389        );
1390    }
1391
1392    #[test]
1393    fn invalid_http_request_decompression_algorithm_is_rejected() {
1394        let result = CommandParser::<RpcServerArgs>::try_parse_from([
1395            "reth",
1396            "--http.decompression",
1397            "gizp",
1398        ]);
1399        assert!(result.is_err());
1400    }
1401
1402    #[test]
1403    fn test_rpc_disable_metrics_arg() {
1404        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1405        assert!(!args.rpc_disable_metrics);
1406
1407        let args =
1408            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.disable-metrics"]).args;
1409        assert!(args.rpc_disable_metrics);
1410    }
1411
1412    #[test]
1413    fn test_rpc_tx_fee_cap_parse_integer() {
1414        let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "2"]).args;
1415        let expected = 2_000_000_000_000_000_000u128; // 2 ETH in wei
1416        assert_eq!(args.rpc_tx_fee_cap, expected);
1417    }
1418
1419    #[test]
1420    fn test_rpc_tx_fee_cap_parse_decimal() {
1421        let args =
1422            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "1.5"]).args;
1423        let expected = 1_500_000_000_000_000_000u128; // 1.5 ETH in wei
1424        assert_eq!(args.rpc_tx_fee_cap, expected);
1425    }
1426
1427    #[test]
1428    fn test_rpc_tx_fee_cap_parse_zero() {
1429        let args = CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.txfeecap", "0"]).args;
1430        assert_eq!(args.rpc_tx_fee_cap, 0); // 0 = no cap
1431    }
1432
1433    #[test]
1434    fn test_rpc_tx_fee_cap_parse_none() {
1435        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1436        let expected = 1_000_000_000_000_000_000u128;
1437        assert_eq!(args.rpc_tx_fee_cap, expected); // 1 ETH default cap
1438    }
1439
1440    #[test]
1441    fn test_rpc_max_trace_bytes() {
1442        let args = CommandParser::<RpcServerArgs>::parse_from(["reth"]).args;
1443        assert_eq!(args.max_trace_bytes(), Some(320 * 1024 * 1024));
1444
1445        let args =
1446            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.max-response-size", "10"])
1447                .args;
1448        assert_eq!(args.max_trace_bytes(), Some(20 * 1024 * 1024));
1449
1450        let args =
1451            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.max-trace-bytes", "1024"])
1452                .args;
1453        assert_eq!(args.max_trace_bytes(), Some(1024));
1454
1455        let args =
1456            CommandParser::<RpcServerArgs>::parse_from(["reth", "--rpc.max-trace-bytes", "0"]).args;
1457        assert_eq!(args.max_trace_bytes(), None);
1458    }
1459
1460    #[test]
1461    fn test_rpc_server_args() {
1462        let args = RpcServerArgs {
1463            http: true,
1464            http_addr: "127.0.0.1".parse().unwrap(),
1465            http_port: 8545,
1466            http_disable_compression: false,
1467            http_compression_algorithms: None,
1468            http_decompression_algorithms: None,
1469            http_api: Some(RpcModuleSelection::try_from_selection(["eth", "admin"]).unwrap()),
1470            http_corsdomain: Some("*".to_string()),
1471            ws: true,
1472            ws_addr: "127.0.0.1".parse().unwrap(),
1473            ws_port: 8546,
1474            ws_allowed_origins: Some("*".to_string()),
1475            ws_api: Some(RpcModuleSelection::try_from_selection(["eth", "admin"]).unwrap()),
1476            ipcdisable: false,
1477            ipcpath: "reth.ipc".to_string(),
1478            ipc_socket_permissions: Some("0o666".to_string()),
1479            auth_addr: "127.0.0.1".parse().unwrap(),
1480            auth_port: 8551,
1481            auth_jwtsecret: Some(std::path::PathBuf::from("/tmp/jwt.hex")),
1482            auth_jwtsecret_hex: None,
1483            auth_ipc: false,
1484            auth_ipc_path: Some("engine.ipc".to_string()),
1485            disable_auth_server: false,
1486            rpc_jwtsecret: Some(
1487                JwtSecret::from_hex(
1488                    "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1489                )
1490                .unwrap(),
1491            ),
1492            rpc_disable_metrics: false,
1493            rpc_max_request_size: 15u32.into(),
1494            rpc_max_response_size: 160u32.into(),
1495            rpc_max_subscriptions_per_connection: 1024u32.into(),
1496            rpc_max_connections: 500u32.into(),
1497            rpc_max_tracing_requests: 16,
1498            rpc_max_blocking_io_requests: 256,
1499            rpc_max_trace_filter_blocks: 4000,
1500            rpc_max_blocks_per_filter: 1000u64.into(),
1501            rpc_max_logs_per_response: 10000u64.into(),
1502            rpc_max_active_filters: 500u64.into(),
1503            rpc_gas_cap: 50_000_000,
1504            rpc_evm_memory_limit: 256,
1505            rpc_tx_fee_cap: 2_000_000_000_000_000_000u128,
1506            rpc_max_simulate_blocks: 256,
1507            rpc_max_trace_bytes: Some(1 << 20),
1508            rpc_compute_state_root_for_eth_simulate: false,
1509            rpc_eth_proof_window: 100_000,
1510            rpc_proof_permits: 16,
1511            rpc_pending_block: PendingBlockKind::Full,
1512            rpc_forwarder: Some("http://localhost:8545".parse().unwrap()),
1513            builder_disallow: None,
1514            rpc_state_cache: RpcStateCacheArgs {
1515                max_blocks: 5000,
1516                max_receipts: 2000,
1517                max_bals: 1000,
1518                cache_computed_bals: true,
1519                prewarm_bals: Some(0),
1520                max_concurrent_db_requests: 512,
1521                max_cached_tx_hashes: 100_000,
1522                ..Default::default()
1523            },
1524            gas_price_oracle: GasPriceOracleArgs {
1525                blocks: 20,
1526                ignore_price: 2,
1527                max_price: 500_000_000_000,
1528                percentile: 60,
1529                default_suggested_fee: None,
1530            },
1531            rpc_send_raw_transaction_sync_timeout: std::time::Duration::from_secs(30),
1532            testing_skip_invalid_transactions: true,
1533            testing_gas_limit: None,
1534            rpc_force_blob_sidecar_upcasting: false,
1535        };
1536
1537        let parsed_args = CommandParser::<RpcServerArgs>::parse_from([
1538            "reth",
1539            "--http",
1540            "--http.addr",
1541            "127.0.0.1",
1542            "--http.port",
1543            "8545",
1544            "--http.api",
1545            "eth,admin",
1546            "--http.corsdomain",
1547            "*",
1548            "--ws",
1549            "--ws.addr",
1550            "127.0.0.1",
1551            "--ws.port",
1552            "8546",
1553            "--ws.origins",
1554            "*",
1555            "--ws.api",
1556            "eth,admin",
1557            "--ipcpath",
1558            "reth.ipc",
1559            "--ipc.permissions",
1560            "0o666",
1561            "--authrpc.addr",
1562            "127.0.0.1",
1563            "--authrpc.port",
1564            "8551",
1565            "--authrpc.jwtsecret",
1566            "/tmp/jwt.hex",
1567            "--auth-ipc.path",
1568            "engine.ipc",
1569            "--rpc.jwtsecret",
1570            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1571            "--rpc.max-request-size",
1572            "15",
1573            "--rpc.max-response-size",
1574            "160",
1575            "--rpc.max-subscriptions-per-connection",
1576            "1024",
1577            "--rpc.max-connections",
1578            "500",
1579            "--rpc.max-tracing-requests",
1580            "16",
1581            "--rpc.max-blocking-io-requests",
1582            "256",
1583            "--rpc.max-trace-filter-blocks",
1584            "4000",
1585            "--rpc.max-blocks-per-filter",
1586            "1000",
1587            "--rpc.max-logs-per-response",
1588            "10000",
1589            "--rpc.max-active-filters",
1590            "500",
1591            "--rpc.gascap",
1592            "50000000",
1593            "--rpc.evm-memory-limit",
1594            "256",
1595            "--rpc.txfeecap",
1596            "2.0",
1597            "--rpc.max-simulate-blocks",
1598            "256",
1599            "--rpc.max-trace-bytes",
1600            "1048576",
1601            "--rpc.eth-proof-window",
1602            "100000",
1603            "--rpc.proof-permits",
1604            "16",
1605            "--rpc.pending-block",
1606            "full",
1607            "--rpc.forwarder",
1608            "http://localhost:8545",
1609            "--rpc-cache.max-blocks",
1610            "5000",
1611            "--rpc-cache.max-receipts",
1612            "2000",
1613            "--rpc-cache.max-bals",
1614            "1000",
1615            "--rpc-cache.cache-computed-bals",
1616            "--rpc-cache.prewarm-bals",
1617            "--rpc-cache.max-concurrent-db-requests",
1618            "512",
1619            "--gpo.blocks",
1620            "20",
1621            "--gpo.ignoreprice",
1622            "2",
1623            "--gpo.maxprice",
1624            "500000000000",
1625            "--gpo.percentile",
1626            "60",
1627            "--rpc.send-raw-transaction-sync-timeout",
1628            "30s",
1629            "--testing.skip-invalid-transactions",
1630        ])
1631        .args;
1632
1633        assert_eq!(parsed_args, args);
1634    }
1635
1636    #[test]
1637    fn parse_auth_jwtsecret_hex() {
1638        let hex = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
1639        let args =
1640            CommandParser::<RpcServerArgs>::parse_from(["reth", "--authrpc.jwtsecret-hex", hex])
1641                .args;
1642
1643        let expected = JwtSecret::from_hex(hex).unwrap();
1644        assert_eq!(args.auth_jwtsecret_hex, Some(expected));
1645        assert_eq!(args.auth_jwtsecret, None);
1646    }
1647
1648    #[test]
1649    fn test_auth_jwtsecret_and_hex_are_mutually_exclusive() {
1650        let result = CommandParser::<RpcServerArgs>::try_parse_from([
1651            "reth",
1652            "--authrpc.jwtsecret",
1653            "/tmp/jwt.hex",
1654            "--authrpc.jwtsecret-hex",
1655            "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1656        ]);
1657
1658        assert!(result.is_err());
1659    }
1660
1661    #[test]
1662    fn test_adjust_instance_ports_suffixes_ipc_paths() {
1663        let paths: Vec<_> = (1..=3u16)
1664            .map(|instance| {
1665                let mut args = RpcServerArgs::default();
1666                let ipcpath = args.ipcpath.clone();
1667                let auth_ipc_path = args.auth_ipc_path().to_string();
1668                args.adjust_instance_ports(Some(instance));
1669                assert_eq!(args.ipcpath, format!("{ipcpath}-{instance}"));
1670                assert_eq!(args.auth_ipc_path(), format!("{auth_ipc_path}-{instance}"));
1671                args.auth_ipc_path().to_string()
1672            })
1673            .collect();
1674
1675        assert_eq!(
1676            paths,
1677            [
1678                "/tmp/reth_engine_api.ipc-1",
1679                "/tmp/reth_engine_api.ipc-2",
1680                "/tmp/reth_engine_api.ipc-3"
1681            ]
1682        );
1683
1684        // Without an instance the paths are left untouched.
1685        let mut args = RpcServerArgs::default();
1686        let auth_ipc_path = args.auth_ipc_path().to_string();
1687        args.adjust_instance_ports(None);
1688        assert_eq!(args.auth_ipc_path(), auth_ipc_path);
1689    }
1690
1691    #[test]
1692    fn test_adjust_instance_ports_preserves_explicit_auth_ipc_path() {
1693        for path in ["engine.ipc", constants::DEFAULT_ENGINE_API_IPC_ENDPOINT] {
1694            let mut args =
1695                CommandParser::<RpcServerArgs>::parse_from(["reth", "--auth-ipc.path", path]).args;
1696            args.adjust_instance_ports(Some(2));
1697            assert_eq!(args.auth_ipc_path(), path);
1698        }
1699    }
1700}