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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
// Copyright 2024 Aleo Network Foundation
// This file is part of the snarkOS library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use snarkos_account::Account;
use snarkos_display::Display;
use snarkos_node::{bft::MEMORY_POOL_PORT, router::messages::NodeType, Node};
use snarkvm::{
    console::{
        account::{Address, PrivateKey},
        algorithms::Hash,
        network::{CanaryV0, MainnetV0, Network, TestnetV0},
    },
    ledger::{
        block::Block,
        committee::{Committee, MIN_DELEGATOR_STAKE, MIN_VALIDATOR_STAKE},
        store::{helpers::memory::ConsensusMemory, ConsensusStore},
    },
    prelude::{FromBytes, ToBits, ToBytes},
    synthesizer::VM,
    utilities::to_bytes_le,
};

use aleo_std::StorageMode;
use anyhow::{bail, ensure, Result};
use clap::Parser;
use colored::Colorize;
use core::str::FromStr;
use indexmap::IndexMap;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use serde::{Deserialize, Serialize};
use std::{
    net::SocketAddr,
    path::PathBuf,
    sync::{atomic::AtomicBool, Arc},
};
use tokio::runtime::{self, Runtime};

/// The recommended minimum number of 'open files' limit for a validator.
/// Validators should be able to handle at least 1000 concurrent connections, each requiring 2 sockets.
#[cfg(target_family = "unix")]
const RECOMMENDED_MIN_NOFILES_LIMIT: u64 = 2048;

/// The development mode RNG seed.
const DEVELOPMENT_MODE_RNG_SEED: u64 = 1234567890u64;
/// The development mode number of genesis committee members.
const DEVELOPMENT_MODE_NUM_GENESIS_COMMITTEE_MEMBERS: u16 = 4;

/// The CDN base url.
const CDN_BASE_URL: &str = "https://blocks.aleo.org";

/// A mapping of `staker_address` to `(validator_address, withdrawal_address, amount)`.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct BondedBalances(IndexMap<String, (String, String, u64)>);

impl FromStr for BondedBalances {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

/// Starts the snarkOS node.
#[derive(Clone, Debug, Parser)]
pub struct Start {
    /// Specify the network ID of this node
    #[clap(default_value = "0", long = "network")]
    pub network: u16,

    /// Specify this node as a validator
    #[clap(long = "validator")]
    pub validator: bool,
    /// Specify this node as a prover
    #[clap(long = "prover")]
    pub prover: bool,
    /// Specify this node as a client
    #[clap(long = "client")]
    pub client: bool,

    /// Specify the account private key of the node
    #[clap(long = "private-key")]
    pub private_key: Option<String>,
    /// Specify the path to a file containing the account private key of the node
    #[clap(long = "private-key-file")]
    pub private_key_file: Option<PathBuf>,

    /// Specify the IP address and port for the node server
    #[clap(long = "node")]
    pub node: Option<SocketAddr>,
    /// Specify the IP address and port for the BFT
    #[clap(long = "bft")]
    pub bft: Option<SocketAddr>,
    /// Specify the IP address and port of the peer(s) to connect to
    #[clap(default_value = "", long = "peers")]
    pub peers: String,
    /// Specify the IP address and port of the validator(s) to connect to
    #[clap(default_value = "", long = "validators")]
    pub validators: String,
    /// If the flag is set, a node will allow untrusted peers to connect
    #[clap(long = "allow-external-peers")]
    pub allow_external_peers: bool,

    /// Specify the IP address and port for the REST server
    #[clap(long = "rest")]
    pub rest: Option<SocketAddr>,
    /// Specify the requests per second (RPS) rate limit per IP for the REST server
    #[clap(default_value = "10", long = "rest-rps")]
    pub rest_rps: u32,
    /// If the flag is set, the node will not initialize the REST server
    #[clap(long)]
    pub norest: bool,

    /// If the flag is set, the node will not render the display
    #[clap(long)]
    pub nodisplay: bool,
    /// Specify the verbosity of the node [options: 0, 1, 2, 3, 4]
    #[clap(default_value = "1", long = "verbosity")]
    pub verbosity: u8,
    /// Specify the path to the file where logs will be stored
    #[clap(default_value_os_t = std::env::temp_dir().join("snarkos.log"), long = "logfile")]
    pub logfile: PathBuf,
    /// Enables the metrics exporter
    #[clap(default_value = "false", long = "metrics")]
    pub metrics: bool,

