zingolib 0.0.1

Zingo backend library.
Documentation
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! ZingConfig
//! TODO: Add Crate Description Here!

#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::{
    io::{self, Error, ErrorKind},
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
};

use log::{LevelFilter, info};
use log4rs::{
    Config,
    append::rolling_file::{
        RollingFileAppender,
        policy::compound::{
            CompoundPolicy, roll::fixed_window::FixedWindowRoller, trigger::size::SizeTrigger,
        },
    },
    config::{Appender, Root},
    encode::pattern::PatternEncoder,
    filter::threshold::ThresholdFilter,
};
use zcash_primitives::consensus::{
    BlockHeight, MAIN_NETWORK, NetworkType, NetworkUpgrade, Parameters, TEST_NETWORK,
};

use crate::wallet::WalletSettings;

/// TODO: Add Doc Comment Here!
pub const DEVELOPER_DONATION_ADDRESS: &str = "u1w47nzy4z5g9zvm4h2s4ztpl8vrdmlclqz5sz02742zs5j3tz232u4safvv9kplg7g06wpk5fx0k0rx3r9gg4qk6nkg4c0ey57l0dyxtatqf8403xat7vyge7mmen7zwjcgvryg22khtg3327s6mqqkxnpwlnrt27kxhwg37qys2kpn2d2jl2zkk44l7j7hq9az82594u3qaescr3c9v";
/// TODO: Add Doc Comment Here!
pub const ZENNIES_FOR_ZINGO_REGTEST_ADDRESS: &str = "uregtest14emvr2anyul683p43d0ck55c04r65ld6f0shetcn77z8j7m64hm4ku3wguf60s75f0g3s7r7g89z22f3ff5tsfgr45efj4pe2gyg5krqp5vvl3afu0280zp9ru2379zat5y6nkqkwjxsvpq5900kchcgzaw8v8z3ggt5yymnuj9hymtv3p533fcrk2wnj48g5vg42vle08c2xtanq0e";
/// TODO: Add Doc Comment Here!
pub const ZENNIES_FOR_ZINGO_TESTNET_ADDRESS: &str = "utest19zd9laj93deq4lkay48xcfyh0tjec786x6yrng38fp6zusgm0c84h3el99fngh8eks4kxv020r2h2njku6pf69anpqmjq5c3suzcjtlyhvpse0aqje09la48xk6a2cnm822s2yhuzfr47pp4dla9rakdk90g0cee070z57d3trqk87wwj4swz6uf6ts6p5z6lep3xyvueuvt7392tww";
/// TODO: Add Doc Comment Here!
pub const ZENNIES_FOR_ZINGO_DONATION_ADDRESS: &str = "u1p32nu0pgev5cr0u6t4ja9lcn29kaw37xch8nyglwvp7grl07f72c46hxvw0u3q58ks43ntg324fmulc2xqf4xl3pv42s232m25vaukp05s6av9z76s3evsstax4u6f5g7tql5yqwuks9t4ef6vdayfmrsymenqtshgxzj59hdydzygesqa7pdpw463hu7afqf4an29m69kfasdwr494";
/// TODO: Add Doc Comment Here!
pub const ZENNIES_FOR_ZINGO_AMOUNT: u64 = 1_000_000;
/// TODO: Add Doc Comment Here!
pub const DEFAULT_LIGHTWALLETD_SERVER: &str = "https://zec.rocks:443";
/// TODO: Add Doc Comment Here!
pub const DEFAULT_WALLET_NAME: &str = "zingo-wallet.dat";
/// TODO: Add Doc Comment Here!
pub const DEFAULT_LOGFILE_NAME: &str = "zingo-wallet.debug.log";

/// Re-export pepper-sync SyncConfig for use with load_clientconfig
///
pub use pepper_sync::sync::{SyncConfig, TransparentAddressDiscovery};

