1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//! # Global configuration of tari base layer system

use super::ConfigurationError;
use config::{Config, ConfigError, Environment};
use multiaddr::Multiaddr;
use std::{
    convert::TryInto,
    fmt::{Display, Formatter, Result as FormatResult},
    net::SocketAddr,
    num::{NonZeroU16, TryFromIntError},
    path::PathBuf,
    str::FromStr,
    time::Duration,
};
use tari_storage::lmdb_store::LMDBConfig;

const DB_INIT_DEFAULT_MB: usize = 1000;
const DB_GROW_DEFAULT_MB: usize = 500;
const DB_RESIZE_DEFAULT_MB: usize = 100;

const DB_INIT_MIN_MB: i64 = 100;
const DB_GROW_MIN_MB: i64 = 20;
const DB_RESIZE_MIN_MB: i64 = 10;

//-------------------------------------        Main Configuration Struct      --------------------------------------//

#[derive(Debug, Clone)]
pub struct GlobalConfig {
    pub network: Network,
    pub comms_transport: CommsTransport,
    pub listnener_liveness_max_sessions: usize,
    pub listener_liveness_allowlist_cidrs: Vec<String>,
    pub data_dir: PathBuf,
    pub db_type: DatabaseType,
    pub db_config: LMDBConfig,
    pub orphan_storage_capacity: usize,
    pub pruning_horizon: u64,
    pub pruned_mode_cleanup_interval: u64,
    pub core_threads: usize,
    pub blocking_threads: usize,
    pub identity_file: PathBuf,
    pub public_address: Multiaddr,
    pub grpc_enabled: bool,
    pub grpc_address: SocketAddr,
    pub grpc_wallet_address: SocketAddr,
    pub peer_seeds: Vec<String>,
    pub peer_db_path: PathBuf,
    pub block_sync_strategy: String,
    pub enable_mining: bool,
    pub num_mining_threads: usize,
    pub tor_identity_file: PathBuf,
    pub wallet_db_file: PathBuf,
    pub wallet_identity_file: PathBuf,
    pub wallet_tor_identity_file: PathBuf,
    pub wallet_peer_db_path: PathBuf,
    pub buffer_size_base_node: usize,
    pub buffer_size_base_node_wallet: usize,
    pub buffer_rate_limit_base_node: usize,
    pub buffer_rate_limit_base_node_wallet: usize,
    pub base_node_query_timeout: Duration,
    pub transaction_broadcast_monitoring_timeout: Duration,
    pub transaction_chain_monitoring_timeout: Duration,
    pub transaction_direct_send_timeout: Duration,
    pub transaction_broadcast_send_timeout: Duration,
    pub prevent_fee_gt_amount: bool,
    pub monerod_url: String,
    pub monerod_username: String,
    pub monerod_password: String,
    pub monerod_use_auth: bool,
    pub proxy_host_address: SocketAddr,
}

impl GlobalConfig {
    pub fn convert_from(mut cfg: Config) -> Result<Self, ConfigurationError> {
        let network = cfg
            .get_str("base_node.network")
            .map_err(|e| ConfigurationError::new("base_node.network", &e.to_string()))?
            .parse()?;

        // Add in settings from the environment (with a prefix of TARI_NODE)
        // Eg.. `TARI_NODE_DEBUG=1 ./target/app` would set the `debug` key
        cfg.merge(Environment::with_prefix("tari").separator("__"))
            .map_err(|e| ConfigurationError::new("environment variable", &e.to_string()))?;
        convert_node_config(network, cfg)
    }
}