    /// Specify the path to a directory containing the storage database for the ledger
    #[clap(long = "storage")]
    pub storage: Option<PathBuf>,
    /// Enables the node to prefetch initial blocks from a CDN
    #[clap(long = "cdn")]
    pub cdn: Option<String>,
    /// If the flag is set, the node will not prefetch from a CDN
    #[clap(long)]
    pub nocdn: bool,

    /// Enables development mode, specify a unique ID for this node
    #[clap(long)]
    pub dev: Option<u16>,
    /// If development mode is enabled, specify the number of genesis validators (default: 4)
    #[clap(long)]
    pub dev_num_validators: Option<u16>,
    /// If developtment mode is enabled, specify whether node 0 should generate traffic to drive the network
    #[clap(default_value = "false", long = "no-dev-txs")]
    pub no_dev_txs: bool,
    /// If development mode is enabled, specify the custom bonded balances as a JSON object (default: None)
    #[clap(long)]
    pub dev_bonded_balances: Option<BondedBalances>,
}

impl Start {
    /// Starts the snarkOS node.
    pub fn parse(self) -> Result<String> {
        // Prepare the shutdown flag.
        let shutdown: Arc<AtomicBool> = Default::default();

        // Initialize the logger.
        let log_receiver =
            crate::helpers::initialize_logger(self.verbosity, self.nodisplay, self.logfile.clone(), shutdown.clone());
        // Initialize the runtime.
        Self::runtime().block_on(async move {
            // Clone the configurations.
            let mut cli = self.clone();
            // Parse the network.
            match cli.network {
                MainnetV0::ID => {
                    // Parse the node from the configurations.
                    let node = cli.parse_node::<MainnetV0>(shutdown.clone()).await.expect("Failed to parse the node");
                    // If the display is enabled, render the display.
                    if !cli.nodisplay {
                        // Initialize the display.
                        Display::start(node, log_receiver).expect("Failed to initialize the display");
                    }
                }
                TestnetV0::ID => {
                    // Parse the node from the configurations.
                    let node = cli.parse_node::<TestnetV0>(shutdown.clone()).await.expect("Failed to parse the node");
                    // If the display is enabled, render the display.
                    if !cli.nodisplay {
                        // Initialize the display.
                        Display::start(node, log_receiver).expect("Failed to initialize the display");
                    }
                }
                CanaryV0::ID => {
                    // Parse the node from the configurations.
                    let node = cli.parse_node::<CanaryV0>(shutdown.clone()).await.expect("Failed to parse the node");
                    // If the display is enabled, render the display.
                    if !cli.nodisplay {
                        // Initialize the display.
                        Display::start(node, log_receiver).expect("Failed to initialize the display");
                    }
                }
                _ => panic!("Invalid network ID specified"),
            };
            // Note: Do not move this. The pending await must be here otherwise
            // other snarkOS commands will not exit.
            std::future::pending::<()>().await;
        });

        Ok(String::new())
    }
}

impl Start {
    /// Returns the initial peer(s) to connect to, from the given configurations.
    fn parse_trusted_peers(&self) -> Result<Vec<SocketAddr>> {
        match self.peers.is_empty() {
            true => Ok(vec![]),
            false => Ok(self
                .peers
                .split(',')
                .flat_map(|ip| match ip.parse::<SocketAddr>() {
                    Ok(ip) => Some(ip),
                    Err(e) => {
                        eprintln!("The IP supplied to --peers ('{ip}') is malformed: {e}");
                        None
                    }
                })
                .collect()),
        }
    }

    /// Returns the initial validator(s) to connect to, from the given configurations.
    fn parse_trusted_validators(&self) -> Result<Vec<SocketAddr>> {
        match self.validators.is_empty() {
            true => Ok(vec![]),
            false => Ok(self
                .validators
                .split(',')
                .flat_map(|ip| match ip.parse::<SocketAddr>() {
                    Ok(ip) => Some(ip),
                    Err(e) => {
                        eprintln!("The IP supplied to --validators ('{ip}') is malformed: {e}");
                        None
                    }
                })
                .collect()),
        }
    }