/// Creates a zingo config for lightclient construction.
pub fn load_clientconfig(
    lightwallet_uri: http::Uri,
    data_dir: Option<PathBuf>,
    chain: ChainType,
    wallet_settings: WalletSettings,
) -> std::io::Result<ZingoConfig> {
    use std::net::ToSocketAddrs;

    let host = lightwallet_uri.host();
    let port = lightwallet_uri.port();

    if host.is_none() || port.is_none() {
        info!("Using offline mode");
    } else {
        match format!(
            "{}:{}",
            lightwallet_uri.host().unwrap(),
            lightwallet_uri.port().unwrap()
        )
        .to_socket_addrs()
        {
            Ok(_) => {
                info!("Connected to {}", lightwallet_uri);
            }
            Err(e) => {
                info!("Couldn't resolve server: {}", e);
            }
        }
    }

    // Create a Light Client Config
    let config = ZingoConfig {
        lightwalletd_uri: Arc::new(RwLock::new(lightwallet_uri)),
        chain,
        wallet_dir: data_dir,
        wallet_name: DEFAULT_WALLET_NAME.into(),
        logfile_name: DEFAULT_LOGFILE_NAME.into(),
        wallet_settings,
    };

    Ok(config)
}

/// TODO: Add Doc Comment Here!
pub fn construct_lightwalletd_uri(server: Option<String>) -> http::Uri {
    match server {
        Some(s) => match s.is_empty() {
            true => {
                return http::Uri::default();
            }
            false => {
                let mut s = if s.starts_with("http") {
                    s
                } else {
                    "http://".to_string() + &s
                };
                let uri: http::Uri = s.parse().unwrap();
                if uri.port().is_none() {
                    s += ":9067";
                }
                s
            }
        },
        None => DEFAULT_LIGHTWALLETD_SERVER.to_string(),
    }
    .parse()
    .unwrap()
}

/// TODO: Add Doc Comment Here!
#[derive(Clone, Debug)]
pub struct ZingoConfigBuilder {
    /// TODO: Add Doc Comment Here!
    pub lightwalletd_uri: Option<http::Uri>,
    /// TODO: Add Doc Comment Here!
    pub chain: ChainType,
    /// TODO: Add Doc Comment Here!
    pub reorg_buffer_offset: Option<u32>,
    /// TODO: Add Doc Comment Here!
    pub monitor_mempool: Option<bool>,
    /// The directory where the wallet and logfiles will be created. By default, this will be in ~/.zcash on Linux and %APPDATA%\Zcash on Windows. For mac it is in: ~/Library/Application Support/Zcash
    pub wallet_dir: Option<PathBuf>,
    /// The filename of the wallet. This will be created in the `wallet_dir`.
    pub wallet_name: Option<PathBuf>,
    /// The filename of the logfile. This will be created in the `wallet_dir`.
    pub logfile_name: Option<PathBuf>,
    /// Wallet settings.
    pub wallet_settings: WalletSettings,
}

/// Configuration data that is necessary? and sufficient? for the creation of a LightClient.
// TODO: this config should only be used to create a lightclient, the data should then be moved into fields of
// lightclient or lightwallet if it needs to retained in memory.
#[derive(Clone, Debug)]
pub struct ZingoConfig {
    /// TODO: Add Doc Comment Here!
    pub lightwalletd_uri: Arc<RwLock<http::Uri>>,
    /// TODO: Add Doc Comment Here!
    pub chain: ChainType,
    /// The directory where the wallet and logfiles will be created. By default, this will be in ~/.zcash on Linux and %APPDATA%\Zcash on Windows.
    pub wallet_dir: Option<PathBuf>,
    /// The filename of the wallet. This will be created in the `wallet_dir`.
    pub wallet_name: PathBuf,
    /// The filename of the logfile. This will be created in the `wallet_dir`.
    pub logfile_name: PathBuf,
    /// Wallet settings.
    pub wallet_settings: WalletSettings,
}

impl ZingoConfigBuilder {
    /// Set the URI of the proxy server we download blockchain information from.
    /// # Examples
    /// ```
    /// use zingolib::config::ZingoConfigBuilder;
    /// use http::Uri;
    /// assert_eq!(ZingoConfigBuilder::default().set_lightwalletd_uri(("https://zcash.mysideoftheweb.com:19067").parse::<Uri>().unwrap()).lightwalletd_uri.clone().unwrap(), "https://zcash.mysideoftheweb.com:19067");
    /// ```
    pub fn set_lightwalletd_uri(&mut self, lightwalletd_uri: http::Uri) -> &mut Self {
        self.lightwalletd_uri = Some(lightwalletd_uri);
        self
    }

