hoprd/
config.rs

1use std::{collections::HashSet, net::SocketAddr, time::Duration};
2
3use hopr_lib::{
4    HoprProtocolConfig, SafeModule, WinningProbability,
5    config::{
6        HoprLibConfig, HoprPacketPipelineConfig, HostConfig, HostType, ProbeConfig, SessionGlobalConfig,
7        TransportConfig,
8    },
9    exports::transport::config::HoprCodecConfig,
10};
11use hoprd_api::config::{Api, Auth};
12use proc_macro_regex::regex;
13use serde::{Deserialize, Serialize};
14use serde_with::serde_as;
15use validator::{Validate, ValidationError, ValidationErrors};
16
17pub const DEFAULT_HOST: &str = "0.0.0.0";
18pub const DEFAULT_PORT: u16 = 9091;
19
20// Validate that the path is a valid UTF-8 path.
21//
22// Also used to perform the identity file existence check on the
23// specified path, which is now circumvented but could
24// return in the future workflows of setting up a node.
25fn validate_file_path(_s: &str) -> Result<(), ValidationError> {
26    Ok(())
27
28    // if std::path::Path::new(_s).is_file() {
29    //     Ok(())
30    // } else {
31    //     Err(ValidationError::new(
32    //         "Invalid file path specified, the file does not exist or is not a file",
33    //     ))
34    // }
35}
36
37fn validate_password(s: &str) -> Result<(), ValidationError> {
38    if !s.is_empty() {
39        Ok(())
40    } else {
41        Err(ValidationError::new("No password could be found"))
42    }
43}
44
45regex!(is_private_key "^(0[xX])?[a-fA-F0-9]{128}$");
46
47pub(crate) fn validate_private_key(s: &str) -> Result<(), ValidationError> {
48    if is_private_key(s) {
49        Ok(())
50    } else {
51        Err(ValidationError::new("No valid private key could be found"))
52    }
53}
54
55fn validate_optional_private_key(s: &str) -> Result<(), ValidationError> {
56    validate_private_key(s)
57}
58
59#[derive(Default, Serialize, Deserialize, Validate, Clone, PartialEq)]
60#[serde(deny_unknown_fields)]
61pub struct Identity {
62    #[validate(custom(function = "validate_file_path"))]
63    #[serde(default)]
64    pub file: String,
65    #[validate(custom(function = "validate_password"))]
66    #[serde(default)]
67    pub password: String,
68    #[validate(custom(function = "validate_optional_private_key"))]
69    #[serde(default)]
70    pub private_key: Option<String>,
71}
72
73impl std::fmt::Debug for Identity {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        let obfuscated: String = "<REDACTED>".into();
76
77        f.debug_struct("Identity")
78            .field("file", &self.file)
79            .field("password", &obfuscated)
80            .field("private_key", &obfuscated)
81            .finish()
82    }
83}
84
85#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize, Validate)]
86#[serde(deny_unknown_fields)]
87pub struct Db {
88    /// Path to the directory containing the database
89    #[serde(default)]
90    pub data: String,
91    /// Determines whether the database should be initialized upon startup.
92    #[serde(default = "just_true")]
93    #[default = true]
94    pub initialize: bool,
95    /// Determines whether the database should be forcibly-initialized if it exists upon startup.
96    #[serde(default)]
97    pub force_initialize: bool,
98}
99
100fn default_session_idle_timeout() -> Duration {
101    HoprLibConfig::default().protocol.session.idle_timeout
102}
103
104fn default_max_sessions() -> usize {
105    HoprLibConfig::default().protocol.session.maximum_sessions as usize
106}
107
108fn default_session_establish_max_retries() -> usize {
109    HoprLibConfig::default().protocol.session.establish_max_retries as usize
110}
111
112fn default_probe_recheck_threshold() -> Duration {
113    HoprLibConfig::default().protocol.probe.recheck_threshold
114}
115
116fn default_probe_interval() -> Duration {
117    HoprLibConfig::default().protocol.probe.interval
118}
119
120fn default_outgoing_ticket_winning_prob() -> Option<f64> {
121    HoprLibConfig::default()
122        .protocol
123        .packet
124        .codec
125        .outgoing_win_prob
126        .map(|p| p.as_f64())
127}
128
129/// Subset of various selected HOPR library network-related configuration options.
130#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct UserHoprNetworkConfig {
133    /// How long it takes before HOPR Session is considered idle and is closed automatically
134    #[default(default_session_idle_timeout())]
135    #[serde(default = "default_session_idle_timeout", with = "humantime_serde")]
136    pub session_idle_timeout: Duration,
137    /// Maximum number of outgoing or incoming Sessions allowed by the Session manager
138    #[default(default_max_sessions())]
139    #[serde(default = "default_max_sessions")]
140    pub maximum_sessions: usize,
141    /// How many retries are made to establish an outgoing HOPR Session
142    #[default(default_session_establish_max_retries())]
143    #[serde(default = "default_session_establish_max_retries")]
144    pub session_establish_max_retries: usize,
145    /// The time interval for which to consider peer re-probing in seconds
146    #[default(default_probe_recheck_threshold())]
147    #[serde(default = "default_probe_recheck_threshold", with = "humantime_serde")]
148    pub probe_recheck_threshold: Duration,
149    /// The delay between individual probing rounds for neighbor discovery
150    #[default(default_probe_interval())]
151    #[serde(default = "default_probe_interval", with = "humantime_serde")]
152    pub probe_interval: Duration,
153    /// Should local addresses be announced on-chain?
154    #[serde(default)]
155    pub announce_local_addresses: bool,
156    /// Should local addresses be preferred when dialing a peer?
157    #[serde(default)]
158    pub prefer_local_addresses: bool,
159    /// Outgoing ticket winning probability.
160    #[default(default_outgoing_ticket_winning_prob())]
161    #[serde(default = "default_outgoing_ticket_winning_prob")]
162    pub outgoing_ticket_winning_prob: Option<f64>,
163}
164
165/// Subset of the [`HoprLibConfig`] that is tuned to be user-facing and more user-friendly.
166#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize)]
167#[serde(deny_unknown_fields)]
168pub struct UserHoprLibConfig {
169    /// Determines whether the node should be advertised publicly on-chain.
170    #[default(just_true())]
171    #[serde(default = "just_true")]
172    pub announce: bool,
173    /// Configuration related to host specifics
174    #[default(default_host())]
175    #[serde(default = "default_host")]
176    pub host: HostConfig,
177    /// Safe and Module configuration
178    #[serde(default)]
179    pub safe_module: SafeModule,
180    /// Various HOPR-network and transport-related configuration options.
181    #[serde(default)]
182    pub network: UserHoprNetworkConfig,
183}
184
185// NOTE: this intentionally does not validate (0.0.0.0) to force user to specify
186// their external IP.
187#[inline]
188fn default_host() -> HostConfig {
189    HostConfig {
190        address: HostType::IPv4(hopr_lib::config::DEFAULT_HOST.to_owned()),
191        port: hopr_lib::config::DEFAULT_PORT,
192    }
193}
194
195impl From<UserHoprLibConfig> for HoprLibConfig {
196    fn from(value: UserHoprLibConfig) -> Self {
197        HoprLibConfig {
198            host: value.host,
199            publish: value.announce,
200            safe_module: value.safe_module,
201            protocol: HoprProtocolConfig {
202                transport: TransportConfig {
203                    announce_local_addresses: value.network.announce_local_addresses,
204                    prefer_local_addresses: value.network.prefer_local_addresses,
205                },
206                packet: HoprPacketPipelineConfig {
207                    codec: HoprCodecConfig {
208                        outgoing_win_prob: value
209                            .network
210                            .outgoing_ticket_winning_prob
211                            .and_then(|v| WinningProbability::try_from_f64(v).ok()),
212                        ..Default::default()
213                    },
214                    ..Default::default()
215                },
216                probe: ProbeConfig {
217                    interval: value.network.probe_interval,
218                    recheck_threshold: value.network.probe_recheck_threshold,
219                    ..Default::default()
220                },
221                session: SessionGlobalConfig {
222                    idle_timeout: value.network.session_idle_timeout,
223                    maximum_sessions: value.network.maximum_sessions as u32,
224                    establish_max_retries: value.network.session_establish_max_retries as u32,
225                    ..Default::default()
226                },
227            },
228        }
229    }
230}
231
232impl Validate for UserHoprLibConfig {
233    fn validate(&self) -> Result<(), ValidationErrors> {
234        HoprLibConfig::from(self.clone()).validate()
235    }
236}
237
238/// The main configuration object of the entire node.
239///
240/// The configuration is composed of individual configurations of corresponding
241/// component configuration objects.
242///
243/// An always up-to-date config YAML example can be found in [example_cfg.yaml](https://github.com/hoprnet/hoprnet/tree/master/hoprd/hoprd/example_cfg.yaml)
244/// which is always in the root of this crate.
245#[derive(Debug, Serialize, Deserialize, Validate, Clone, PartialEq, smart_default::SmartDefault)]
246#[serde(deny_unknown_fields)]
247pub struct HoprdConfig {
248    /// Configuration related to hopr-lib functionality
249    #[validate(nested)]
250    #[serde(default)]
251    pub hopr: UserHoprLibConfig,
252    /// Configuration regarding the identity of the node
253    #[validate(nested)]
254    #[serde(default)]
255    pub identity: Identity,
256    /// Configuration of the underlying database engine
257    #[validate(nested)]
258    #[serde(default)]
259    pub db: Db,
260    /// Configuration relevant for the API of the node
261    #[validate(nested)]
262    #[serde(default)]
263    pub api: Api,
264    /// Configuration of the Session entry/exit node IP protocol forwarding.
265    #[validate(nested)]
266    #[serde(default)]
267    pub session_ip_forwarding: SessionIpForwardingConfig,
268    /// Blokli provider URL to connect to.
269    #[validate(url)]
270    pub blokli_url: Option<String>,
271    /// Configuration of underlying node behavior in the form strategies
272    ///
273    /// Strategies represent automatically executable behavior performed by
274    /// the node given pre-configured triggers.
275    #[validate(nested)]
276    #[serde(default = "hopr_strategy::hopr_default_strategies")]
277    #[default(hopr_strategy::hopr_default_strategies())]
278    pub strategy: hopr_strategy::StrategyConfig,
279}
280
281impl HoprdConfig {
282    pub fn as_redacted(&self) -> Self {
283        let mut ret = self.clone();
284        // redacting sensitive information
285        match ret.api.auth {
286            Auth::None => {}
287            Auth::Token(_) => ret.api.auth = Auth::Token("<REDACTED>".to_owned()),
288        }
289
290        if ret.identity.private_key.is_some() {
291            ret.identity.private_key = Some("<REDACTED>".to_owned());
292        }
293
294        "<REDACTED>".clone_into(&mut ret.identity.password);
295
296        ret
297    }
298
299    pub fn as_redacted_string(&self) -> crate::errors::Result<String> {
300        let redacted_cfg = self.as_redacted();
301        serde_json::to_string(&redacted_cfg).map_err(|e| crate::errors::HoprdError::SerializationError(e.to_string()))
302    }
303}
304
305fn default_target_retry_delay() -> Duration {
306    Duration::from_secs(2)
307}
308
309fn default_entry_listen_host() -> SocketAddr {
310    "127.0.0.1:0".parse().unwrap()
311}
312
313fn default_max_tcp_target_retries() -> u32 {
314    10
315}
316
317fn just_true() -> bool {
318    true
319}
320
321/// Configuration of the Exit node (see [`HoprServerIpForwardingReactor`](crate::exit::HoprServerIpForwardingReactor))
322/// and the Entry node.
323#[serde_as]
324#[derive(
325    Clone, Debug, Eq, PartialEq, smart_default::SmartDefault, serde::Deserialize, serde::Serialize, validator::Validate,
326)]
327pub struct SessionIpForwardingConfig {
328    /// Controls whether allowlisting should be done via `target_allow_list`.
329    /// If set to `false`, the node will act as an Exit node for any target.
330    ///
331    /// Defaults to `true`.
332    #[serde(default = "just_true")]
333    #[default(true)]
334    pub use_target_allow_list: bool,
335
336    /// Enforces only the given target addresses (after DNS resolution).
337    ///
338    /// This is used only if `use_target_allow_list` is set to `true`.
339    /// If left empty (and `use_target_allow_list` is `true`), the node will not act as an Exit node.
340    ///
341    /// Defaults to empty.
342    #[serde(default)]
343    #[serde_as(as = "HashSet<serde_with::DisplayFromStr>")]
344    pub target_allow_list: HashSet<SocketAddr>,
345
346    /// Delay between retries in seconds to reach a TCP target.
347    ///
348    /// Defaults to 2 seconds.
349    #[serde(default = "default_target_retry_delay")]
350    #[default(default_target_retry_delay())]
351    #[serde_as(as = "serde_with::DurationSeconds<u64>")]
352    pub tcp_target_retry_delay: Duration,
353
354    /// Maximum number of retries to reach a TCP target before giving up.
355    ///
356    /// Default is 10.
357    #[serde(default = "default_max_tcp_target_retries")]
358    #[default(default_max_tcp_target_retries())]
359    #[validate(range(min = 1))]
360    pub max_tcp_target_retries: u32,
361
362    /// Specifies the default `listen_host` for Session listening sockets
363    /// at an Entry node.
364    #[serde(default = "default_entry_listen_host")]
365    #[default(default_entry_listen_host())]
366    #[serde_as(as = "serde_with::DisplayFromStr")]
367    pub default_entry_listen_host: SocketAddr,
368}
369
370#[cfg(test)]
371mod tests {
372    use std::{
373        io::{Read, Write},
374        str::FromStr,
375    };
376
377    use anyhow::Context;
378    use clap::{Args, Command, FromArgMatches};
379    use hopr_lib::Address;
380    use tempfile::NamedTempFile;
381
382    use super::*;
383
384    pub fn example_cfg() -> anyhow::Result<HoprdConfig> {
385        let safe_module = hopr_lib::config::SafeModule {
386            safe_transaction_service_provider: "https:://provider.com/".to_owned(),
387            safe_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
388            module_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
389        };
390
391        let identity = Identity {
392            file: "path/to/identity.file".to_string(),
393            password: "change_me".to_owned(),
394            private_key: None,
395        };
396
397        let host = HostConfig {
398            address: HostType::IPv4("1.2.3.4".into()),
399            port: 9091,
400        };
401
402        Ok(HoprdConfig {
403            hopr: UserHoprLibConfig {
404                host,
405                safe_module,
406                ..Default::default()
407            },
408            db: Db {
409                data: "/app/db".to_owned(),
410                ..Default::default()
411            },
412            identity,
413            ..HoprdConfig::default()
414        })
415    }
416
417    #[test]
418    fn test_config_should_be_serializable_into_string() -> anyhow::Result<()> {
419        let cfg = example_cfg()?;
420
421        let from_yaml: HoprdConfig = serde_yaml::from_str(include_str!("../example_cfg.yaml"))?;
422        assert_eq!(cfg, from_yaml);
423
424        Ok(())
425    }
426
427    #[test]
428    fn test_config_should_be_deserializable_from_a_string_in_a_file() -> anyhow::Result<()> {
429        let mut config_file = NamedTempFile::new()?;
430        let mut prepared_config_file = config_file.reopen()?;
431
432        let cfg = example_cfg()?;
433        let yaml = serde_yaml::to_string(&cfg)?;
434        config_file.write_all(yaml.as_bytes())?;
435
436        let mut buf = String::new();
437        prepared_config_file.read_to_string(&mut buf)?;
438        let deserialized_cfg: HoprdConfig = serde_yaml::from_str(&buf)?;
439
440        assert_eq!(deserialized_cfg, cfg);
441
442        Ok(())
443    }
444
445    /// TODO: This test attempts to deserialize the data structure incorrectly in the native build
446    /// (`confirmations`` are an extra field), as well as misses the native implementation for the
447    /// version satisfies check
448    #[test]
449    #[ignore]
450    fn test_config_is_extractable_from_the_cli_arguments() -> anyhow::Result<()> {
451        let pwnd = "rpc://pawned!";
452
453        let mut config_file = NamedTempFile::new()?;
454
455        let mut cfg = example_cfg()?;
456        cfg.blokli_url = Some(pwnd.to_owned());
457
458        let yaml = serde_yaml::to_string(&cfg)?;
459        config_file.write_all(yaml.as_bytes())?;
460        let cfg_file_path = config_file
461            .path()
462            .to_str()
463            .context("file path should have a string representation")?
464            .to_string();
465
466        let cli_args = vec!["hoprd", "--configurationFilePath", cfg_file_path.as_str()];
467
468        let mut cmd = Command::new("hoprd").version("0.0.0");
469        cmd = crate::cli::CliArgs::augment_args(cmd);
470        let derived_matches = cmd.try_get_matches_from(cli_args)?;
471        let args = crate::cli::CliArgs::from_arg_matches(&derived_matches)?;
472
473        // skipping validation
474        let cfg = HoprdConfig::try_from(args)?;
475
476        assert_eq!(cfg.blokli_url, Some(pwnd.to_owned()));
477
478        Ok(())
479    }
480}