    /// Returns the CDN to prefetch initial blocks from, from the given configurations.
    fn parse_cdn<N: Network>(&self) -> Option<String> {
        // Determine if the node type is not declared.
        let is_no_node_type = !(self.validator || self.prover || self.client);

        // Disable CDN if:
        //  1. The node is in development mode.
        //  2. The user has explicitly disabled CDN.
        //  3. The node is a prover (no need to sync).
        //  4. The node type is not declared (defaults to client) (no need to sync).
        if self.dev.is_some() || self.nocdn || self.prover || is_no_node_type {
            None
        }
        // Enable the CDN otherwise.
        else {
            // Determine the CDN URL.
            match &self.cdn {
                // Use the provided CDN URL if it is not empty.
                Some(cdn) => match cdn.is_empty() {
                    true => None,
                    false => Some(cdn.clone()),
                },
                // If no CDN URL is provided, determine the CDN URL based on the network ID.
                None => match N::ID {
                    MainnetV0::ID => Some(format!("{CDN_BASE_URL}/mainnet/v0")),
                    TestnetV0::ID => Some(format!("{CDN_BASE_URL}/testnet/v0")),
                    CanaryV0::ID => Some(format!("{CDN_BASE_URL}/canary/v0")),
                    _ => None,
                },
            }
        }
    }

    /// Read the private key directly from an argument or from a filesystem location,
    /// returning the Aleo account.
    fn parse_private_key<N: Network>(&self) -> Result<Account<N>> {
        match self.dev {
            None => match (&self.private_key, &self.private_key_file) {
                // Parse the private key directly.
                (Some(private_key), None) => Account::from_str(private_key.trim()),
                // Parse the private key from a file.
                (None, Some(path)) => {
                    check_permissions(path)?;
                    Account::from_str(std::fs::read_to_string(path)?.trim())
                }
                // Ensure the private key is provided to the CLI, except for clients or nodes in development mode.
                (None, None) => match self.client {
                    true => Account::new(&mut rand::thread_rng()),
                    false => bail!("Missing the '--private-key' or '--private-key-file' argument"),
                },
                // Ensure only one private key flag is provided to the CLI.
                (Some(_), Some(_)) => {
                    bail!("Cannot use '--private-key' and '--private-key-file' simultaneously, please use only one")
                }
            },
            Some(dev) => {
                // Sample the private key of this node.
                Account::try_from({
                    // Initialize the (fixed) RNG.
                    let mut rng = ChaChaRng::seed_from_u64(DEVELOPMENT_MODE_RNG_SEED);
                    // Iterate through 'dev' address instances to match the account.
                    for _ in 0..dev {
                        let _ = PrivateKey::<N>::new(&mut rng)?;
                    }
                    let private_key = PrivateKey::<N>::new(&mut rng)?;
                    println!("🔑 Your development private key for node {dev} is {}.\n", private_key.to_string().bold());
                    private_key
                })
            }
        }
    }

    /// Updates the configurations if the node is in development mode.
    fn parse_development(
        &mut self,
        trusted_peers: &mut Vec<SocketAddr>,
        trusted_validators: &mut Vec<SocketAddr>,
    ) -> Result<()> {
        // If `--dev` is set, assume the dev nodes are initialized from 0 to `dev`,
        // and add each of them to the trusted peers. In addition, set the node IP to `4130 + dev`,
        // and the REST IP to `3030 + dev`.
        if let Some(dev) = self.dev {
            // Add the dev nodes to the trusted peers.
            if trusted_peers.is_empty() {
                for i in 0..dev {
                    if i != dev {
                        trusted_peers.push(SocketAddr::from_str(&format!("127.0.0.1:{}", 4130 + i))?);
                    }
                }
            }
            // Add the dev nodes to the trusted validators.
            if trusted_validators.is_empty() {
                // To avoid ambiguity, we define the first few nodes to be the trusted validators to connect to.
                for i in 0..2 {
                    if i != dev {
                        trusted_validators.push(SocketAddr::from_str(&format!("127.0.0.1:{}", MEMORY_POOL_PORT + i))?);
                    }
                }
            }
            // Set the node IP to `4130 + dev`.
            //
            // Note: the `node` flag is an option to detect remote devnet testing.
            if self.node.is_none() {
                self.node = Some(SocketAddr::from_str(&format!("0.0.0.0:{}", 4130 + dev))?);
            }

            // If the `norest` flag is not set and the REST IP is not already specified set the REST IP to `3030 + dev`.
            if !self.norest && self.rest.is_none() {
                self.rest = Some(SocketAddr::from_str(&format!("0.0.0.0:{}", 3030 + dev)).unwrap());
            }
        }
        Ok(())
    }