    /// Set the chain the consuming client will interact with.
    /// See <https://github.com/bitcoin/bips/blob/master/bip-0087.mediawiki#coin-type>
    /// for chain types.
    /// Note "chain type" is not a formal standard.
    /// # Examples
    /// ```
    /// use zingolib::config::ZingoConfigBuilder;
    /// use zingolib::config::ChainType::Testnet;
    /// assert_eq!(ZingoConfigBuilder::default().set_chain(Testnet).create().chain, Testnet);
    /// ```
    pub fn set_chain(&mut self, chain: ChainType) -> &mut Self {
        self.chain = chain;
        self
    }

    /// Set the wallet directory where client transaction data will be stored in a wallet.
    /// # Examples
    /// ```
    /// use zingolib::config::ZingoConfigBuilder;
    /// use tempfile::TempDir;
    /// let dir = tempfile::TempDir::with_prefix("zingo_doc_test").unwrap().into_path();
    /// let config = ZingoConfigBuilder::default().set_wallet_dir(dir.clone()).create();
    /// assert_eq!(config.wallet_dir.clone().unwrap(), dir);
    /// ```
    pub fn set_wallet_dir(&mut self, dir: PathBuf) -> &mut Self {
        self.wallet_dir = Some(dir);
        self
    }

    /// TODO: Add Doc Comment Here!
    pub fn set_wallet_settings(&mut self, wallet_settings: WalletSettings) -> &mut Self {
        self.wallet_settings = wallet_settings;
        self
    }

    /// TODO: Add Doc Comment Here!
    pub fn create(&self) -> ZingoConfig {
        let lightwalletd_uri = self.lightwalletd_uri.clone().unwrap_or_default();
        ZingoConfig {
            lightwalletd_uri: Arc::new(RwLock::new(lightwalletd_uri)),
            chain: self.chain,
            wallet_dir: self.wallet_dir.clone(),
            wallet_name: DEFAULT_WALLET_NAME.into(),
            logfile_name: DEFAULT_LOGFILE_NAME.into(),
            wallet_settings: self.wallet_settings.clone(),
        }
    }
}

impl Default for ZingoConfigBuilder {
    fn default() -> Self {
        ZingoConfigBuilder {
            lightwalletd_uri: None,
            monitor_mempool: None,
            reorg_buffer_offset: None,
            wallet_dir: None,
            wallet_name: None,
            logfile_name: None,
            chain: ChainType::Mainnet,
            wallet_settings: WalletSettings {
                sync_config: pepper_sync::sync::SyncConfig {
                    transparent_address_discovery:
                        pepper_sync::sync::TransparentAddressDiscovery::minimal(),
                },
            },
        }
    }
}

impl ZingoConfig {
    /// TODO: Add Doc Comment Here!
    pub fn build(chain: ChainType) -> ZingoConfigBuilder {
        ZingoConfigBuilder {
            chain,
            ..ZingoConfigBuilder::default()
        }
    }

    #[cfg(any(test, feature = "test-elevation"))]
    /// create a ZingoConfig that helps a LightClient connect to a server.
    pub fn create_testnet() -> ZingoConfig {
        ZingoConfig::build(ChainType::Testnet)
            .set_lightwalletd_uri(
                ("https://lightwalletd.testnet.electriccoin.co:9067")
                    .parse::<http::Uri>()
                    .unwrap(),
            )
            .create()
    }

    #[cfg(any(test, feature = "test-elevation"))]
    /// create a ZingoConfig that helps a LightClient connect to a server.
    pub fn create_mainnet() -> ZingoConfig {
        ZingoConfig::build(ChainType::Mainnet)
            .set_lightwalletd_uri(("https://zec.rocks:443").parse::<http::Uri>().unwrap())
            .create()
    }

    #[cfg(feature = "test-elevation")]
    /// create a ZingoConfig that signals a LightClient not to connect to a server.
    pub fn create_unconnected(chain: ChainType, dir: Option<PathBuf>) -> ZingoConfig {
        if let Some(dir) = dir {
            ZingoConfig::build(chain).set_wallet_dir(dir).create()
        } else {
            ZingoConfig::build(chain).create()
        }
    }

    /// Convenience wrapper
    pub fn sapling_activation_height(&self) -> u64 {
        self.chain
            .activation_height(NetworkUpgrade::Sapling)
            .unwrap()
            .into()
    }

