Skip to main content

reth_node_core/args/
rpc_state_cache.rs

1use super::{database::parse_byte_size, DefaultRpcServerArgs};
2use clap::{builder::Resettable, Args};
3use reth_cli_util::parsers::{format_duration, parse_duration};
4use reth_rpc_server_types::constants::cache::{
5    DEFAULT_BAL_CACHE_MAX_BYTES, DEFAULT_BAL_CACHE_MAX_LEN, DEFAULT_BLOCK_CACHE_MAX_BYTES,
6    DEFAULT_BLOCK_CACHE_MAX_LEN, DEFAULT_CACHE_IDLE_TIMEOUT, DEFAULT_CONCURRENT_DB_REQUESTS,
7    DEFAULT_MAX_CACHED_TX_HASHES, DEFAULT_RECEIPT_CACHE_MAX_BYTES, DEFAULT_RECEIPT_CACHE_MAX_LEN,
8};
9use std::time::Duration;
10
11/// Parameters to configure RPC state cache.
12#[derive(Debug, Clone, Args, PartialEq, Eq)]
13#[command(next_help_heading = "RPC State Cache")]
14pub struct RpcStateCacheArgs {
15    /// Max number of blocks in cache.
16    #[arg(
17        long = "rpc-cache.max-blocks",
18        default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_blocks,
19    )]
20    pub max_blocks: u32,
21
22    /// Max number receipts in cache.
23    #[arg(
24        long = "rpc-cache.max-receipts",
25        default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_receipts,
26    )]
27    pub max_receipts: u32,
28
29    /// Max number of block access lists in cache.
30    #[arg(
31        long = "rpc-cache.max-bals",
32        default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_bals,
33    )]
34    pub max_bals: u32,
35
36    /// Maximum estimated block cache memory in bytes or with a unit (e.g. 1GB, 500MB).
37    /// Units use powers of 1024. Zero disables caching. The entry count limit also applies.
38    #[arg(long = "rpc-cache.max-blocks-bytes", value_name = "BYTES", value_parser = parse_byte_size, default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_blocks_bytes)]
39    pub max_blocks_bytes: usize,
40
41    /// Maximum estimated receipts cache memory in bytes or with a unit (e.g. 1GB, 500MB).
42    /// Units use powers of 1024. Zero disables caching. The entry count limit also applies.
43    #[arg(long = "rpc-cache.max-receipts-bytes", value_name = "BYTES", value_parser = parse_byte_size, default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_receipts_bytes)]
44    pub max_receipts_bytes: usize,
45
46    /// Maximum estimated block access list cache memory in bytes or with a unit (e.g. 1GB, 500MB).
47    /// Units use powers of 1024. Zero disables caching. The entry count limit also applies.
48    #[arg(long = "rpc-cache.max-bals-bytes", value_name = "BYTES", value_parser = parse_byte_size, default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_bals_bytes)]
49    pub max_bals_bytes: usize,
50
51    /// Evict blocks, receipts, and block access lists after this duration without a cache hit
52    /// (e.g. 5m, 30s). Zero disables expiration. Cleanup starts every 1 to 60 seconds and removes
53    /// at most five entries per cache per poll.
54    #[arg(long = "rpc-cache.idle-timeout", value_name = "DURATION", value_parser = parse_duration, default_value = format_duration(DefaultRpcServerArgs::get_global().rpc_state_cache.idle_timeout))]
55    pub idle_timeout: Duration,
56
57    /// Cache block access lists computed by RPC requests for transaction tracing.
58    #[arg(long = "rpc-cache.cache-computed-bals", default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.cache_computed_bals)]
59    pub cache_computed_bals: bool,
60
61    /// Replay new canonical blocks to cache block access lists until native BAL support.
62    ///
63    /// Optionally replay the latest BLOCKS blocks sequentially on startup. Without a count, only
64    /// new blocks are prewarmed. Implies --rpc-cache.cache-computed-bals.
65    /// Prewarming stops when a canonical block with a block access list hash is received.
66    #[arg(
67        long = "rpc-cache.prewarm-bals",
68        value_name = "BLOCKS",
69        num_args = 0..=1,
70        default_missing_value = "0",
71        default_value = Resettable::from(DefaultRpcServerArgs::get_global().rpc_state_cache.prewarm_bals.map(|v| v.to_string().into())),
72        require_equals = true,
73    )]
74    pub prewarm_bals: Option<usize>,
75
76    /// Max number of concurrent database requests.
77    #[arg(
78        long = "rpc-cache.max-concurrent-db-requests",
79        default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_concurrent_db_requests,
80    )]
81    pub max_concurrent_db_requests: usize,
82
83    /// Maximum number of transaction hashes to cache for transaction lookups.
84    #[arg(
85        long = "rpc-cache.max-cached-tx-hashes",
86        default_value_t = DefaultRpcServerArgs::get_global().rpc_state_cache.max_cached_tx_hashes,
87    )]
88    pub max_cached_tx_hashes: u32,
89}
90
91impl RpcStateCacheArgs {
92    /// Sets the Cache sizes to zero, effectively disabling caching.
93    pub const fn set_zero_lengths(&mut self) {
94        self.max_blocks = 0;
95        self.max_receipts = 0;
96        self.max_bals = 0;
97        self.max_blocks_bytes = 0;
98        self.max_receipts_bytes = 0;
99        self.max_bals_bytes = 0;
100        self.idle_timeout = Duration::ZERO;
101        self.cache_computed_bals = false;
102        self.prewarm_bals = None;
103    }
104}
105
106impl Default for RpcStateCacheArgs {
107    fn default() -> Self {
108        Self {
109            max_blocks: DEFAULT_BLOCK_CACHE_MAX_LEN,
110            max_receipts: DEFAULT_RECEIPT_CACHE_MAX_LEN,
111            max_bals: DEFAULT_BAL_CACHE_MAX_LEN,
112            max_blocks_bytes: DEFAULT_BLOCK_CACHE_MAX_BYTES,
113            max_receipts_bytes: DEFAULT_RECEIPT_CACHE_MAX_BYTES,
114            max_bals_bytes: DEFAULT_BAL_CACHE_MAX_BYTES,
115            idle_timeout: DEFAULT_CACHE_IDLE_TIMEOUT,
116            cache_computed_bals: false,
117            prewarm_bals: None,
118            max_concurrent_db_requests: DEFAULT_CONCURRENT_DB_REQUESTS,
119            max_cached_tx_hashes: DEFAULT_MAX_CACHED_TX_HASHES,
120        }
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::node_config::NodeConfig;
128    use clap::Parser;
129
130    #[derive(Parser)]
131    struct CommandParser {
132        #[command(flatten)]
133        args: RpcStateCacheArgs,
134    }
135
136    #[test]
137    fn rpc_cache_defaults() {
138        let args = CommandParser::parse_from(["reth"]).args;
139        assert_eq!(args, RpcStateCacheArgs::default());
140    }
141
142    #[test]
143    fn rpc_cache_byte_limits_reject_invalid_values() {
144        let overflow = format!("{}0", usize::MAX);
145        let unit_overflow = format!("{}GB", usize::MAX);
146        for flag in [
147            "--rpc-cache.max-blocks-bytes",
148            "--rpc-cache.max-receipts-bytes",
149            "--rpc-cache.max-bals-bytes",
150        ] {
151            for value in ["-1", "-1GB", "1XB", "1.5GB", &overflow, &unit_overflow] {
152                assert!(
153                    CommandParser::try_parse_from(["reth", &format!("{flag}={value}")]).is_err(),
154                    "accepted {flag}={value}"
155                );
156            }
157        }
158    }
159
160    #[test]
161    fn rpc_cache_byte_limits_accept_units() {
162        for (value, expected) in [
163            ("0GB", 0),
164            ("1024B", 1024),
165            ("1KB", 1024),
166            ("500MB", 500 * 1024 * 1024),
167            ("1GB", 1024 * 1024 * 1024),
168            ("1gb", 1024 * 1024 * 1024),
169            (" 500 MB ", 500 * 1024 * 1024),
170            ("1TB", 1024usize.pow(4)),
171        ] {
172            let args = CommandParser::parse_from([
173                "reth",
174                "--rpc-cache.max-blocks-bytes",
175                value,
176                "--rpc-cache.max-receipts-bytes",
177                value,
178                "--rpc-cache.max-bals-bytes",
179                value,
180            ])
181            .args;
182            assert_eq!(args.max_blocks_bytes, expected);
183            assert_eq!(args.max_receipts_bytes, expected);
184            assert_eq!(args.max_bals_bytes, expected);
185        }
186    }
187
188    #[test]
189    fn disabling_rpc_cache_overrides_positive_byte_limits() {
190        let mut config = NodeConfig::default();
191        config.rpc.rpc_state_cache = RpcStateCacheArgs {
192            max_blocks_bytes: 1024,
193            max_receipts_bytes: 2048,
194            max_bals_bytes: 4096,
195            idle_timeout: Duration::from_secs(60),
196            cache_computed_bals: true,
197            prewarm_bals: Some(10),
198            ..Default::default()
199        };
200
201        let args = config.with_disabled_rpc_cache().rpc.rpc_state_cache;
202        assert_eq!(args.max_blocks, 0);
203        assert_eq!(args.max_receipts, 0);
204        assert_eq!(args.max_bals, 0);
205        assert_eq!(args.max_blocks_bytes, 0);
206        assert_eq!(args.max_receipts_bytes, 0);
207        assert_eq!(args.max_bals_bytes, 0);
208        assert_eq!(args.idle_timeout, Duration::ZERO);
209        assert!(!args.cache_computed_bals);
210        assert_eq!(args.prewarm_bals, None);
211    }
212}