    /// Returns an alternative genesis block if the node is in development mode.
    /// Otherwise, returns the actual genesis block.
    fn parse_genesis<N: Network>(&self) -> Result<Block<N>> {
        if self.dev.is_some() {
            // Determine the number of genesis committee members.
            let num_committee_members = match self.dev_num_validators {
                Some(num_committee_members) => num_committee_members,
                None => DEVELOPMENT_MODE_NUM_GENESIS_COMMITTEE_MEMBERS,
            };
            ensure!(
                num_committee_members >= DEVELOPMENT_MODE_NUM_GENESIS_COMMITTEE_MEMBERS,
                "Number of genesis committee members is too low"
            );

            // Initialize the (fixed) RNG.
            let mut rng = ChaChaRng::seed_from_u64(DEVELOPMENT_MODE_RNG_SEED);
            // Initialize the development private keys.
            let development_private_keys =
                (0..num_committee_members).map(|_| PrivateKey::<N>::new(&mut rng)).collect::<Result<Vec<_>>>()?;
            // Initialize the development addresses.
            let development_addresses =
                development_private_keys.iter().map(Address::<N>::try_from).collect::<Result<Vec<_>>>()?;

            // Construct the committee based on the state of the bonded balances.
            let (committee, bonded_balances) = match &self.dev_bonded_balances {
                Some(bonded_balances) => {
                    // Parse the bonded balances.
                    let bonded_balances = bonded_balances
                        .0
                        .iter()
                        .map(|(staker_address, (validator_address, withdrawal_address, amount))| {
                            let staker_addr = Address::<N>::from_str(staker_address)?;
                            let validator_addr = Address::<N>::from_str(validator_address)?;
                            let withdrawal_addr = Address::<N>::from_str(withdrawal_address)?;
                            Ok((staker_addr, (validator_addr, withdrawal_addr, *amount)))
                        })
                        .collect::<Result<IndexMap<_, _>>>()?;

                    // Construct the committee members.
                    let mut members = IndexMap::new();
                    for (staker_address, (validator_address, _, amount)) in bonded_balances.iter() {
                        // Ensure that the staking amount is sufficient.
                        match staker_address == validator_address {
                            true => ensure!(amount >= &MIN_VALIDATOR_STAKE, "Validator stake is too low"),
                            false => ensure!(amount >= &MIN_DELEGATOR_STAKE, "Delegator stake is too low"),
                        }

                        // Ensure that the validator address is included in the list of development addresses.
                        ensure!(
                            development_addresses.contains(validator_address),
                            "Validator address {validator_address} is not included in the list of development addresses"
                        );

                        // Add or update the validator entry in the list of members
                        members.entry(*validator_address).and_modify(|(stake, _, _)| *stake += amount).or_insert((
                            *amount,
                            true,
                            rng.gen_range(0..100),
                        ));
                    }
                    // Construct the committee.
                    let committee = Committee::<N>::new(0u64, members)?;
                    (committee, bonded_balances)
                }
                None => {
                    // Calculate the committee stake per member.
                    let stake_per_member =
                        N::STARTING_SUPPLY.saturating_div(2).saturating_div(num_committee_members as u64);
                    ensure!(stake_per_member >= MIN_VALIDATOR_STAKE, "Committee stake per member is too low");

                    // Construct the committee members and distribute stakes evenly among committee members.
                    let members = development_addresses
                        .iter()
                        .map(|address| (*address, (stake_per_member, true, rng.gen_range(0..100))))
                        .collect::<IndexMap<_, _>>();

                    // Construct the bonded balances.
                    // Note: The withdrawal address is set to the staker address.
                    let bonded_balances = members
                        .iter()
                        .map(|(address, (stake, _, _))| (*address, (*address, *address, *stake)))
                        .collect::<IndexMap<_, _>>();
                    // Construct the committee.
                    let committee = Committee::<N>::new(0u64, members)?;

                    (committee, bonded_balances)
                }
            };

            // Ensure that the number of committee members is correct.
            ensure!(
                committee.members().len() == num_committee_members as usize,
                "Number of committee members {} does not match the expected number of members {num_committee_members}",
                committee.members().len()
            );

            // Calculate the public balance per validator.
            let remaining_balance = N::STARTING_SUPPLY.saturating_sub(committee.total_stake());
            let public_balance_per_validator = remaining_balance.saturating_div(num_committee_members as u64);

            // Construct the public balances with fairly equal distribution.
            let mut public_balances = development_private_keys
                .iter()
                .map(|private_key| Ok((Address::try_from(private_key)?, public_balance_per_validator)))
                .collect::<Result<indexmap::IndexMap<_, _>>>()?;

            // If there is some leftover balance, add it to the 0-th validator.
            let leftover =
                remaining_balance.saturating_sub(public_balance_per_validator * num_committee_members as u64);
            if leftover > 0 {
                let (_, balance) = public_balances.get_index_mut(0).unwrap();
                *balance += leftover;
            }

            // Check if the sum of committee stakes and public balances equals the total starting supply.
            let public_balances_sum: u64 = public_balances.values().copied().sum();
            if committee.total_stake() + public_balances_sum != N::STARTING_SUPPLY {
                bail!("Sum of committee stakes and public balances does not equal total starting supply.");
            }

            // Construct the genesis block.
            load_or_compute_genesis(development_private_keys[0], committee, public_balances, bonded_balances, &mut rng)
        } else {
            // If the `dev_num_validators` flag is set, inform the user that it is ignored.
            if self.dev_num_validators.is_some() {
                eprintln!("The '--dev-num-validators' flag is ignored because '--dev' is not set");
            }

            Block::from_bytes_le(N::genesis_bytes())
        }
    }