    /// TODO: Add Doc Comment Here!
    pub fn orchard_activation_height(&self) -> u64 {
        self.chain
            .activation_height(NetworkUpgrade::Nu5)
            .unwrap()
            .into()
    }

    /// TODO: Add Doc Comment Here!
    pub fn set_data_dir(&mut self, dir_str: String) {
        self.wallet_dir = Some(PathBuf::from(dir_str));
    }

    /// Build the Logging config
    pub fn get_log_config(&self) -> io::Result<Config> {
        let window_size = 3; // log0, log1, log2
        let fixed_window_roller = FixedWindowRoller::builder()
            .build("zingo-wallet-log{}", window_size)
            .unwrap();
        let size_limit = 5 * 1024 * 1024; // 5MB as max log file size to roll
        let size_trigger = SizeTrigger::new(size_limit);
        let compound_policy =
            CompoundPolicy::new(Box::new(size_trigger), Box::new(fixed_window_roller));

        Config::builder()
            .appender(
                Appender::builder()
                    .filter(Box::new(ThresholdFilter::new(LevelFilter::Info)))
                    .build(
                        "logfile",
                        Box::new(
                            RollingFileAppender::builder()
                                .encoder(Box::new(PatternEncoder::new("{d} {l}::{m}{n}")))
                                .build(self.get_log_path(), Box::new(compound_policy))?,
                        ),
                    ),
            )
            .build(
                Root::builder()
                    .appender("logfile")
                    .build(LevelFilter::Debug),
            )
            .map_err(|e| Error::new(ErrorKind::Other, format!("{}", e)))
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_zingo_wallet_dir(&self) -> Box<Path> {
        #[cfg(any(target_os = "ios", target_os = "android"))]
        {
            PathBuf::from(&self.wallet_dir.as_ref().unwrap()).into_boxed_path()
        }

        #[cfg(not(any(target_os = "ios", target_os = "android")))]
        {
            let mut zcash_data_location;
            // If there's some --data-dir path provided, use it
            if self.wallet_dir.is_some() {
                zcash_data_location = PathBuf::from(&self.wallet_dir.as_ref().unwrap());
            } else {
                #[cfg(any(target_os = "macos", target_os = "windows"))]
                {
                    zcash_data_location =
                        dirs::data_dir().expect("Couldn't determine app data directory!");
                    zcash_data_location.push("Zcash");
                }

                #[cfg(not(any(target_os = "macos", target_os = "windows")))]
                {
                    if dirs::home_dir().is_none() {
                        log::info!("Couldn't determine home dir!");
                    }
                    zcash_data_location =
                        dirs::home_dir().expect("Couldn't determine home directory!");
                    zcash_data_location.push(".zcash");
                }

                match &self.chain {
                    ChainType::Testnet => zcash_data_location.push("testnet3"),
                    ChainType::Regtest(_) => zcash_data_location.push("regtest"),
                    ChainType::Mainnet => {}
                };
            }

            // Create directory if it doesn't exist on non-mobile platforms
            match std::fs::create_dir_all(zcash_data_location.clone()) {
                Ok(_) => {}
                Err(e) => {
                    eprintln!("Couldn't create zcash directory!\n{}", e);
                    panic!("Couldn't create zcash directory!");
                }
            };

            zcash_data_location.into_boxed_path()
        }
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_zcash_params_path(&self) -> io::Result<Box<Path>> {
        #[cfg(any(target_os = "ios", target_os = "android"))]
        {
            Ok(PathBuf::from(&self.wallet_dir.as_ref().unwrap()).into_boxed_path())
        }

        //TODO:  This fn is not correct for regtest mode
        #[cfg(not(any(target_os = "ios", target_os = "android")))]
        {
            if dirs::home_dir().is_none() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Couldn't determine Home Dir",
                ));
            }

            let zcash_params_dir = zcash_proofs::default_params_folder().unwrap();

            Ok(zcash_params_dir.into_boxed_path())
        }
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_lightwalletd_uri(&self) -> http::Uri {
        self.lightwalletd_uri
            .read()
            .expect("Couldn't read configured server URI!")
            .clone()
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_wallet_pathbuf(&self) -> PathBuf {
        let mut wallet_location = self.get_zingo_wallet_dir().into_path_buf();
        wallet_location.push(&self.wallet_name);
        wallet_location
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_wallet_path(&self) -> Box<Path> {
        self.get_wallet_pathbuf().into_boxed_path()
    }

    /// TODO: Add Doc Comment Here!
    pub fn wallet_path_exists(&self) -> bool {
        self.get_wallet_path().exists()
    }

    /// TODO: Add Doc Comment Here!
    #[deprecated(note = "this method was renamed 'wallet_path_exists' for clarity")]
    pub fn wallet_exists(&self) -> bool {
        self.wallet_path_exists()
    }

    /// TODO: Add Doc Comment Here!
    pub fn backup_existing_wallet(&self) -> Result<String, String> {
        if !self.wallet_path_exists() {
            return Err(format!(
                "Couldn't find existing wallet to backup. Looked in {:?}",
                self.get_wallet_path().to_str()
            ));
        }

        let mut backup_file_path = self.get_zingo_wallet_dir().into_path_buf();
        backup_file_path.push(format!(
            "zingo-wallet.backup.{}.dat",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs()
        ));

        let backup_file_str = backup_file_path.to_string_lossy().to_string();
        std::fs::copy(self.get_wallet_path(), backup_file_path).map_err(|e| format!("{}", e))?;

        Ok(backup_file_str)
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_log_path(&self) -> Box<Path> {
        let mut log_path = self.get_zingo_wallet_dir().into_path_buf();
        log_path.push(&self.logfile_name);
        //println!("LogFile:\n{}", log_path.to_str().unwrap());

        log_path.into_boxed_path()
    }
}

/// TODO: Add Doc Comment Here!
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChainType {
    /// Public testnet
    Testnet,
    /// Local testnet
    Regtest(RegtestNetwork),
    /// Mainnet
    Mainnet,
}

impl std::fmt::Display for ChainType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use ChainType::*;
        let name = match self {
            Testnet => "test",
            Regtest(_) => "regtest",
            Mainnet => "main",
        };
        write!(f, "{name}")
    }
}

impl Parameters for ChainType {
    fn network_type(&self) -> NetworkType {
        match self {
            ChainType::Mainnet => NetworkType::Main,
            ChainType::Testnet => NetworkType::Test,
            ChainType::Regtest(_) => NetworkType::Regtest,
        }
    }

    fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        use ChainType::*;
        match self {
            Mainnet => MAIN_NETWORK.activation_height(nu),
            Testnet => TEST_NETWORK.activation_height(nu),
            Regtest(regtest_network) => regtest_network.activation_height(nu),
        }
    }
}

/// TODO: Add Doc Comment Here!
// TODO: replace with infrastucture types
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RegtestNetwork {
    activation_heights: ActivationHeights,
}

impl RegtestNetwork {
    /// TODO: Add Doc Comment Here!
    pub fn new(
        overwinter_activation_height: u64,
        sapling_activation_height: u64,
        blossom_activation_height: u64,
        heartwood_activation_height: u64,
        canopy_activation_height: u64,
        orchard_activation_height: u64,
        nu6_activation_height: u64,
    ) -> Self {
        Self {
            activation_heights: ActivationHeights::new(
                overwinter_activation_height,
                sapling_activation_height,
                blossom_activation_height,
                heartwood_activation_height,
                canopy_activation_height,
                orchard_activation_height,
                nu6_activation_height,
            ),
        }
    }

    /// TODO: Add Doc Comment Here!
    pub fn all_upgrades_active() -> Self {
        Self {
            activation_heights: ActivationHeights::new(1, 1, 1, 1, 1, 1, 1),
        }
    }

    /// TODO: Add Doc Comment Here!
    pub fn set_orchard_and_nu6(custom_activation_height: u64) -> Self {
        Self {
            activation_heights: ActivationHeights::new(
                1,
                1,
                1,
                1,
                1,
                custom_activation_height,
                custom_activation_height,
            ),
        }
    }

    /// Network parameters
    pub fn activation_height(&self, nu: NetworkUpgrade) -> Option<BlockHeight> {
        match nu {
            NetworkUpgrade::Overwinter => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Overwinter),
            ),
            NetworkUpgrade::Sapling => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Sapling),
            ),
            NetworkUpgrade::Blossom => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Blossom),
            ),
            NetworkUpgrade::Heartwood => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Heartwood),
            ),
            NetworkUpgrade::Canopy => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Canopy),
            ),
            NetworkUpgrade::Nu5 => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Nu5),
            ),
            NetworkUpgrade::Nu6 => Some(
                self.activation_heights
                    .get_activation_height(NetworkUpgrade::Nu6),
            ),
        }
    }
}

