Skip to main content

hoprd/
config.rs

1use std::time::Duration;
2
3use hopr_builder::config::SessionIpForwardingConfig;
4use hopr_lib::{
5    HoprBalance, HoprProtocolConfig, SafeModule, TagAllocatorConfig, WinningProbability,
6    config::{
7        HoprLibConfig, HoprPacketPipelineConfig, HostConfig, HostType, ProbeConfig, SessionGlobalConfig,
8        TransportConfig,
9    },
10    exports::transport::config::HoprCodecConfig,
11};
12use hoprd_api::config::{Api, Auth};
13use proc_macro_regex::regex;
14use serde::{Deserialize, Serialize};
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.tag_allocator.session 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    /// Minimum incoming ticket price.
164    ///
165    /// The value cannot be lower than the minimum network ticket price multiplied by the node's path position,
166    /// and will default to that value whenever it is lower.
167    #[serde(default)]
168    pub min_incoming_ticket_price: Option<HoprBalance>,
169}
170
171/// Subset of the [`HoprLibConfig`] that is tuned to be user-facing and more user-friendly.
172#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize)]
173#[serde(deny_unknown_fields)]
174pub struct UserHoprLibConfig {
175    /// Determines whether the node should be advertised publicly on-chain.
176    #[default(just_true())]
177    #[serde(default = "just_true")]
178    pub announce: bool,
179    /// Configuration related to host specifics
180    #[default(default_host())]
181    #[serde(default = "default_host")]
182    pub host: HostConfig,
183    /// Safe and Module configuration
184    #[serde(default)]
185    pub safe_module: SafeModule,
186    /// Various HOPR-network and transport-related configuration options.
187    #[serde(default)]
188    pub network: UserHoprNetworkConfig,
189}
190
191// NOTE: this intentionally does not validate (0.0.0.0) to force user to specify
192// their external IP.
193#[inline]
194fn default_host() -> HostConfig {
195    HostConfig {
196        address: HostType::IPv4(hopr_lib::config::DEFAULT_HOST.to_owned()),
197        port: hopr_lib::config::DEFAULT_PORT,
198    }
199}
200
201impl From<UserHoprLibConfig> for HoprLibConfig {
202    fn from(value: UserHoprLibConfig) -> Self {
203        HoprLibConfig {
204            host: value.host,
205            publish: value.announce,
206            safe_module: value.safe_module,
207            protocol: HoprProtocolConfig {
208                transport: TransportConfig {
209                    announce_local_addresses: value.network.announce_local_addresses,
210                    prefer_local_addresses: value.network.prefer_local_addresses,
211                },
212                packet: HoprPacketPipelineConfig {
213                    codec: HoprCodecConfig {
214                        outgoing_win_prob: value
215                            .network
216                            .outgoing_ticket_winning_prob
217                            .and_then(|v| WinningProbability::try_from_f64(v).ok()),
218                        min_incoming_ticket_price: value.network.min_incoming_ticket_price,
219                        ..Default::default()
220                    },
221                    ..Default::default()
222                },
223                probe: ProbeConfig {
224                    interval: value.network.probe_interval,
225                    recheck_threshold: value.network.probe_recheck_threshold,
226                    ..Default::default()
227                },
228                session: SessionGlobalConfig {
229                    idle_timeout: value.network.session_idle_timeout,
230                    establish_max_retries: value.network.session_establish_max_retries as u32,
231                    tag_allocator: TagAllocatorConfig {
232                        session: value.network.maximum_sessions as u64,
233                        ..Default::default()
234                    },
235                    ..Default::default()
236                },
237                path_planner: Default::default(),
238                counter_flush_interval: Default::default(),
239            },
240        }
241    }
242}
243
244impl Validate for UserHoprLibConfig {
245    fn validate(&self) -> Result<(), ValidationErrors> {
246        HoprLibConfig::from(self.clone()).validate()
247    }
248}
249
250/// The main configuration object of the entire node.
251///
252/// The configuration is composed of individual configurations of corresponding
253/// component configuration objects.
254///
255/// 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)
256/// which is always in the root of this crate.
257#[derive(Debug, Serialize, Deserialize, Validate, Clone, PartialEq, smart_default::SmartDefault)]
258#[serde(deny_unknown_fields)]
259pub struct HoprdConfig {
260    /// Configuration related to hopr-lib functionality
261    #[validate(nested)]
262    #[serde(default)]
263    pub hopr: UserHoprLibConfig,
264    /// Configuration regarding the identity of the node
265    #[validate(nested)]
266    #[serde(default)]
267    pub identity: Identity,
268    /// Configuration of the underlying database engine
269    #[validate(nested)]
270    #[serde(default)]
271    pub db: Db,
272    /// Configuration relevant for the API of the node
273    #[validate(nested)]
274    #[serde(default)]
275    pub api: Api,
276    /// Configuration of the Session entry/exit node IP protocol forwarding.
277    #[validate(nested)]
278    #[serde(default)]
279    pub session_ip_forwarding: SessionIpForwardingConfig,
280    /// Blokli provider URL to connect to.
281    #[validate(url)]
282    pub blokli_url: Option<String>,
283    /// Configuration of underlying node behavior in the form strategies
284    ///
285    /// Strategies represent automatically executable behavior performed by
286    /// the node given pre-configured triggers.
287    #[validate(nested)]
288    #[serde(default = "hopr_strategy::hopr_default_strategies")]
289    #[default(hopr_strategy::hopr_default_strategies())]
290    pub strategy: hopr_strategy::StrategyConfig,
291}
292
293impl HoprdConfig {
294    pub fn as_redacted(&self) -> Self {
295        let mut ret = self.clone();
296        // redacting sensitive information
297        match ret.api.auth {
298            Auth::None => {}
299            Auth::Token(_) => ret.api.auth = Auth::Token("<REDACTED>".to_owned()),
300        }
301
302        if ret.identity.private_key.is_some() {
303            ret.identity.private_key = Some("<REDACTED>".to_owned());
304        }
305
306        "<REDACTED>".clone_into(&mut ret.identity.password);
307
308        ret
309    }
310
311    pub fn as_redacted_string(&self) -> crate::errors::Result<String> {
312        let redacted_cfg = self.as_redacted();
313        serde_json::to_string(&redacted_cfg).map_err(|e| crate::errors::HoprdError::SerializationError(e.to_string()))
314    }
315}
316
317fn just_true() -> bool {
318    true
319}
320
321#[cfg(test)]
322mod tests {
323    use std::{
324        io::{Read, Write},
325        str::FromStr,
326    };
327
328    use anyhow::Context;
329    use clap::{Args, Command, FromArgMatches};
330    use hopr_lib::Address;
331    use tempfile::NamedTempFile;
332
333    use super::*;
334
335    pub fn example_cfg() -> anyhow::Result<HoprdConfig> {
336        let safe_module = hopr_lib::config::SafeModule {
337            safe_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
338            module_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
339        };
340
341        let identity = Identity {
342            file: "path/to/identity.file".to_string(),
343            password: "change_me".to_owned(),
344            private_key: None,
345        };
346
347        let host = HostConfig {
348            address: HostType::IPv4("1.2.3.4".into()),
349            port: 9091,
350        };
351
352        Ok(HoprdConfig {
353            hopr: UserHoprLibConfig {
354                host,
355                safe_module,
356                ..Default::default()
357            },
358            db: Db {
359                data: "/app/db".to_owned(),
360                ..Default::default()
361            },
362            identity,
363            ..HoprdConfig::default()
364        })
365    }
366
367    #[test]
368    fn test_config_should_be_serializable_into_string() -> anyhow::Result<()> {
369        let cfg = example_cfg()?;
370
371        let from_yaml: HoprdConfig = serde_saphyr::from_str(include_str!("../example_cfg.yaml"))?;
372        assert_eq!(cfg, from_yaml);
373
374        Ok(())
375    }
376
377    #[test]
378    fn test_config_should_be_deserializable_from_a_string_in_a_file() -> anyhow::Result<()> {
379        let mut config_file = NamedTempFile::new()?;
380        let mut prepared_config_file = config_file.reopen()?;
381
382        let cfg = example_cfg()?;
383        let yaml = serde_saphyr::to_string(&cfg)?;
384        config_file.write_all(yaml.as_bytes())?;
385
386        let mut buf = String::new();
387        prepared_config_file.read_to_string(&mut buf)?;
388        let deserialized_cfg: HoprdConfig = serde_saphyr::from_str(&buf)?;
389
390        assert_eq!(deserialized_cfg, cfg);
391
392        Ok(())
393    }
394
395    /// TODO: This test attempts to deserialize the data structure incorrectly in the native build
396    /// (`confirmations`` are an extra field), as well as misses the native implementation for the
397    /// version satisfies check
398    #[test]
399    #[ignore]
400    fn test_config_is_extractable_from_the_cli_arguments() -> anyhow::Result<()> {
401        let pwnd = "rpc://pawned!";
402
403        let mut config_file = NamedTempFile::new()?;
404
405        let mut cfg = example_cfg()?;
406        cfg.blokli_url = Some(pwnd.to_owned());
407
408        let yaml = serde_saphyr::to_string(&cfg)?;
409        config_file.write_all(yaml.as_bytes())?;
410        let cfg_file_path = config_file
411            .path()
412            .to_str()
413            .context("file path should have a string representation")?
414            .to_string();
415
416        let cli_args = vec!["hoprd", "--configurationFilePath", cfg_file_path.as_str()];
417
418        let mut cmd = Command::new("hoprd").version("0.0.0");
419        cmd = crate::cli::CliArgs::augment_args(cmd);
420        let derived_matches = cmd.try_get_matches_from(cli_args)?;
421        let args = crate::cli::CliArgs::from_arg_matches(&derived_matches)?;
422
423        // skipping validation
424        let cfg = HoprdConfig::try_from(args)?;
425
426        assert_eq!(cfg.blokli_url, Some(pwnd.to_owned()));
427
428        Ok(())
429    }
430}