    /// Returns the node type, from the given configurations.
    const fn parse_node_type(&self) -> NodeType {
        if self.validator {
            NodeType::Validator
        } else if self.prover {
            NodeType::Prover
        } else {
            NodeType::Client
        }
    }

    /// Returns the node type corresponding to the given configurations.
    #[rustfmt::skip]
    async fn parse_node<N: Network>(&mut self, shutdown: Arc<AtomicBool>) -> Result<Node<N>> {
        // Print the welcome.
        println!("{}", crate::helpers::welcome_message());

        // Parse the trusted peers to connect to.
        let mut trusted_peers = self.parse_trusted_peers()?;
        // Parse the trusted validators to connect to.
        let mut trusted_validators = self.parse_trusted_validators()?;
        // Parse the development configurations.
        self.parse_development(&mut trusted_peers, &mut trusted_validators)?;

        // Parse the CDN.
        let cdn = self.parse_cdn::<N>();

        // Parse the genesis block.
        let genesis = self.parse_genesis::<N>()?;
        // Parse the private key of the node.
        let account = self.parse_private_key::<N>()?;
        // Parse the node type.
        let node_type = self.parse_node_type();

        // Parse the node IP.
        let node_ip = match self.node {
            Some(node_ip) => node_ip,
            None => SocketAddr::from_str("0.0.0.0:4130").unwrap(),
        };

        // Parse the REST IP.
        let rest_ip = match self.norest {
            true => None,
            false => self.rest.or_else(|| Some("0.0.0.0:3030".parse().unwrap())),
        };

        // If the display is not enabled, render the welcome message.
        if self.nodisplay {
            // Print the Aleo address.
            println!("👛 Your Aleo address is {}.\n", account.address().to_string().bold());
            // Print the node type and network.
            println!(
                "🧭 Starting {} on {} at {}.\n",
                node_type.description().bold(),
                N::NAME.bold(),
                node_ip.to_string().bold()
            );

            // If the node is running a REST server, print the REST IP and JWT.
            if node_type.is_validator() {
                if let Some(rest_ip) = rest_ip {
                    println!("🌐 Starting the REST server at {}.\n", rest_ip.to_string().bold());

                    if let Ok(jwt_token) = snarkos_node_rest::Claims::new(account.address()).to_jwt_string() {
                        println!("🔑 Your one-time JWT token is {}\n", jwt_token.dimmed());
                    }
                }
            }
        }

        // If the node is a validator, check if the open files limit is lower than recommended.
        #[cfg(target_family = "unix")]
        if node_type.is_validator() {
            crate::helpers::check_open_files_limit(RECOMMENDED_MIN_NOFILES_LIMIT);
        }
        // Check if the machine meets the minimum requirements for a validator.
        crate::helpers::check_validator_machine(node_type);

        // Initialize the metrics.
        if self.metrics {
            metrics::initialize_metrics();
        }

        // Initialize the storage mode.
        let storage_mode = match &self.storage {
            Some(path) => StorageMode::Custom(path.clone()),
            None => StorageMode::from(self.dev),
        };

        // Determine whether to generate background transactions in dev mode.
        let dev_txs = match self.dev {
            Some(_) => !self.no_dev_txs,
            None => {
                // If the `no_dev_txs` flag is set, inform the user that it is ignored.
                if self.no_dev_txs {
                    eprintln!("The '--no-dev-txs' flag is ignored because '--dev' is not set");
                }
                false
            }
        };

        // Initialize the node.
        match node_type {
            NodeType::Validator => Node::new_validator(node_ip, self.bft, rest_ip, self.rest_rps, account, &trusted_peers, &trusted_validators, genesis, cdn, storage_mode, self.allow_external_peers, dev_txs, shutdown.clone()).await,
            NodeType::Prover => Node::new_prover(node_ip, account, &trusted_peers, genesis, storage_mode, shutdown.clone()).await,
            NodeType::Client => Node::new_client(node_ip, rest_ip, self.rest_rps, account, &trusted_peers, genesis, cdn, storage_mode, shutdown).await,
        }
    }

