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
20fn validate_file_path(_s: &str) -> Result<(), ValidationError> {
26 Ok(())
27
28 }
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 #[serde(default)]
90 pub data: String,
91 #[serde(default = "just_true")]
93 #[default = true]
94 pub initialize: bool,
95 #[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#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct UserHoprNetworkConfig {
133 #[default(default_session_idle_timeout())]
135 #[serde(default = "default_session_idle_timeout", with = "humantime_serde")]
136 pub session_idle_timeout: Duration,
137 #[default(default_max_sessions())]
139 #[serde(default = "default_max_sessions")]
140 pub maximum_sessions: usize,
141 #[default(default_session_establish_max_retries())]
143 #[serde(default = "default_session_establish_max_retries")]
144 pub session_establish_max_retries: usize,
145 #[default(default_probe_recheck_threshold())]
147 #[serde(default = "default_probe_recheck_threshold", with = "humantime_serde")]
148 pub probe_recheck_threshold: Duration,
149 #[default(default_probe_interval())]
151 #[serde(default = "default_probe_interval", with = "humantime_serde")]
152 pub probe_interval: Duration,
153 #[serde(default)]
155 pub announce_local_addresses: bool,
156 #[serde(default)]
158 pub prefer_local_addresses: bool,
159 #[default(default_outgoing_ticket_winning_prob())]
161 #[serde(default = "default_outgoing_ticket_winning_prob")]
162 pub outgoing_ticket_winning_prob: Option<f64>,
163 #[serde(default)]
168 pub min_incoming_ticket_price: Option<HoprBalance>,
169}
170
171#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault, Serialize, Deserialize)]
173#[serde(deny_unknown_fields)]
174pub struct UserHoprLibConfig {
175 #[default(just_true())]
177 #[serde(default = "just_true")]
178 pub announce: bool,
179 #[default(default_host())]
181 #[serde(default = "default_host")]
182 pub host: HostConfig,
183 #[serde(default)]
185 pub safe_module: SafeModule,
186 #[serde(default)]
188 pub network: UserHoprNetworkConfig,
189 #[serde(default)]
198 pub ticket_storage_file: Option<String>,
199}
200
201#[inline]
204fn default_host() -> HostConfig {
205 HostConfig {
206 address: HostType::IPv4(hopr_lib::config::DEFAULT_HOST.to_owned()),
207 port: hopr_lib::config::DEFAULT_PORT,
208 }
209}
210
211impl From<UserHoprLibConfig> for HoprLibConfig {
212 fn from(value: UserHoprLibConfig) -> Self {
213 HoprLibConfig {
214 host: value.host,
215 publish: value.announce,
216 safe_module: value.safe_module,
217 ticket_storage_file: value.ticket_storage_file,
218 protocol: HoprProtocolConfig {
219 transport: TransportConfig {
220 announce_local_addresses: value.network.announce_local_addresses,
221 prefer_local_addresses: value.network.prefer_local_addresses,
222 },
223 packet: HoprPacketPipelineConfig {
224 codec: HoprCodecConfig {
225 outgoing_win_prob: value
226 .network
227 .outgoing_ticket_winning_prob
228 .and_then(|v| WinningProbability::try_from_f64(v).ok()),
229 min_incoming_ticket_price: value.network.min_incoming_ticket_price,
230 ..Default::default()
231 },
232 ..Default::default()
233 },
234 probe: ProbeConfig {
235 interval: value.network.probe_interval,
236 recheck_threshold: value.network.probe_recheck_threshold,
237 ..Default::default()
238 },
239 session: SessionGlobalConfig {
240 idle_timeout: value.network.session_idle_timeout,
241 establish_max_retries: value.network.session_establish_max_retries as u32,
242 tag_allocator: TagAllocatorConfig {
243 session: value.network.maximum_sessions as u64,
244 ..Default::default()
245 },
246 ..Default::default()
247 },
248 path_planner: Default::default(),
249 counter_flush_interval: Default::default(),
250 },
251 ..Default::default()
252 }
253 }
254}
255
256impl Validate for UserHoprLibConfig {
257 fn validate(&self) -> Result<(), ValidationErrors> {
258 HoprLibConfig::from(self.clone()).validate()
259 }
260}
261
262#[derive(Debug, Serialize, Deserialize, Validate, Clone, PartialEq, smart_default::SmartDefault)]
270#[serde(deny_unknown_fields)]
271pub struct HoprdConfig {
272 #[validate(nested)]
274 #[serde(default)]
275 pub hopr: UserHoprLibConfig,
276 #[validate(nested)]
278 #[serde(default)]
279 pub identity: Identity,
280 #[validate(nested)]
282 #[serde(default)]
283 pub db: Db,
284 #[validate(nested)]
286 #[serde(default)]
287 pub api: Api,
288 #[validate(nested)]
290 #[serde(default)]
291 pub session_ip_forwarding: SessionIpForwardingConfig,
292 #[validate(url)]
294 pub blokli_url: Option<String>,
295 #[validate(nested)]
300 #[serde(default = "hopr_strategy::hopr_default_strategies")]
301 #[default(hopr_strategy::hopr_default_strategies())]
302 pub strategy: hopr_strategy::StrategyConfig,
303}
304
305impl HoprdConfig {
306 pub fn as_redacted(&self) -> Self {
307 let mut ret = self.clone();
308 match ret.api.auth {
310 Auth::None => {}
311 Auth::Token(_) => ret.api.auth = Auth::Token("<REDACTED>".to_owned()),
312 }
313
314 if ret.identity.private_key.is_some() {
315 ret.identity.private_key = Some("<REDACTED>".to_owned());
316 }
317
318 "<REDACTED>".clone_into(&mut ret.identity.password);
319
320 ret
321 }
322
323 pub fn as_redacted_string(&self) -> crate::errors::Result<String> {
324 let redacted_cfg = self.as_redacted();
325 serde_json::to_string(&redacted_cfg).map_err(|e| crate::errors::HoprdError::SerializationError(e.to_string()))
326 }
327}
328
329fn just_true() -> bool {
330 true
331}
332
333#[cfg(test)]
334mod tests {
335 use std::{
336 io::{Read, Write},
337 str::FromStr,
338 };
339
340 use anyhow::Context;
341 use clap::{Args, Command, FromArgMatches};
342 use hopr_lib::Address;
343 use tempfile::NamedTempFile;
344
345 use super::*;
346
347 pub fn example_cfg() -> anyhow::Result<HoprdConfig> {
348 let safe_module = hopr_lib::config::SafeModule {
349 safe_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
350 module_address: Address::from_str("0x0000000000000000000000000000000000000000")?,
351 };
352
353 let identity = Identity {
354 file: "path/to/identity.file".to_string(),
355 password: "change_me".to_owned(),
356 private_key: None,
357 };
358
359 let host = HostConfig {
360 address: HostType::IPv4("1.2.3.4".into()),
361 port: 9091,
362 };
363
364 Ok(HoprdConfig {
365 hopr: UserHoprLibConfig {
366 host,
367 safe_module,
368 ..Default::default()
369 },
370 db: Db {
371 data: "/app/db".to_owned(),
372 ..Default::default()
373 },
374 identity,
375 ..HoprdConfig::default()
376 })
377 }
378
379 #[test]
380 fn test_config_should_be_serializable_into_string() -> anyhow::Result<()> {
381 let cfg = example_cfg()?;
382
383 let from_yaml: HoprdConfig = serde_saphyr::from_str(include_str!("../example_cfg.yaml"))?;
384 assert_eq!(cfg, from_yaml);
385
386 Ok(())
387 }
388
389 #[test]
390 fn test_config_should_be_deserializable_from_a_string_in_a_file() -> anyhow::Result<()> {
391 let mut config_file = NamedTempFile::new()?;
392 let mut prepared_config_file = config_file.reopen()?;
393
394 let cfg = example_cfg()?;
395 let yaml = serde_saphyr::to_string(&cfg)?;
396 config_file.write_all(yaml.as_bytes())?;
397
398 let mut buf = String::new();
399 prepared_config_file.read_to_string(&mut buf)?;
400 let deserialized_cfg: HoprdConfig = serde_saphyr::from_str(&buf)?;
401
402 assert_eq!(deserialized_cfg, cfg);
403
404 Ok(())
405 }
406
407 #[test]
411 #[ignore]
412 fn test_config_is_extractable_from_the_cli_arguments() -> anyhow::Result<()> {
413 let pwnd = "rpc://pawned!";
414
415 let mut config_file = NamedTempFile::new()?;
416
417 let mut cfg = example_cfg()?;
418 cfg.blokli_url = Some(pwnd.to_owned());
419
420 let yaml = serde_saphyr::to_string(&cfg)?;
421 config_file.write_all(yaml.as_bytes())?;
422 let cfg_file_path = config_file
423 .path()
424 .to_str()
425 .context("file path should have a string representation")?
426 .to_string();
427
428 let cli_args = vec!["hoprd", "--configurationFilePath", cfg_file_path.as_str()];
429
430 let mut cmd = Command::new("hoprd").version("0.0.0");
431 cmd = crate::cli::CliArgs::augment_args(cmd);
432 let derived_matches = cmd.try_get_matches_from(cli_args)?;
433 let args = crate::cli::CliArgs::from_arg_matches(&derived_matches)?;
434
435 let cfg = HoprdConfig::try_from(args)?;
437
438 assert_eq!(cfg.blokli_url, Some(pwnd.to_owned()));
439
440 Ok(())
441 }
442}