/// TODO: Add Doc Comment Here!
// TODO: replace with infrastucture types
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ActivationHeights {
    overwinter: BlockHeight,
    sapling: BlockHeight,
    blossom: BlockHeight,
    heartwood: BlockHeight,
    canopy: BlockHeight,
    orchard: BlockHeight,
    nu6: BlockHeight,
}

impl ActivationHeights {
    /// TODO: Add Doc Comment Here!
    pub fn new(
        overwinter: u64,
        sapling: u64,
        blossom: u64,
        heartwood: u64,
        canopy: u64,
        orchard: u64,
        nu6: u64,
    ) -> Self {
        Self {
            overwinter: BlockHeight::from_u32(overwinter as u32),
            sapling: BlockHeight::from_u32(sapling as u32),
            blossom: BlockHeight::from_u32(blossom as u32),
            heartwood: BlockHeight::from_u32(heartwood as u32),
            canopy: BlockHeight::from_u32(canopy as u32),
            orchard: BlockHeight::from_u32(orchard as u32),
            nu6: BlockHeight::from_u32(nu6 as u32),
        }
    }

    /// TODO: Add Doc Comment Here!
    pub fn get_activation_height(&self, network_upgrade: NetworkUpgrade) -> BlockHeight {
        match network_upgrade {
            NetworkUpgrade::Overwinter => self.overwinter,
            NetworkUpgrade::Sapling => self.sapling,
            NetworkUpgrade::Blossom => self.blossom,
            NetworkUpgrade::Heartwood => self.heartwood,
            NetworkUpgrade::Canopy => self.canopy,
            NetworkUpgrade::Nu5 => self.orchard,
            NetworkUpgrade::Nu6 => self.nu6,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::wallet::WalletSettings;

    /// Validate that the load_clientconfig function creates a valid config from an empty uri
    #[tokio::test]
    async fn test_load_clientconfig() {
        rustls::crypto::ring::default_provider()
            .install_default()
            .expect("Ring to work as a default");
        tracing_subscriber::fmt().init();

        let valid_uri = crate::config::construct_lightwalletd_uri(Some("".to_string()));

        let temp_dir = tempfile::TempDir::new().unwrap();

        let temp_path = temp_dir.path().to_path_buf();

        let valid_config = crate::config::load_clientconfig(
            valid_uri.clone(),
            Some(temp_path),
            crate::config::ChainType::Mainnet,
            WalletSettings {
                sync_config: pepper_sync::sync::SyncConfig {
                    transparent_address_discovery:
                        pepper_sync::sync::TransparentAddressDiscovery::minimal(),
                },
            },
        );

        assert!(valid_config.is_ok());
    }

    #[tokio::test]
    async fn test_load_clientconfig_serverless() {
        rustls::crypto::ring::default_provider()
            .install_default()
            .expect("Ring to work as a default");
        tracing_subscriber::fmt().init();

        let valid_uri = crate::config::construct_lightwalletd_uri(Some(
            crate::config::DEFAULT_LIGHTWALLETD_SERVER.to_string(),
        ));
        // let invalid_uri = construct_lightwalletd_uri(Some("Invalid URI".to_string()));
        let temp_dir = tempfile::TempDir::new().unwrap();

        let temp_path = temp_dir.path().to_path_buf();
        // let temp_path_invalid = temp_dir.path().to_path_buf();

        let valid_config = crate::config::load_clientconfig(
            valid_uri.clone(),
            Some(temp_path),
            crate::config::ChainType::Mainnet,
            WalletSettings {
                sync_config: pepper_sync::sync::SyncConfig {
                    transparent_address_discovery:
                        pepper_sync::sync::TransparentAddressDiscovery::minimal(),
                },
            },
        )
        .unwrap();

        assert_eq!(valid_config.get_lightwalletd_uri(), valid_uri);
        assert_eq!(valid_config.chain, crate::config::ChainType::Mainnet);

        // let invalid_config = load_clientconfig_serverless(
        //     invalid_uri.clone(),
        //     Some(temp_path_invalid),
        //     ChainType::Mainnet,
        //     true,
        // );
        // assert_eq!(invalid_config.is_err(), true);
    }
}