    /// Returns a runtime for the node.
    fn runtime() -> Runtime {
        // Retrieve the number of cores.
        let num_cores = num_cpus::get();

        // Initialize the number of tokio worker threads, max tokio blocking threads, and rayon cores.
        // Note: We intentionally set the number of tokio worker threads and number of rayon cores to be
        // more than the number of physical cores, because the node is expected to be I/O-bound.
        let (num_tokio_worker_threads, max_tokio_blocking_threads, num_rayon_cores_global) =
            (2 * num_cores, 512, num_cores);

        // Initialize the parallelization parameters.
        rayon::ThreadPoolBuilder::new()
            .stack_size(8 * 1024 * 1024)
            .num_threads(num_rayon_cores_global)
            .build_global()
            .unwrap();

        // Initialize the runtime configuration.
        runtime::Builder::new_multi_thread()
            .enable_all()
            .thread_stack_size(8 * 1024 * 1024)
            .worker_threads(num_tokio_worker_threads)
            .max_blocking_threads(max_tokio_blocking_threads)
            .build()
            .expect("Failed to initialize a runtime for the router")
    }
}

fn check_permissions(path: &PathBuf) -> Result<(), snarkvm::prelude::Error> {
    #[cfg(target_family = "unix")]
    {
        use std::os::unix::fs::PermissionsExt;
        ensure!(path.exists(), "The file '{:?}' does not exist", path);
        let parent = path.parent();
        if let Some(parent) = parent {
            let parent_permissions = parent.metadata()?.permissions().mode();
            ensure!(
                parent_permissions & 0o777 == 0o700,
                "The folder {:?} must be readable only by the owner (0700)",
                parent
            );
        }
        let permissions = path.metadata()?.permissions().mode();
        ensure!(permissions & 0o777 == 0o600, "The file {:?} must be readable only by the owner (0600)", path);
    }
    Ok(())
}

/// Loads or computes the genesis block.
fn load_or_compute_genesis<N: Network>(
    genesis_private_key: PrivateKey<N>,
    committee: Committee<N>,
    public_balances: indexmap::IndexMap<Address<N>, u64>,
    bonded_balances: indexmap::IndexMap<Address<N>, (Address<N>, Address<N>, u64)>,
    rng: &mut ChaChaRng,
) -> Result<Block<N>> {
    // Construct the preimage.
    let mut preimage = Vec::new();

    // Input the network ID.
    preimage.extend(&N::ID.to_le_bytes());

    // Input the genesis private key, committee, and public balances.
    preimage.extend(genesis_private_key.to_bytes_le()?);
    preimage.extend(committee.to_bytes_le()?);
    preimage.extend(&to_bytes_le![public_balances.iter().collect::<Vec<(_, _)>>()]?);
    preimage.extend(&to_bytes_le![
        bonded_balances
            .iter()
            .flat_map(|(staker, (validator, withdrawal, amount))| to_bytes_le![staker, validator, withdrawal, amount])
            .collect::<Vec<_>>()
    ]?);

    // Input the parameters' metadata based on network
    match N::ID {
        snarkvm::console::network::MainnetV0::ID => {
            preimage.extend(snarkvm::parameters::mainnet::BondValidatorVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::BondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::UnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::ClaimUnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::SetValidatorStateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::TransferPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::TransferPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::TransferPrivateToPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::TransferPublicToPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::FeePrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::FeePublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::mainnet::InclusionVerifier::METADATA.as_bytes());
        }
        snarkvm::console::network::TestnetV0::ID => {
            preimage.extend(snarkvm::parameters::testnet::BondValidatorVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::BondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::UnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::ClaimUnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::SetValidatorStateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::TransferPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::TransferPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::TransferPrivateToPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::TransferPublicToPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::FeePrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::FeePublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::testnet::InclusionVerifier::METADATA.as_bytes());
        }
        snarkvm::console::network::CanaryV0::ID => {
            preimage.extend(snarkvm::parameters::canary::BondValidatorVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::BondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::UnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::ClaimUnbondPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::SetValidatorStateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::TransferPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::TransferPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::TransferPrivateToPublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::TransferPublicToPrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::FeePrivateVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::FeePublicVerifier::METADATA.as_bytes());
            preimage.extend(snarkvm::parameters::canary::InclusionVerifier::METADATA.as_bytes());
        }
        _ => {
            // Unrecognized Network ID
            bail!("Unrecognized Network ID: {}", N::ID);
        }
    }

    // Initialize the hasher.
    let hasher = snarkvm::console::algorithms::BHP256::<N>::setup("aleo.dev.block")?;
    // Compute the hash.
    let hash = hasher.hash(&preimage.to_bits_le())?.to_string();

    // A closure to load the block.
    let load_block = |file_path| -> Result<Block<N>> {
        // Attempts to load the genesis block file locally.
        let buffer = std::fs::read(file_path)?;
        // Return the genesis block.
        Block::from_bytes_le(&buffer)
    };

    // Construct the file path.
    let file_path = std::env::temp_dir().join(hash);
    // Check if the genesis block exists.
    if file_path.exists() {
        // If the block loads successfully, return it.
        if let Ok(block) = load_block(&file_path) {
            return Ok(block);
        }
    }

    /* Otherwise, compute the genesis block and store it. */

    // Initialize a new VM.
    let vm = VM::from(ConsensusStore::<N, ConsensusMemory<N>>::open(Some(0))?)?;
    // Initialize the genesis block.
    let block = vm.genesis_quorum(&genesis_private_key, committee, public_balances, bonded_balances, rng)?;
    // Write the genesis block to the file.
    std::fs::write(&file_path, block.to_bytes_le()?)?;
    // Return the genesis block.
    Ok(block)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::{Command, CLI};
    use snarkvm::prelude::MainnetV0;

    type CurrentNetwork = MainnetV0;

    #[test]
    fn test_parse_trusted_peers() {
        let config = Start::try_parse_from(["snarkos", "--peers", ""].iter()).unwrap();
        assert!(config.parse_trusted_peers().is_ok());
        assert!(config.parse_trusted_peers().unwrap().is_empty());

        let config = Start::try_parse_from(["snarkos", "--peers", "1.2.3.4:5"].iter()).unwrap();
        assert!(config.parse_trusted_peers().is_ok());
        assert_eq!(config.parse_trusted_peers().unwrap(), vec![SocketAddr::from_str("1.2.3.4:5").unwrap()]);

        let config = Start::try_parse_from(["snarkos", "--peers", "1.2.3.4:5,6.7.8.9:0"].iter()).unwrap();
        assert!(config.parse_trusted_peers().is_ok());
        assert_eq!(config.parse_trusted_peers().unwrap(), vec![
            SocketAddr::from_str("1.2.3.4:5").unwrap(),
            SocketAddr::from_str("6.7.8.9:0").unwrap()
        ]);
    }

    #[test]
    fn test_parse_trusted_validators() {
        let config = Start::try_parse_from(["snarkos", "--validators", ""].iter()).unwrap();
        assert!(config.parse_trusted_validators().is_ok());
        assert!(config.parse_trusted_validators().unwrap().is_empty());

        let config = Start::try_parse_from(["snarkos", "--validators", "1.2.3.4:5"].iter()).unwrap();
        assert!(config.parse_trusted_validators().is_ok());
        assert_eq!(config.parse_trusted_validators().unwrap(), vec![SocketAddr::from_str("1.2.3.4:5").unwrap()]);

        let config = Start::try_parse_from(["snarkos", "--validators", "1.2.3.4:5,6.7.8.9:0"].iter()).unwrap();
        assert!(config.parse_trusted_validators().is_ok());
        assert_eq!(config.parse_trusted_validators().unwrap(), vec![
            SocketAddr::from_str("1.2.3.4:5").unwrap(),
            SocketAddr::from_str("6.7.8.9:0").unwrap()
        ]);
    }

    #[test]
    fn test_parse_cdn() {
        // Validator (Prod)
        let config = Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_some());
        let config =
            Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx", "--cdn", "url"].iter())
                .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_some());
        let config =
            Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx", "--cdn", ""].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Validator (Dev)
        let config =
            Start::try_parse_from(["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx", "--cdn", ""].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Prover (Prod)
        let config = Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config =
            Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx", "--cdn", "url"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config =
            Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx", "--cdn", ""].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Prover (Dev)
        let config =
            Start::try_parse_from(["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx", "--cdn", ""].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Client (Prod)
        let config = Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_some());
        let config =
            Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx", "--cdn", "url"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_some());
        let config =
            Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx", "--cdn", ""].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Client (Dev)
        let config =
            Start::try_parse_from(["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(
            ["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx", "--cdn", ""].iter(),
        )
        .unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Default (Prod)
        let config = Start::try_parse_from(["snarkos"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(["snarkos", "--cdn", "url"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(["snarkos", "--cdn", ""].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());

        // Default (Dev)
        let config = Start::try_parse_from(["snarkos", "--dev", "0"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(["snarkos", "--dev", "0", "--cdn", "url"].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
        let config = Start::try_parse_from(["snarkos", "--dev", "0", "--cdn", ""].iter()).unwrap();
        assert!(config.parse_cdn::<CurrentNetwork>().is_none());
    }

    #[test]
    fn test_parse_development_and_genesis() {
        let prod_genesis = Block::from_bytes_le(CurrentNetwork::genesis_bytes()).unwrap();

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config = Start::try_parse_from(["snarkos"].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        let candidate_genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
        assert_eq!(trusted_peers.len(), 0);
        assert_eq!(trusted_validators.len(), 0);
        assert_eq!(candidate_genesis, prod_genesis);

        let _config = Start::try_parse_from(["snarkos", "--dev", ""].iter()).unwrap_err();

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config = Start::try_parse_from(["snarkos", "--dev", "1"].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3031").unwrap()));

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config = Start::try_parse_from(["snarkos", "--dev", "1", "--rest", "127.0.0.1:8080"].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        assert_eq!(config.rest, Some(SocketAddr::from_str("127.0.0.1:8080").unwrap()));

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config = Start::try_parse_from(["snarkos", "--dev", "1", "--norest"].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        assert!(config.rest.is_none());

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config = Start::try_parse_from(["snarkos", "--dev", "0"].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        let expected_genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4130").unwrap()));
        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3030").unwrap()));
        assert_eq!(trusted_peers.len(), 0);
        assert_eq!(trusted_validators.len(), 1);
        assert!(!config.validator);
        assert!(!config.prover);
        assert!(!config.client);
        assert_ne!(expected_genesis, prod_genesis);

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config =
            Start::try_parse_from(["snarkos", "--dev", "1", "--validator", "--private-key", ""].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4131").unwrap()));
        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3031").unwrap()));
        assert_eq!(trusted_peers.len(), 1);
        assert_eq!(trusted_validators.len(), 1);
        assert!(config.validator);
        assert!(!config.prover);
        assert!(!config.client);
        assert_eq!(genesis, expected_genesis);

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config =
            Start::try_parse_from(["snarkos", "--dev", "2", "--prover", "--private-key", ""].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4132").unwrap()));
        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3032").unwrap()));
        assert_eq!(trusted_peers.len(), 2);
        assert_eq!(trusted_validators.len(), 2);
        assert!(!config.validator);
        assert!(config.prover);
        assert!(!config.client);
        assert_eq!(genesis, expected_genesis);

        let mut trusted_peers = vec![];
        let mut trusted_validators = vec![];
        let mut config =
            Start::try_parse_from(["snarkos", "--dev", "3", "--client", "--private-key", ""].iter()).unwrap();
        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4133").unwrap()));
        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3033").unwrap()));
        assert_eq!(trusted_peers.len(), 3);
        assert_eq!(trusted_validators.len(), 2);
        assert!(!config.validator);
        assert!(!config.prover);
        assert!(config.client);
        assert_eq!(genesis, expected_genesis);
    }

    #[test]
    fn clap_snarkos_start() {
        let arg_vec = vec![
            "snarkos",
            "start",
            "--nodisplay",
            "--dev",
            "2",
            "--validator",
            "--private-key",
            "PRIVATE_KEY",
            "--cdn",
            "CDN",
            "--peers",
            "IP1,IP2,IP3",
            "--validators",
            "IP1,IP2,IP3",
            "--rest",
            "127.0.0.1:3030",
        ];
        let cli = CLI::parse_from(arg_vec);

        if let Command::Start(start) = cli.command {
            assert!(start.nodisplay);
            assert_eq!(start.dev, Some(2));
            assert!(start.validator);
            assert_eq!(start.private_key.as_deref(), Some("PRIVATE_KEY"));
            assert_eq!(start.cdn, Some("CDN".to_string()));
            assert_eq!(start.rest, Some("127.0.0.1:3030".parse().unwrap()));
            assert_eq!(start.network, 0);
            assert_eq!(start.peers, "IP1,IP2,IP3");
            assert_eq!(start.validators, "IP1,IP2,IP3");
        } else {
            panic!("Unexpected result of clap parsing!");
        }
    }
}