fn convert_node_config(network: Network, cfg: Config) -> Result<GlobalConfig, ConfigurationError> {
    let net_str = network.to_string().to_lowercase();

    let key = config_string("base_node", &net_str, "data_dir");
    let data_dir: PathBuf = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    let key = config_string("base_node", &net_str, "db_type");
    let db_type = cfg
        .get_str(&key)
        .map(|s| s.to_lowercase())
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    let db_type = match db_type.as_str() {
        "memory" => Ok(DatabaseType::Memory),
        "lmdb" => Ok(DatabaseType::LMDB(data_dir.join("db"))),
        invalid_opt => Err(ConfigurationError::new(
            "base_node.db_type",
            &format!("Invalid option: {}", invalid_opt),
        )),
    }?;

    let key = config_string("base_node", &net_str, "db_init_size_mb");
    let init_size_mb = match cfg.get_int(&key) {
        Ok(mb) if mb < DB_INIT_MIN_MB => {
            return Err(ConfigurationError::new(
                &key,
                &format!("DB initial size must be at least {} MB.", DB_INIT_MIN_MB),
            ))
        },
        Ok(mb) => mb as usize,
        Err(e) => match e {
            ConfigError::NotFound(_) => DB_INIT_DEFAULT_MB, // default
            other => return Err(ConfigurationError::new(&key, &other.to_string())),
        },
    };

    let key = config_string("base_node", &net_str, "db_grow_size_mb");
    let grow_size_mb = match cfg.get_int(&key) {
        Ok(mb) if mb < DB_GROW_MIN_MB => {
            return Err(ConfigurationError::new(
                &key,
                &format!("DB grow size must be at least {} MB.", DB_GROW_MIN_MB),
            ))
        },
        Ok(mb) => mb as usize,
        Err(e) => match e {
            ConfigError::NotFound(_) => DB_GROW_DEFAULT_MB, // default
            other => return Err(ConfigurationError::new(&key, &other.to_string())),
        },
    };

    let key = config_string("base_node", &net_str, "db_resize_threshold_mb");
    let resize_threshold_mb = match cfg.get_int(&key) {
        Ok(mb) if mb < DB_RESIZE_MIN_MB => {
            return Err(ConfigurationError::new(
                &key,
                &format!("DB resize threshold must be at least {} MB.", DB_RESIZE_MIN_MB),
            ))
        },
        Ok(mb) if mb as usize >= grow_size_mb => {
            return Err(ConfigurationError::new(
                &key,
                "DB resize threshold must be less than grow size.",
            ))
        },
        Ok(mb) if mb as usize >= init_size_mb => {
            return Err(ConfigurationError::new(
                &key,
                "DB resize threshold must be less than init size.",
            ))
        },
        Ok(mb) => mb as usize,
        Err(e) => match e {
            ConfigError::NotFound(_) => DB_RESIZE_DEFAULT_MB, // default
            other => return Err(ConfigurationError::new(&key, &other.to_string())),
        },
    };

    let db_config = LMDBConfig::new_from_mb(init_size_mb, grow_size_mb, resize_threshold_mb);

    let key = config_string("base_node", &net_str, "orphan_storage_capacity");
    let orphan_storage_capacity = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = config_string("base_node", &net_str, "pruning_horizon");
    let pruning_horizon = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64;

    let key = config_string("base_node", &net_str, "pruned_mode_cleanup_interval");
    let pruned_mode_cleanup_interval = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64;

    // Thread counts
    let key = config_string("base_node", &net_str, "core_threads");
    let core_threads = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = config_string("base_node", &net_str, "blocking_threads");
    let blocking_threads = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    // NodeIdentity path
    let key = config_string("base_node", &net_str, "identity_file");
    let identity_file = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    // Wallet identity path
    let key = config_string("base_node", &net_str, "wallet_identity_file");
    let wallet_identity_file = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    let key = config_string("base_node", &net_str, "wallet_tor_identity_file");
    let wallet_tor_identity_file = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    // Tor private key persistence
    let key = config_string("base_node", &net_str, "tor_identity_file");
    let tor_identity_file = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    // Transport
    let comms_transport = network_transport_config(&cfg, &net_str)?;

    // Public address
    let key = config_string("base_node", &net_str, "public_address");
    let public_address = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        .and_then(|addr| {
            addr.parse::<Multiaddr>()
                .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        })?;

    // GPRC enabled
    let key = config_string("base_node", &net_str, "grpc_enabled");
    let grpc_enabled = cfg
        .get_bool(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as bool;

    let key = config_string("base_node", &net_str, "grpc_address");
    let grpc_address = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        .and_then(|addr| {
            addr.parse::<SocketAddr>()
                .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        })?;

    let key = config_string("base_node", &net_str, "grpc_wallet_address");
    let grpc_wallet_address = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        .and_then(|addr| {
            addr.parse::<SocketAddr>()
                .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        })?;

    // Peer seeds
    let key = config_string("base_node", &net_str, "peer_seeds");
    let peer_seeds = cfg
        .get_array(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;
    let peer_seeds = peer_seeds.into_iter().map(|v| v.into_str().unwrap()).collect();

    // Peer DB path
    let peer_db_path = data_dir.join("peer_db");
    let wallet_peer_db_path = data_dir.join("wallet_peer_db");

    let key = config_string("base_node", &net_str, "block_sync_strategy");
    let block_sync_strategy = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    // set base node mining
    let key = config_string("base_node", &net_str, "enable_mining");
    let enable_mining = cfg
        .get_bool(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as bool;

    let key = config_string("base_node", &net_str, "num_mining_threads");
    let num_mining_threads = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    // set wallet_file
    let key = "wallet.wallet_file".to_string();
    let wallet_db_file = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?
        .into();

    let key = "wallet.base_node_query_timeout";
    let base_node_query_timeout = Duration::from_secs(
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64,
    );

    let key = "wallet.transaction_broadcast_monitoring_timeout";
    let transaction_broadcast_monitoring_timeout = Duration::from_secs(
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64,
    );

    let key = "wallet.transaction_chain_monitoring_timeout";
    let transaction_chain_monitoring_timeout = Duration::from_secs(
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64,
    );

    let key = "wallet.transaction_direct_send_timeout";
    let transaction_direct_send_timeout = Duration::from_secs(
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64,
    );

    let key = "wallet.transaction_broadcast_send_timeout";
    let transaction_broadcast_send_timeout = Duration::from_secs(
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as u64,
    );

    let key = "wallet.prevent_fee_gt_amount";
    let prevent_fee_gt_amount = cfg
        .get_bool(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as bool;

    let key = "common.liveness_max_sessions";
    let liveness_max_sessions = cfg
        .get_int(key)
        .map_err(|e| ConfigurationError::new(key, &e.to_string()))?
        .try_into()
        .map_err(|e: TryFromIntError| ConfigurationError::new(&key, &e.to_string()))?;

    let key = "common.liveness_allowlist_cidrs";
    let liveness_allowlist_cidrs = cfg
        .get_array(key)
        .map(|values| values.iter().map(ToString::to_string).collect())
        .unwrap_or_else(|_| vec!["127.0.0.1/32".to_string()]);

    let key = "common.buffer_size_base_node";
    let buffer_size_base_node = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = "common.buffer_size_base_node_wallet";
    let buffer_size_base_node_wallet = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = "common.buffer_rate_limit_base_node";
    let buffer_rate_limit_base_node = cfg
        .get_int(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = "common.buffer_rate_limit_base_node_wallet";
    let buffer_rate_limit_base_node_wallet =
        cfg.get_int(&key)
            .map_err(|e| ConfigurationError::new(&key, &e.to_string()))? as usize;

    let key = config_string("merge_mining_proxy", &net_str, "monerod_url");
    let monerod_url = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    let key = config_string("merge_mining_proxy", &net_str, "monerod_use_auth");
    let monerod_use_auth = cfg
        .get_bool(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    let key = config_string("merge_mining_proxy", &net_str, "monerod_username");
    let monerod_username = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    let key = config_string("merge_mining_proxy", &net_str, "monerod_password");
    let monerod_password = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))?;

    let key = config_string("merge_mining_proxy", &net_str, "proxy_host_address");
    let proxy_host_address = cfg
        .get_str(&key)
        .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        .and_then(|addr| {
            addr.parse::<SocketAddr>()
                .map_err(|e| ConfigurationError::new(&key, &e.to_string()))
        })?;

    Ok(GlobalConfig {
        network,
        comms_transport,
        listnener_liveness_max_sessions: liveness_max_sessions,
        listener_liveness_allowlist_cidrs: liveness_allowlist_cidrs,
        data_dir,
        db_type,
        db_config,
        orphan_storage_capacity,
        pruning_horizon,
        pruned_mode_cleanup_interval,
        core_threads,
        blocking_threads,
        identity_file,
        public_address,
        grpc_enabled,
        grpc_address,
        grpc_wallet_address,
        peer_seeds,
        peer_db_path,
        block_sync_strategy,
        enable_mining,
        num_mining_threads,
        tor_identity_file,
        wallet_identity_file,
        wallet_db_file,
        wallet_tor_identity_file,
        wallet_peer_db_path,
        buffer_size_base_node,
        buffer_size_base_node_wallet,
        buffer_rate_limit_base_node,
        buffer_rate_limit_base_node_wallet,
        base_node_query_timeout,
        transaction_broadcast_monitoring_timeout,
        transaction_chain_monitoring_timeout,
        transaction_direct_send_timeout,
        transaction_broadcast_send_timeout,
        prevent_fee_gt_amount,
        proxy_host_address,
        monerod_url,
        monerod_username,
        monerod_password,
        monerod_use_auth,
    })
}

fn network_transport_config(cfg: &Config, network: &str) -> Result<CommsTransport, ConfigurationError> {
    let get_conf_str = |key| {
        cfg.get_str(key)
            .map_err(|err| ConfigurationError::new(key, &err.to_string()))
    };

    let get_conf_multiaddr = |key| {
        let path_str = get_conf_str(key)?;
        path_str
            .parse::<Multiaddr>()
            .map_err(|err| ConfigurationError::new(key, &err.to_string()))
    };

    let transport_key = config_string("base_node", network, "transport");
    let transport = get_conf_str(&transport_key)?;

    match transport.to_lowercase().as_str() {
        "tcp" => {
            let key = config_string("base_node", network, "tcp_listener_address");
            let listener_address = get_conf_multiaddr(&key)?;
            let key = config_string("base_node", network, "tcp_tor_socks_address");
            let tor_socks_address = get_conf_multiaddr(&key).ok();
            let key = config_string("base_node", network, "tcp_tor_socks_auth");
            let tor_socks_auth = get_conf_str(&key).ok().and_then(|auth_str| auth_str.parse().ok());

            Ok(CommsTransport::Tcp {
                listener_address,
                tor_socks_auth,
                tor_socks_address,
            })
        },
        "tor" => {
            let key = config_string("base_node", network, "tor_control_address");
            let control_server_address = get_conf_multiaddr(&key)?;

            let key = config_string("base_node", network, "tor_control_auth");
            let auth_str = get_conf_str(&key)?;
            let auth = auth_str
                .parse()
                .map_err(|err: String| ConfigurationError::new(&key, &err))?;

            let key = config_string("base_node", network, "tor_forward_address");
            let forward_address = get_conf_multiaddr(&key)?;
            let key = config_string("base_node", network, "tor_onion_port");
            let onion_port = cfg
                .get::<NonZeroU16>(&key)
                .map_err(|err| ConfigurationError::new(&key, &err.to_string()))?;

            let key = config_string("base_node", network, "tor_socks_address_override");
            let socks_address_override = match get_conf_str(&key).ok() {
                Some(addr) => Some(
                    addr.parse::<Multiaddr>()
                        .map_err(|err| ConfigurationError::new(&key, &err.to_string()))?,
                ),
                None => None,
            };

            Ok(CommsTransport::TorHiddenService {
                control_server_address,
                auth,
                socks_address_override,
                forward_address,
                onion_port,
            })
        },
        "socks5" => {
            let key = config_string("base_node", network, "socks5_proxy_address");
            let proxy_address = get_conf_multiaddr(&key)?;

            let key = config_string("base_node", network, "socks5_auth");
            let auth_str = get_conf_str(&key)?;
            let auth = auth_str
                .parse()
                .map_err(|err: String| ConfigurationError::new(&key, &err))?;

            let key = config_string("base_node", network, "socks5_listener_address");
            let listener_address = get_conf_multiaddr(&key)?;

            Ok(CommsTransport::Socks5 {
                proxy_address,
                listener_address,
                auth,
            })
        },
        t => Err(ConfigurationError::new(
            &transport_key,
            &format!("Invalid transport type '{}'", t),
        )),
    }
}

fn config_string(prefix: &str, network: &str, key: &str) -> String {
    format!("{}.{}.{}", prefix, network, key)
}

//---------------------------------------------       Network type        ------------------------------------------//
#[derive(Clone, Debug, PartialEq, Copy)]
pub enum Network {
    MainNet,
    Rincewind,
}

impl FromStr for Network {
    type Err = ConfigurationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.to_lowercase().as_str() {
            "rincewind" => Ok(Self::Rincewind),
            "mainnet" => Ok(Self::MainNet),
            invalid => Err(ConfigurationError::new(
                "network",
                &format!("Invalid network option: {}", invalid),
            )),
        }
    }
}

impl Display for Network {
    fn fmt(&self, f: &mut Formatter) -> FormatResult {
        let msg = match self {
            Self::MainNet => "mainnet",
            Self::Rincewind => "rincewind",
        };
        f.write_str(msg)
    }
}

//---------------------------------------------      Database type        ------------------------------------------//
#[derive(Debug, Clone)]
pub enum DatabaseType {
    LMDB(PathBuf),
    Memory,
}

//---------------------------------------------     Network Transport     ------------------------------------------//
#[derive(Debug, Clone)]
pub enum TorControlAuthentication {
    None,
    Password(String),
}

fn parse_key_value(s: &str, split_chr: char) -> (String, Option<&str>) {
    let mut parts = s.splitn(2, split_chr);
    (
        parts
            .next()
            .expect("splitn always emits at least one part")
            .to_lowercase(),
        parts.next(),
    )
}

impl FromStr for TorControlAuthentication {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (auth_type, maybe_value) = parse_key_value(s, '=');
        match auth_type.as_str() {
            "none" => Ok(TorControlAuthentication::None),
            "password" => {
                let password = maybe_value.ok_or_else(|| {
                    "Invalid format for 'password' tor authentication type. It should be in the format \
                     'password=xxxxxx'."
                        .to_string()
                })?;
                Ok(TorControlAuthentication::Password(password.to_string()))
            },
            s => Err(format!("Invalid tor auth type '{}'", s)),
        }
    }
}

#[derive(Debug, Clone)]
pub enum SocksAuthentication {
    None,
    UsernamePassword(String, String),
}

impl FromStr for SocksAuthentication {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (auth_type, maybe_value) = parse_key_value(s, '=');
        match auth_type.as_str() {
            "none" => Ok(SocksAuthentication::None),
            "username_password" => {
                let (username, password) = maybe_value
                    .and_then(|value| {
                        let (un, pwd) = parse_key_value(value, ':');
                        // If pwd is None, return None
                        pwd.map(|p| (un, p))
                    })
                    .ok_or_else(|| {
                        "Invalid format for 'username-password' socks authentication type. It should be in the format \
                         'username_password=my_username:xxxxxx'."
                            .to_string()
                    })?;
                Ok(SocksAuthentication::UsernamePassword(username, password.to_string()))
            },
            s => Err(format!("Invalid tor auth type '{}'", s)),
        }
    }
}

#[derive(Debug, Clone)]
pub enum CommsTransport {
    /// Use TCP to join the Tari network. This transport can only communicate with TCP/IP addresses, so peers with
    /// e.g. tor onion addresses will not be contactable.
    Tcp {
        listener_address: Multiaddr,
        tor_socks_address: Option<Multiaddr>,
        tor_socks_auth: Option<SocksAuthentication>,
    },
    /// Configures the node to run over a tor hidden service using the Tor proxy. This transport recognises ip/tcp,
    /// onion v2, onion v3 and DNS addresses.
    TorHiddenService {
        /// The address of the control server
        control_server_address: Multiaddr,
        socks_address_override: Option<Multiaddr>,
        /// The address used to receive proxied traffic from the tor proxy to the Tari node. This port must be
        /// available
        forward_address: Multiaddr,
        auth: TorControlAuthentication,
        onion_port: NonZeroU16,
    },
    /// Use a SOCKS5 proxy transport. This transport recognises any addresses supported by the proxy.
    Socks5 {
        proxy_address: Multiaddr,
        auth: SocksAuthentication,
        listener_address: Multiaddr,
    },
}