Skip to main content

reth_cli_util/
parsers.rs

1use alloy_eips::BlockHashOrNumber;
2use alloy_primitives::B256;
3use jiff::{
4    fmt::friendly::{SpanParser, SpanPrinter},
5    SignedDuration, Span, SpanRelativeTo, SpanRound, Unit,
6};
7use reth_fs_util::FsPathError;
8use std::{
9    net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
10    path::Path,
11    str::FromStr,
12    time::Duration,
13};
14
15/// Helper to parse a [Duration] from seconds
16pub fn parse_duration_from_secs(arg: &str) -> eyre::Result<Duration, std::num::ParseIntError> {
17    let seconds = arg.parse()?;
18    Ok(Duration::from_secs(seconds))
19}
20
21/// Helper to parse a [Duration] from seconds if it's a number or milliseconds if the input contains
22/// a `ms` suffix:
23///  * `5ms` -> 5 milliseconds
24///  * `5` -> 5 seconds
25///  * `5s` -> 5 seconds
26pub fn parse_duration_from_secs_or_ms(
27    arg: &str,
28) -> eyre::Result<Duration, std::num::ParseIntError> {
29    if arg.ends_with("ms") {
30        arg.trim_end_matches("ms").parse().map(Duration::from_millis)
31    } else if arg.ends_with('s') {
32        arg.trim_end_matches('s').parse().map(Duration::from_secs)
33    } else {
34        arg.parse().map(Duration::from_secs)
35    }
36}
37
38/// Helper to format a [Duration] to the format that can be parsed by
39/// [`parse_duration_from_secs_or_ms`].
40pub fn format_duration_as_secs_or_ms(duration: Duration) -> String {
41    if duration.as_millis().is_multiple_of(1000) {
42        format!("{}", duration.as_secs())
43    } else {
44        format!("{}ms", duration.as_millis())
45    }
46}
47
48/// Parses a human-readable duration such as `30s`, `500ms`, `5min`, `1h 30m` or `2d`.
49///
50/// Days are 24 hours and weeks are 7 days. Months and years are rejected because their length
51/// varies. A bare `0` is accepted as zero.
52pub fn parse_duration(arg: &str) -> Result<Duration, jiff::Error> {
53    if arg.trim() == "0" {
54        return Ok(Duration::ZERO)
55    }
56    let span = SpanParser::new().parse_span(arg)?;
57    span.to_duration(SpanRelativeTo::days_are_24_hours())?.try_into()
58}
59
60/// Formats a [Duration] in the format parsed by [`parse_duration`], e.g. `1d 2h 30m 500ms`.
61pub fn format_duration(duration: Duration) -> String {
62    let printer = SpanPrinter::new();
63    let span = SignedDuration::try_from(duration)
64        .and_then(Span::try_from)
65        .and_then(|span| span.round(SpanRound::new().largest(Unit::Day).days_are_24_hours()));
66    match span {
67        Ok(span) => printer.span_to_string(&span),
68        // A span holds at most ~20,000 years, so longer durations are printed in hours.
69        Err(_) => printer.unsigned_duration_to_string(&duration),
70    }
71}
72
73/// Parse [`BlockHashOrNumber`]
74pub fn hash_or_num_value_parser(value: &str) -> eyre::Result<BlockHashOrNumber, eyre::Error> {
75    match B256::from_str(value) {
76        Ok(hash) => Ok(BlockHashOrNumber::Hash(hash)),
77        Err(_) => Ok(BlockHashOrNumber::Number(value.parse()?)),
78    }
79}
80
81/// Error thrown while parsing a socket address.
82#[derive(thiserror::Error, Debug)]
83pub enum SocketAddressParsingError {
84    /// Failed to convert the string into a socket addr
85    #[error("could not parse socket address: {0}")]
86    Io(#[from] std::io::Error),
87    /// Input must not be empty
88    #[error("cannot parse socket address from empty string")]
89    Empty,
90    /// Failed to parse the address
91    #[error("could not parse socket address from {0}")]
92    Parse(String),
93    /// Failed to parse port
94    #[error("could not parse port: {0}")]
95    Port(#[from] std::num::ParseIntError),
96}
97
98/// Parse a [`SocketAddr`] from a `str`.
99///
100/// The following formats are checked:
101///
102/// - If the value can be parsed as a `u16` or starts with `:` it is considered a port, and the
103///   hostname is set to `localhost`.
104/// - If the value contains `:` it is assumed to be the format `<host>:<port>`
105/// - Otherwise it is assumed to be a hostname
106///
107/// An error is returned if the value is empty.
108pub fn parse_socket_address(value: &str) -> eyre::Result<SocketAddr, SocketAddressParsingError> {
109    if value.is_empty() {
110        return Err(SocketAddressParsingError::Empty)
111    }
112
113    if let Some(port) = value.strip_prefix(':').or_else(|| value.strip_prefix("localhost:")) {
114        let port: u16 = port.parse()?;
115        return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))
116    }
117    if let Ok(port) = value.parse() {
118        return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))
119    }
120    value
121        .to_socket_addrs()?
122        .next()
123        .ok_or_else(|| SocketAddressParsingError::Parse(value.to_string()))
124}
125
126/// Wrapper around [`reth_fs_util::read_json_file`] which can be used as a clap value parser.
127pub fn read_json_from_file<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, FsPathError> {
128    reth_fs_util::read_json_file(Path::new(path))
129}
130
131/// Parses an ether value from a string.
132///
133/// The amount in eth like "1.05" will be interpreted in wei (1.05 * 1e18).
134/// Supports both decimal and integer inputs.
135///
136/// # Examples
137/// - "1.05" -> 1.05 ETH = 1.05 * 10^18 wei
138/// - "2" -> 2 ETH = 2 * 10^18 wei
139pub fn parse_ether_value(value: &str) -> eyre::Result<u128> {
140    let eth = value.parse::<f64>()?;
141    if eth.is_sign_negative() {
142        return Err(eyre::eyre!("Ether value cannot be negative"))
143    }
144    let wei = eth * 1e18;
145    Ok(wei as u128)
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use rand::Rng;
152
153    #[test]
154    fn parse_socket_addresses() {
155        for value in ["localhost:9000", ":9000", "9000"] {
156            let socket_addr = parse_socket_address(value)
157                .unwrap_or_else(|_| panic!("could not parse socket address: {value}"));
158
159            assert!(socket_addr.ip().is_loopback());
160            assert_eq!(socket_addr.port(), 9000);
161        }
162    }
163
164    #[test]
165    fn parse_socket_address_random() {
166        let port: u16 = rand::rng().random();
167
168        for value in [format!("localhost:{port}"), format!(":{port}"), port.to_string()] {
169            let socket_addr = parse_socket_address(&value)
170                .unwrap_or_else(|_| panic!("could not parse socket address: {value}"));
171
172            assert!(socket_addr.ip().is_loopback());
173            assert_eq!(socket_addr.port(), port);
174        }
175    }
176
177    #[test]
178    fn parse_ms_or_seconds() {
179        let ms = parse_duration_from_secs_or_ms("5ms").unwrap();
180        assert_eq!(ms, Duration::from_millis(5));
181
182        let seconds = parse_duration_from_secs_or_ms("5").unwrap();
183        assert_eq!(seconds, Duration::from_secs(5));
184
185        let seconds = parse_duration_from_secs_or_ms("5s").unwrap();
186        assert_eq!(seconds, Duration::from_secs(5));
187
188        assert!(parse_duration_from_secs_or_ms("5ns").is_err());
189    }
190
191    #[test]
192    fn parse_ether_values() {
193        // Test basic decimal value
194        let wei = parse_ether_value("1.05").unwrap();
195        assert_eq!(wei, 1_050_000_000_000_000_000u128);
196
197        // Test integer value
198        let wei = parse_ether_value("2").unwrap();
199        assert_eq!(wei, 2_000_000_000_000_000_000u128);
200
201        // Test zero
202        let wei = parse_ether_value("0").unwrap();
203        assert_eq!(wei, 0);
204
205        // Test negative value fails
206        assert!(parse_ether_value("-1").is_err());
207
208        // Test invalid input fails
209        assert!(parse_ether_value("abc").is_err());
210    }
211
212    #[test]
213    fn parse_human_durations() {
214        for (value, expected) in [
215            ("0", Duration::ZERO),
216            ("0s", Duration::ZERO),
217            ("500ms", Duration::from_millis(500)),
218            ("1.5s", Duration::from_millis(1500)),
219            ("30sec", Duration::from_secs(30)),
220            ("5min", Duration::from_secs(300)),
221            ("1h 30m", Duration::from_secs(5400)),
222            ("1h30m", Duration::from_secs(5400)),
223            ("12hours", Duration::from_secs(12 * 3600)),
224            ("2d", Duration::from_secs(2 * 86400)),
225            ("1d 2h", Duration::from_secs(86400 + 7200)),
226            ("1week", Duration::from_secs(7 * 86400)),
227            ("100us", Duration::from_micros(100)),
228        ] {
229            assert_eq!(parse_duration(value).unwrap(), expected, "{value}");
230        }
231    }
232
233    #[test]
234    fn parse_duration_rejects_invalid() {
235        for value in ["", "3600", "1month", "1y", "-1s"] {
236            assert!(parse_duration(value).is_err(), "{value}");
237        }
238    }
239
240    #[test]
241    fn format_human_durations() {
242        for (duration, expected) in [
243            (Duration::ZERO, "0s"),
244            (Duration::from_millis(500), "500ms"),
245            (Duration::from_millis(1500), "1s 500ms"),
246            (Duration::from_secs(90), "1m 30s"),
247            (Duration::from_secs(3600), "1h"),
248            (Duration::from_secs(7 * 86400 + 5), "7d 5s"),
249            (Duration::new(3725, 1_000_500), "1h 2m 5s 1ms 500ns"),
250        ] {
251            assert_eq!(format_duration(duration), expected);
252            assert_eq!(parse_duration(expected).unwrap(), duration);
253        }
254        assert_eq!(format_duration(Duration::from_secs(u64::MAX)), "5124095576030431h 15s");
255    }
256}