Skip to main content

snarkos_cli/commands/
start.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::helpers::{
17    args::{network_id_parser, parse_node_data_dir},
18    dev::*,
19};
20
21use snarkos_account::Account;
22use snarkos_display::Display;
23use snarkos_node::{
24    Node,
25    bft::MEMORY_POOL_PORT,
26    network::{NodeType, bootstrap_peers},
27    rest::DEFAULT_REST_PORT,
28    router::DEFAULT_NODE_PORT,
29};
30use snarkos_utilities::{DevHotswapConfig, NodeDataDir, SignalHandler, jwt_secret_file, node_data};
31
32use snarkvm::{
33    console::{
34        account::{Address, PrivateKey},
35        algorithms::Hash,
36        network::{CanaryV0, MainnetV0, Network, TestnetV0},
37    },
38    ledger::{
39        block::Block,
40        committee::{Committee, MIN_DELEGATOR_STAKE, MIN_VALIDATOR_STAKE},
41        store::{ConsensusStore, helpers::memory::ConsensusMemory},
42    },
43    prelude::{FromBytes, Itertools, ToBits, ToBytes},
44    synthesizer::VM,
45    utilities::to_bytes_le,
46};
47
48use aleo_std::{StorageMode, aleo_ledger_dir};
49use anyhow::{Context, Result, anyhow, bail, ensure};
50use base64::prelude::{BASE64_STANDARD, Engine};
51use clap::Parser;
52use colored::Colorize;
53use core::str::FromStr;
54use indexmap::IndexMap;
55use rand::{RngExt, SeedableRng};
56use rand_chacha::ChaChaRng;
57use serde::{Deserialize, Serialize};
58
59use std::{
60    fs,
61    io::IsTerminal,
62    net::{Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs},
63    path::{Path, PathBuf},
64    sync::{Arc, atomic::AtomicBool},
65};
66use tokio::{
67    runtime::{self, Handle, Runtime},
68    sync::mpsc,
69    task,
70};
71use tracing::{debug, info, warn};
72use ureq::http;
73
74/// The recommended minimum number of 'open files' limit for a validator.
75/// Validators should be able to handle at least 1000 concurrent connections, each requiring 2 sockets.
76#[cfg(target_family = "unix")]
77const RECOMMENDED_MIN_NOFILES_LIMIT: u64 = 2048;
78
79// A mapping of `staker_address` to `(validator_address, withdrawal_address, amount)`.
80#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
81pub struct BondedBalances(IndexMap<String, (String, String, u64)>);
82
83impl FromStr for BondedBalances {
84    type Err = serde_json::Error;
85
86    fn from_str(s: &str) -> Result<Self, Self::Err> {
87        serde_json::from_str(s)
88    }
89}
90
91// Starts the snarkOS node.
92#[derive(Clone, Debug, Parser)]
93#[command(
94    // Use kebab-case for all arguments (e.g., use the `private-key` flag for the `private_key` field).
95    // This is already the default, but we specify it in case clap's default changes in the future.
96    rename_all = "kebab-case",
97
98    // Ensure at most one node type is specified.
99    group(clap::ArgGroup::new("node_type").required(false).multiple(false)
100),
101
102    // Ensure all other dev flags can only be set if `--dev` is set.
103    group(clap::ArgGroup::new("dev_flags").required(false).multiple(true).requires("dev")
104),
105    // Ensure any rest flag (including `--rest`) cannot be set
106    // if `--norest` is set.
107    group(clap::ArgGroup::new("rest_flags").required(false).multiple(true).conflicts_with("norest")),
108
109    // Ensure you cannot set --verbosity and --log-filter flags at the same time.
110    group(clap::ArgGroup::new("log_flags").required(false).multiple(false)),
111
112    // Ensure you need to set either --jwt-secret and --jwt-timestamp or --nojwt flags.
113    group(clap::ArgGroup::new("jwt_flags").required(false).multiple(true).conflicts_with("nojwt").conflicts_with("norest")),
114)]
115pub struct Start {
116    /// Specify the network ID of this node
117    /// [options: 0 = mainnet, 1 = testnet, 2 = canary]
118    #[clap(long, default_value_t=MainnetV0::ID, long, value_parser = network_id_parser())]
119    pub network: u16,
120
121    /// Start the node as a prover.
122    #[clap(long, group = "node_type")]
123    pub prover: bool,
124
125    /// Start the node as a client (default).
126    ///
127    /// Client are "full nodes", i.e, validate and execute all blocks they receive, but they do not participate in AleoBFT consensus.
128    #[clap(long, group = "node_type", verbatim_doc_comment)]
129    pub client: bool,
130
131    /// Start the node as a bootstrap client.
132    #[clap(long = "bootstrap-client", group = "node_type", conflicts_with_all = ["peers", "validators"], verbatim_doc_comment)]
133    pub bootstrap_client: bool,
134
135    /// Start the node as a validator.
136    ///
137    /// Validators are "full nodes", like clients, but also participate in AleoBFT.
138    #[clap(long, group = "node_type", verbatim_doc_comment)]
139    pub validator: bool,
140
141    /// Specify the account private key of the node
142    #[clap(long)]
143    pub private_key: Option<String>,
144
145    /// Specify the path to a file containing the account private key of the node
146    #[clap(long = "private-key-file")]
147    pub private_key_file: Option<PathBuf>,
148
149    /// Set the IP address and port used for P2P communication.
150    #[clap(long)]
151    pub node: Option<SocketAddr>,
152
153    /// Set the IP address and port used for BFT communication.
154    /// This argument is only allowed for validator nodes.
155    #[clap(long, requires = "validator")]
156    pub bft: Option<SocketAddr>,
157
158    /// Specify the host:port address pairs of the peer(s) to connect to (as a comma-separated list).
159    ///
160    /// These peers will be set as "trusted", which means the node will not disconnect from them when performing peer rotation.
161    ///
162    /// Setting peers to "" has the same effect as not setting the flag at all, except when using `--dev`.
163    #[clap(long, verbatim_doc_comment)]
164    pub peers: Option<String>,
165
166    /// Specify the host:port address pairs of the validator(s) to connect to.
167    #[clap(long)]
168    pub validators: Option<String>,
169
170    /// [DEPRECATED] [NO-OP] Allow untrusted peers (not listed in `--peers`) to connect.
171    ///
172    /// The flag will be ignored by client and prover nodes, as this behavior is always enabled for these types of nodes.
173    #[clap(long, verbatim_doc_comment)]
174    pub allow_external_peers: bool,
175
176    /// [DEPRECATED] [NO-OP] If the flag is set, a client will periodically evict more external peers
177    #[clap(long)]
178    pub rotate_external_peers: bool,
179
180    /// Specify the IP address and port for the REST server
181    #[clap(long, group = "rest_flags")]
182    pub rest: Option<SocketAddr>,
183
184    /// Specify the requests per second (RPS) rate limit per IP for the REST server
185    #[clap(long, default_value_t = 10, group = "rest_flags")]
186    pub rest_rps: u32,
187
188    /// Specify the JWT secret for the REST server (16B, base64-encoded).
189    #[clap(long, group = "jwt_flags")]
190    pub jwt_secret: Option<String>,
191
192    /// Specify the JWT creation timestamp; can be any time in the last 10 years.
193    #[clap(long, group = "jwt_flags")]
194    pub jwt_timestamp: Option<i64>,
195
196    /// If the flag is set, the node will not initialize the REST server.
197    #[clap(long)]
198    pub norest: bool,
199
200    /// If the flag is set, the node will not require JWT authentication for the REST server.
201    #[clap(long, group = "rest_flags")]
202    pub nojwt: bool,
203
204    /// If the flag is set, the node will only connect to trusted peers and validators.
205    #[clap(long)]
206    pub trusted_peers_only: bool,
207
208    /// Write log message to stdout instead of showing a terminal UI.
209    ///
210    /// This is useful, for example, for running a node as a service instead of in the foreground or to pipe its output into a file.
211    #[clap(long, verbatim_doc_comment)]
212    pub nodisplay: bool,
213
214    /// Do not show the Aleo banner and information about the node on startup.
215    #[clap(long, hide = true)]
216    pub nobanner: bool,
217
218    /// Specify the log verbosity of the node.
219    /// [options: 0 (lowest log level) to 6 (highest level)]
220    #[clap(long, default_value_t = 1, group = "log_flags")]
221    pub verbosity: u8,
222
223    /// Set a custom log filtering scheme, e.g., "off,snarkos_bft=trace", to show all log messages of snarkos_bft but nothing else.
224    #[clap(long, group = "log_flags")]
225    pub log_filter: Option<String>,
226
227    /// Specify the path to the file where logs will be stored
228    #[clap(long, default_value_os_t = std::env::temp_dir().join("snarkos.log"))]
229    pub logfile: PathBuf,
230
231    /// Enable the metrics exporter
232    #[cfg(feature = "metrics")]
233    #[clap(long)]
234    pub metrics: bool,
235
236    /// Specify the IP address and port for the metrics exporter
237    #[cfg(feature = "metrics")]
238    #[clap(long, requires = "metrics")]
239    pub metrics_ip: Option<SocketAddr>,
240
241    /// Specify the directory that holds all ledger data, e.g., blocks and transactions.
242    /// This flag overrides the default path, even when `--dev` is set.
243    ///
244    /// The old name for this flag (`--storage`) is DEPRECATED and will eventually be removed.
245    #[clap(long, verbatim_doc_comment, alias = "storage")]
246    pub ledger_storage: Option<PathBuf>,
247
248    /// Specify the directory that holds node-specific data, that is not part of the global ledger.
249    /// This flag overrides the default path, even when `--dev` is set.
250    ///
251    /// That folder may contain sensitive data, such as the JWT secret, and should not be shared with untrusted parties.
252    /// For validators, it also contains the latest proposal cache, which is required to participate in consensus.
253    #[clap(long, verbatim_doc_comment)]
254    pub node_data_storage: Option<PathBuf>,
255
256    /// If specified, the node will automatically save database checkpoints.
257    #[clap(long)]
258    pub auto_db_checkpoints: Option<PathBuf>,
259
260    /// Enables the node to prefetch initial blocks from a CDN
261    #[clap(long, conflicts_with = "nocdn")]
262    pub cdn: Option<http::Uri>,
263
264    /// If the flag is set, the node will not prefetch from a CDN
265    #[clap(long)]
266    pub nocdn: bool,
267
268    /// Enables development mode used to set up test networks.
269    ///
270    /// The purpose of this flag is to run multiple nodes on the same machine and in the same working directory.
271    /// To do this, set the value to a unique ID within the test work. For example if there are four nodes in the network, pass `--dev 0` for the first node, `--dev 1` for the second, and so forth.
272    ///
273    /// If you do not explicitly set the `--peers` flag, this will also populate the set of trusted peers, so that the network is fully connected.
274    /// Additionally, if you do not set the `--rest` or the `--norest` flags, it will also set the REST port to `3030` for the first node, `3031` for the second, and so forth.
275    #[clap(long, verbatim_doc_comment)]
276    pub dev: Option<u16>,
277
278    /// If development mode is enabled, specify the number of genesis validator.
279    #[clap(long, group = "dev_flags", default_value_t=DEVELOPMENT_MODE_NUM_GENESIS_COMMITTEE_MEMBERS)]
280    pub dev_num_validators: u16,
281
282    /// If development mode is enabled, specify the number of clients.
283    /// This is only used by validators to automatically populate their set of trusted peers.
284    ///
285    /// This option cannot be used while also passing the `--peers` flag.
286    #[clap(long, group = "dev_flags", conflicts_with = "peers")]
287    pub dev_num_clients: Option<u16>,
288
289    /// If development mode is enabled, specify whether node 0 should generate traffic to drive the network.
290    #[clap(long, group = "dev_flags")]
291    pub no_dev_txs: bool,
292
293    /// If development mode is enabled, specify the custom bonded balances as a JSON object.
294    #[clap(long, group = "dev_flags")]
295    pub dev_bonded_balances: Option<BondedBalances>,
296
297    /// If development mode is enabled, specify whether to run the node on a production ledger.
298    #[clap(long, group = "dev_flags", requires = "dev_num_validators", default_value_t = false)]
299    pub dev_on_prod: bool,
300
301    /// If the flag is set, the node will attempt to automatically migrate the node data to the new format.
302    #[clap(long)]
303    pub auto_migrate_node_data: bool,
304
305    /// Paths to Slipstream plugin config files (JSON5). May be repeated for multiple plugins.
306    /// Requires the node to be compiled with --features slipstream-plugins.
307    #[cfg(feature = "slipstream-plugins")]
308    #[clap(long = "slipstream-config", value_name = "PATH", verbatim_doc_comment)]
309    pub slipstream_configs: Vec<PathBuf>,
310}
311
312impl Start {
313    /// Starts the snarkOS node and blocks until it terminates.
314    pub fn parse(self) -> Result<String> {
315        // Prepare the shutdown flag.
316        let shutdown: Arc<AtomicBool> = Default::default();
317
318        // Initialize the logger.
319        let log_receiver = crate::helpers::initialize_logger(
320            self.verbosity,
321            &self.log_filter,
322            self.nodisplay,
323            self.logfile.clone(),
324            shutdown.clone(),
325        )
326        .with_context(|| "Failed to set up logger")?;
327
328        // When running in a non-interactive session, disallow the use of the terminal UI.
329        if !std::io::stdout().is_terminal() && !self.nodisplay {
330            anyhow::bail!(
331                "snarkOS cannot use the terminal UI in a non-interactive session. Please restart with `--nodisplay`."
332            );
333        }
334
335        // Initialize the runtime.
336        let runtime = Self::runtime();
337        let handle = runtime.handle().clone();
338        runtime.block_on(async move {
339            // Error messages.
340            let node_parse_error = || "Failed to start node";
341
342            // Periodically check if the number of file descriptors isn't becoming insufficient.
343            #[cfg(unix)]
344            crate::helpers::spawn_fd_monitor();
345
346            // Clone the configurations.
347            let mut self_ = self.clone();
348
349            // Parse the node arguments, start it, and block until shutdown.
350            match self_.network {
351                MainnetV0::ID => {
352                    self_.parse_node::<MainnetV0>(handle, log_receiver).await.with_context(node_parse_error)?
353                }
354                TestnetV0::ID => {
355                    self_.parse_node::<TestnetV0>(handle, log_receiver).await.with_context(node_parse_error)?
356                }
357                CanaryV0::ID => {
358                    self_.parse_node::<CanaryV0>(handle, log_receiver).await.with_context(node_parse_error)?
359                }
360                _ => panic!("Invalid network ID specified"),
361            };
362
363            Ok(String::new())
364        })
365    }
366}
367
368impl Start {
369    /// Returns the initial peer(s) to connect to, from the given configurations.
370    fn parse_trusted_addrs(&self, list: &Option<String>) -> Result<Vec<SocketAddr>> {
371        let Some(list) = list else { return Ok(vec![]) };
372
373        match list.is_empty() {
374            // Split on an empty string returns an empty string.
375            true => Ok(vec![]),
376            false => list.split(',').map(resolve_potential_hostnames).collect(),
377        }
378    }
379
380    /// Returns the CDN to prefetch initial blocks from, or `None` if fetching from the CDN is disabled.
381    fn parse_cdn<N: Network>(&self) -> Result<Option<http::Uri>> {
382        // Disable CDN if:
383        //  1. The node is in development mode.
384        //  2. The user has explicitly disabled CDN.
385        //  3. The node is a prover (no need to sync).
386        let no_cdn_reasons = [("--dev", self.dev.is_some()), ("--nocdn", self.nocdn), ("--prover", self.prover)]
387            .into_iter()
388            .filter_map(|(reason, flag_set)| flag_set.then_some(reason))
389            .join(" and ");
390        if !no_cdn_reasons.is_empty() {
391            info!("CDN disabled because the following flags are set: {no_cdn_reasons}.");
392            Ok(None)
393        }
394        // Enable the CDN otherwise.
395        else {
396            // Determine the CDN URL.
397            match &self.cdn {
398                // Use the provided CDN URL if it is not empty.
399                Some(cdn) => match cdn.to_string().is_empty() {
400                    true => Ok(None),
401                    false => Ok(Some(cdn.clone())),
402                },
403                // If no CDN URL is provided, determine the CDN URL based on the network ID.
404                None => {
405                    let uri = format!("{}/{}", snarkos_node_cdn::CDN_BASE_URL, N::SHORT_NAME);
406                    Ok(Some(http::Uri::try_from(&uri).with_context(|| "Unexpected error")?))
407                }
408            }
409        }
410    }
411
412    /// Read the private key directly from an argument or from a filesystem location,
413    /// returning the Aleo account.
414    fn parse_private_key<N: Network>(&self) -> Result<Account<N>> {
415        match self.dev {
416            None => match (&self.private_key, &self.private_key_file) {
417                // Parse the private key directly.
418                (Some(private_key), None) => Account::from_str(private_key.trim()),
419                // Parse the private key from a file.
420                (None, Some(path)) => {
421                    check_permissions(path)?;
422                    Account::from_str(std::fs::read_to_string(path)?.trim())
423                }
424                // Ensure the private key is provided to the CLI, except for clients or nodes in development mode.
425                (None, None) => match self.client {
426                    true => Account::new(&mut rand::rng()),
427                    false => bail!("Missing the '--private-key' or '--private-key-file' argument"),
428                },
429                // Ensure only one private key flag is provided to the CLI.
430                (Some(_), Some(_)) => {
431                    bail!("Cannot use '--private-key' and '--private-key-file' simultaneously, please use only one")
432                }
433            },
434            Some(index) => {
435                let private_key = get_development_key(index)?;
436                if !self.nobanner {
437                    println!(
438                        "🔑 Your development private key for node {index} is {}.\n",
439                        private_key.to_string().bold()
440                    );
441                }
442                Account::try_from(private_key)
443            }
444        }
445    }
446
447    /// Updates the configurations if the node is in development mode.
448    fn parse_development(
449        &mut self,
450        trusted_peers: &mut Vec<SocketAddr>,
451        trusted_validators: &mut Vec<SocketAddr>,
452    ) -> Result<()> {
453        // If `--dev` is not set, return early.
454        let Some(dev) = self.dev else {
455            return Ok(());
456        };
457
458        // Determine the number of development validators.
459        let num_validators = self.dev_num_validators;
460        ensure!(num_validators >= 4, "Value for `dev_num_validators` is too low. Needs to be at least 4.");
461
462        // If `--dev` is set, assume the dev nodes are initialized from 0 to `dev`,
463        // and add each of them to the trusted peers. In addition, set the node IP to `4130 + dev`,
464        // and the REST port to `3030 + dev`.
465        info!("Development mode enabled with index={dev} and num_validators={num_validators}.");
466
467        // Nodes only start as validators if the `--validator` flag is set, because the default mode is "client".
468        let is_validator = self.validator;
469
470        // Ensure the node type and `dev_num_validators` are compatible.
471        if is_validator {
472            ensure!(
473                dev < num_validators,
474                "Development validator index is too high (dev={dev}, dev_num_validators={num_validators})",
475            );
476        }
477        // A dev client or prover is allowed to have an index lower than
478        // `dev_num_validators` in order to have a balance at startup.
479
480        // Add the dev nodes to the trusted validators.
481        if trusted_validators.is_empty() && is_validator {
482            // Validators add all other validators as trusted.
483            for idx in 0..num_validators {
484                if idx == dev {
485                    continue;
486                }
487                trusted_validators.push(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, MEMORY_POOL_PORT + idx)));
488            }
489
490            debug!("Trusted validators set to: {trusted_validators:?}");
491        }
492
493        // Determine if we need to populate `trusted_peers`.
494        if trusted_peers.is_empty() {
495            if is_validator {
496                if let Some(num_clients) = self.dev_num_clients {
497                    // Ensure the clients that added this validator as a trusted peer are able to connect to it.
498                    for client_idx in 0..num_clients {
499                        if get_devnet_validators_for_client(client_idx, num_validators).contains(&dev) {
500                            let node_idx = num_validators + client_idx;
501                            trusted_peers.push(get_devnet_router_address_for_node(node_idx));
502                        }
503                    }
504                } else {
505                    warn!(
506                        "Development validator started without trusted peers or `--dev-num-clients`. No clients will be able to connect to it."
507                    );
508                }
509            } else {
510                // Clients/provers add two validators to connect to.
511                for validator_idx in get_devnet_validators_for_client(dev, num_validators) {
512                    trusted_peers.push(get_devnet_router_address_for_node(validator_idx));
513                }
514            }
515
516            debug!("Trusted peers set to: {trusted_peers:?}");
517        } else {
518            debug!("Trusted peers/validators was set manually. Will not populate them with development addresses.")
519        }
520
521        // Set the node's listening port to `4130 + dev`.
522        //
523        // Note: the `node` flag is an option to detect remote devnet testing.
524        if self.node.is_none() {
525            // Pick 0.0.0.0 here, not localhost.
526            let port = get_devnet_router_address_for_node(dev).port();
527            let address = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, port));
528            debug!("Setting node address to {address} due to dev={dev}");
529            self.node = Some(address);
530        }
531
532        // If the `norest` flag is not set and the REST IP is not already specified set the REST IP to `3030 + dev`.
533        if !self.norest && self.rest.is_none() {
534            let port = DEFAULT_REST_PORT + dev;
535            debug!("Setting REST port to {port} due to dev={dev}");
536            self.rest = Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, port)));
537        }
538
539        Ok(())
540    }
541
542    /// Returns the path to where the JWT secret for the node is stored.
543    fn jwt_secret_path<N: Network>(node_data_dir: &NodeDataDir, address: &Address<N>) -> PathBuf {
544        node_data_dir.path().join(jwt_secret_file(address))
545    }
546
547    /// Returns an alternative genesis block if the node is in development mode.
548    /// Otherwise, returns the actual genesis block.
549    fn parse_genesis<N: Network>(&self) -> Result<Block<N>> {
550        if self.dev.is_some() && !self.dev_on_prod {
551            // Determine the number of genesis committee members.
552            let num_committee_members = self.dev_num_validators;
553            ensure!(
554                num_committee_members >= DEVELOPMENT_MODE_NUM_GENESIS_COMMITTEE_MEMBERS,
555                "Number of genesis committee members is too low"
556            );
557
558            // Initialize the (fixed) RNG.
559            let mut rng = ChaChaRng::seed_from_u64(DEVELOPMENT_MODE_RNG_SEED);
560            // Initialize the development private keys.
561            let dev_keys =
562                (0..num_committee_members).map(|_| PrivateKey::<N>::new(&mut rng)).collect::<Result<Vec<_>>>()?;
563            // Initialize the development addresses.
564            let development_addresses = dev_keys.iter().map(Address::<N>::try_from).collect::<Result<Vec<_>>>()?;
565
566            // Construct the committee based on the state of the bonded balances.
567            let (committee, bonded_balances) = match &self.dev_bonded_balances {
568                Some(bonded_balances) => {
569                    // Parse the bonded balances.
570                    let bonded_balances = bonded_balances
571                        .0
572                        .iter()
573                        .map(|(staker_address, (validator_address, withdrawal_address, amount))| {
574                            let staker_addr = Address::<N>::from_str(staker_address)?;
575                            let validator_addr = Address::<N>::from_str(validator_address)?;
576                            let withdrawal_addr = Address::<N>::from_str(withdrawal_address)?;
577                            Ok((staker_addr, (validator_addr, withdrawal_addr, *amount)))
578                        })
579                        .collect::<Result<IndexMap<_, _>>>()?;
580
581                    // Construct the committee members.
582                    let mut members = IndexMap::new();
583                    for (staker_address, (validator_address, _, amount)) in bonded_balances.iter() {
584                        // Ensure that the staking amount is sufficient.
585                        match staker_address == validator_address {
586                            true => ensure!(amount >= &MIN_VALIDATOR_STAKE, "Validator stake is too low"),
587                            false => ensure!(amount >= &MIN_DELEGATOR_STAKE, "Delegator stake is too low"),
588                        }
589
590                        // Ensure that the validator address is included in the list of development addresses.
591                        ensure!(
592                            development_addresses.contains(validator_address),
593                            "Validator address {validator_address} is not included in the list of development addresses"
594                        );
595
596                        // Add or update the validator entry in the list of members
597                        members.entry(*validator_address).and_modify(|(stake, _, _)| *stake += amount).or_insert((
598                            *amount,
599                            true,
600                            rng.random_range(0..100),
601                        ));
602                    }
603                    // Construct the committee.
604                    let committee = Committee::<N>::new(0u64, members)?;
605                    (committee, bonded_balances)
606                }
607                None => {
608                    // Calculate the committee stake per member.
609                    let stake_per_member =
610                        N::STARTING_SUPPLY.saturating_div(2).saturating_div(num_committee_members as u64);
611                    ensure!(stake_per_member >= MIN_VALIDATOR_STAKE, "Committee stake per member is too low");
612
613                    // Construct the committee members and distribute stakes evenly among committee members.
614                    let members = development_addresses
615                        .iter()
616                        .map(|address| (*address, (stake_per_member, true, rng.random_range(0..100))))
617                        .collect::<IndexMap<_, _>>();
618
619                    // Construct the bonded balances.
620                    // Note: The withdrawal address is set to the staker address.
621                    let bonded_balances = members
622                        .iter()
623                        .map(|(address, (stake, _, _))| (*address, (*address, *address, *stake)))
624                        .collect::<IndexMap<_, _>>();
625                    // Construct the committee.
626                    let committee = Committee::<N>::new(0u64, members)?;
627
628                    (committee, bonded_balances)
629                }
630            };
631
632            // Ensure that the number of committee members is correct.
633            ensure!(
634                committee.members().len() == num_committee_members as usize,
635                "Number of committee members {} does not match the expected number of members {num_committee_members}",
636                committee.members().len()
637            );
638
639            // Calculate the public balance per validator.
640            let remaining_balance = N::STARTING_SUPPLY.saturating_sub(committee.total_stake());
641            let public_balance_per_validator = remaining_balance.saturating_div(num_committee_members as u64);
642
643            // Construct the public balances with fairly equal distribution.
644            let mut public_balances = dev_keys
645                .iter()
646                .map(|private_key| Ok((Address::try_from(private_key)?, public_balance_per_validator)))
647                .collect::<Result<indexmap::IndexMap<_, _>>>()?;
648
649            // If there is some leftover balance, add it to the 0-th validator.
650            let leftover =
651                remaining_balance.saturating_sub(public_balance_per_validator * num_committee_members as u64);
652            if leftover > 0 {
653                let (_, balance) = public_balances.get_index_mut(0).unwrap();
654                *balance += leftover;
655            }
656
657            // Check if the sum of committee stakes and public balances equals the total starting supply.
658            let public_balances_sum: u64 = public_balances.values().copied().sum();
659            if committee.total_stake() + public_balances_sum != N::STARTING_SUPPLY {
660                bail!("Sum of committee stakes and public balances does not equal total starting supply.");
661            }
662
663            // Construct the genesis block.
664            std::thread::spawn(move || {
665                load_or_compute_genesis(dev_keys[0], committee, public_balances, bonded_balances, &mut rng)
666            })
667            .join()
668            .unwrap()
669        } else {
670            Block::from_bytes_le(N::genesis_bytes())
671        }
672    }
673
674    /// Returns the node type specified in the command-line arguments.
675    /// This will return `NodeType::Client` if no node type was specified by the user.
676    const fn parse_node_type(&self) -> NodeType {
677        if self.validator {
678            NodeType::Validator
679        } else if self.prover {
680            NodeType::Prover
681        } else if self.bootstrap_client {
682            NodeType::BootstrapClient
683        } else {
684            NodeType::Client
685        }
686    }
687
688    /// Start the node and blocks until it terminates.
689    #[rustfmt::skip]
690    async fn parse_node<N: Network>(&mut self, handle: Handle, log_receiver: mpsc::Receiver<Vec<u8>>) -> Result<()> {
691        if !self.nobanner {
692            // Print the welcome banner.
693            println!("{}", crate::helpers::welcome_message());
694        }
695
696        // Only allow dev mode if we built with the 'test_network' feature.
697        if self.dev.is_some() && cfg!(not(feature = "test_network")) {
698            bail!("The 'dev' flag is set, but the 'test_network' feature is not enabled");
699        }
700
701        // Parse the trusted peers to connect to.
702        let mut trusted_peers = self.parse_trusted_addrs(&self.peers)?;
703        // Parse the trusted validators to connect to.
704        let mut trusted_validators = self.parse_trusted_addrs(&self.validators)?;
705
706        // Ensure there are no bootstrappers among the trusted peers and validators.
707        let bootstrap_peers = bootstrap_peers::<N>(self.dev.is_some());
708        for trusted in [&mut trusted_peers, &mut trusted_validators] {
709            let initial_peer_count = trusted.len();
710            trusted.retain(|addr| !bootstrap_peers.contains(addr));
711            let final_peer_count = trusted.len();
712            // Warn if this had to be corrected.
713            if final_peer_count != initial_peer_count {
714                warn!(
715                    "Removed some ({}) trusted peers due to them also being bootstrap peers.",
716                    initial_peer_count - final_peer_count
717                );
718            }
719        }
720
721        // Parse the development configurations.
722        self.parse_development(&mut trusted_peers, &mut trusted_validators)?;
723
724        // Determine if the node should sync from CDn..
725        let cdn = self.parse_cdn::<N>().with_context(|| "Failed to parse given CDN URL")?;
726
727        // Parse the genesis block.
728        let start = self.clone();
729        let genesis = task::spawn_blocking(move || start.parse_genesis::<N>()).await??;
730        // Parse the private key of the node.
731        let account = self.parse_private_key::<N>()?;
732        // Parse the node type.
733        let node_type = self.parse_node_type();
734
735        // Parse the node IP or use the default IP/port.
736        let node_ip = self.node.unwrap_or(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, DEFAULT_NODE_PORT)));
737
738        // Parse the REST IP.
739        let rest_ip = match self.norest {
740            true => None,
741            false => self.rest.or_else(|| Some("0.0.0.0:3030".parse().unwrap())),
742        };
743
744        // Initialize the storage mode.
745        let storage_mode = match &self.ledger_storage {
746            Some(path) => StorageMode::Custom(path.clone()),
747            None => match self.dev {
748                Some(id) => StorageMode::Development(id),
749                None => StorageMode::Production,
750            },
751        };
752
753        // Users may have unintentionally set a custom path for the ledger, but not for the node data.
754        // For validators, we make this an errors, so important files like the proposal cache are stored at the location
755        // exepcted by the node operator.
756        if self.node_data_storage.is_some() && !matches!(storage_mode, StorageMode::Custom(_)) {
757            if node_type == NodeType::Validator {
758                bail!("Custom path set for `--node-data-storage`, but not for `--ledger-storage`.")
759            } else {
760                warn!("Custom path set for `--node-data-storage`, but not for `--ledger-storage`. The latter will use the default path.");   
761            }
762        } else if matches!(storage_mode, StorageMode::Custom(_)) && self.node_data_storage.is_none() {
763            if node_type == NodeType::Validator {
764                bail!("Custom path set for `--ledger-storage`, but not for `--node-data-storage`.");
765            } else {
766                warn!("Custom path set for `--ledger-storage`, but not for `--node-data-storage`. The latter will use the default path.");
767            }
768        }
769
770        // Parse the node data directory.
771        let node_data_dir = parse_node_data_dir(&self.node_data_storage, N::ID, self.dev).with_context(|| "Failed to setup node configuration directory")?;
772
773        // Make sure the directory exists before continue.
774        let data_path = node_data_dir.path();
775        if !data_path.exists() {
776            info!("Creating directore for node data storage at {data_path:?}");
777            std::fs::create_dir_all(data_path)
778                .with_context(|| format!("Failed to create directory for node data storage at {data_path:?}"))?
779        } else if !data_path.is_dir() {
780            bail!("Node data storage location at {data_path:?} is not a directory");
781        } else {
782            debug!("Using existing directory at {data_path:?} for node data storage");
783        }
784
785        // Checks for the old storage format and prints instructions to migrate.
786        // We perform this check after creating the node data directory, so that migrating the data is easier.
787        Self::check_for_old_storage_format(&aleo_ledger_dir(N::ID, &storage_mode), &account.address(), &node_data_dir, self.dev, self.auto_migrate_node_data).with_context(|| "Node still uses the old storage format.")?;
788
789        // Compute the optional REST server JWT.
790        let jwt_token = if self.nojwt {
791            None
792        } else if let Some(jwt_b64) = &self.jwt_secret {
793            // Decode the JWT secret.
794            let jwt_bytes = BASE64_STANDARD.decode(jwt_b64).map_err(|_| anyhow::anyhow!("Invalid JWT secret"))?;
795            if jwt_bytes.len() != 16 {
796                bail!("The JWT secret must be 16 bytes long");
797            }
798            // Create the JWT token based on the given secret.
799            let jwt_token = snarkos_node_rest::Claims::new(account.address(), Some(jwt_bytes), self.jwt_timestamp).to_jwt_string()?;
800            // Store the JWT secret to a file.
801            let path = Self::jwt_secret_path(&node_data_dir, &account.address());
802            std::fs::write(path, &jwt_token)?;
803            // Return the JWT token for optional printing.
804            Some(jwt_token)
805        } else {
806            // Create a random JWT token.
807            let jwt_token = snarkos_node_rest::Claims::new(account.address(), None, self.jwt_timestamp).to_jwt_string()?;
808            // Store the JWT secret to a file.
809            let path = Self::jwt_secret_path(&node_data_dir, &account.address());
810            std::fs::write(path, &jwt_token)? ;
811            // Return the JWT token for optional printing.
812            Some(jwt_token)
813        };
814
815        if !self.nobanner {
816            // Print the Aleo address.
817            println!("👛 Your Aleo address is {}.\n", account.address().to_string().bold());
818            // Print the node type and network.
819            println!(
820                "🧭 Starting {} on {} at {}.\n",
821                node_type.description().bold(),
822                N::NAME.bold(),
823                node_ip.to_string().bold()
824            );
825            // If the node is running a REST server, determine the JWT.
826            if let Some(rest_ip) = rest_ip {
827                println!("🌐 Starting the REST server at {}.\n", rest_ip.to_string().bold());
828                if let Some(jwt_token) = jwt_token {
829                    println!("🔑 Your one-time JWT token is {}\n", jwt_token.dimmed());
830                }
831            }
832        }
833
834        // If the node is a validator, check if the open files limit is lower than recommended.
835        #[cfg(target_family = "unix")]
836        if node_type.is_validator() {
837            crate::helpers::check_open_files_limit(RECOMMENDED_MIN_NOFILES_LIMIT);
838        }
839        // Check if the machine meets the minimum requirements for a validator.
840        crate::helpers::check_validator_machine(node_type);
841
842        // Initialize the metrics.
843        #[cfg(feature = "metrics")]
844        if self.metrics {
845            metrics::initialize_metrics(self.metrics_ip);
846        }
847
848        // Determine whether to generate background transactions in dev mode.
849        let dev_txs = match self.dev {
850            Some(_) => !self.no_dev_txs,
851            None => {
852                // If the `no_dev_txs` flag is set, inform the user that it is ignored.
853                if self.no_dev_txs {
854                    eprintln!("The '--no-dev-txs' flag is ignored because '--dev' is not set");
855                }
856                false
857            }
858        };
859
860        // Determine the dev committee hotswap configuration.
861        let dev_hotswap_config = self.dev_on_prod.then_some(DevHotswapConfig {
862            dev_num_validators: self.dev_num_validators,
863        });
864
865        // TODO(kaimast): start the display earlier and show sync progress.
866        if !self.nodisplay && cdn.is_some() {
867            println!("🪧 The terminal UI will not start until the node has finished syncing from the CDN. If this step takes too long, consider restarting with `--nodisplay`.");
868        }
869
870        // Register the signal handler.
871        let signal_handler = SignalHandler::new(Some(handle));
872
873        // Collect slipstream plugin config paths (empty slice when feature is disabled).
874        #[cfg(feature = "slipstream-plugins")]
875        let slipstream_configs: &[PathBuf] = &self.slipstream_configs;
876        #[cfg(not(feature = "slipstream-plugins"))]
877        let slipstream_configs: &[PathBuf] = &[];
878
879        // Initialize the node.
880        let node = match node_type {
881            NodeType::Validator => Node::new_validator(node_ip, self.bft, rest_ip, self.rest_rps, account, &trusted_peers, &trusted_validators, genesis, cdn, storage_mode, node_data_dir, self.trusted_peers_only, self.auto_db_checkpoints.clone(), dev_txs, self.dev, slipstream_configs, dev_hotswap_config, signal_handler.clone()).await,
882            NodeType::Prover => Node::new_prover(node_ip, account, &trusted_peers, genesis, node_data_dir, self.trusted_peers_only, self.dev, signal_handler.clone()).await,
883            NodeType::Client => Node::new_client(node_ip, rest_ip, self.rest_rps, account, &trusted_peers, genesis, cdn, storage_mode, node_data_dir, self.trusted_peers_only, self.auto_db_checkpoints.clone(), self.dev, slipstream_configs, signal_handler.clone()).await,
884            NodeType::BootstrapClient => Node::new_bootstrap_client(node_ip, account, *genesis.header(), self.dev).await,
885        }?;
886
887        if !self.nodisplay {
888            Display::start(node.clone(), log_receiver, signal_handler.clone()).with_context(|| "Failed to start the display")?;
889        }
890
891        node.wait_for_signals(&signal_handler).await;
892        Ok(())
893    }
894
895    /// Check if the node is still using the old storage format,
896    /// in which case we print an error and exit.
897    /// We detect this by checking if
898    /// - a peer-cache file exists inside the ledger directory,
899    /// - a current-proposal-cache file exists at the parent directory of the ledger directory
900    /// - a jwt_secret_*.txt file exists at the parent directory of the ledger directory
901    fn check_for_old_storage_format<N: Network>(
902        ledger_dir: &Path,
903        address: &Address<N>,
904        node_data_dir: &NodeDataDir,
905        dev: Option<u16>,
906        auto_migrate: bool,
907    ) -> Result<()> {
908        let ledger_parent_dir = ledger_dir.parent().unwrap();
909
910        // Determine the old paths used for node configuration files.
911        let old_router_cache_path = ledger_dir.join(node_data::LEGACY_ROUTER_PEER_CACHE_FILE);
912        let old_gateway_cache_path = ledger_dir.join(node_data::LEGACY_GATEWAY_PEER_CACHE_FILE);
913        let old_proposal_cache_path = ledger_dir.join(node_data::legacy_current_proposal_cache_file(N::ID, dev));
914        let old_jwt_secret_path = ledger_parent_dir.join(node_data::jwt_secret_file(address));
915
916        if auto_migrate {
917            if old_router_cache_path.exists() {
918                let new_router_cache_path = node_data_dir.router_peer_cache_path();
919                info!("Migrating node data file \"{old_router_cache_path:?}\" to \"{new_router_cache_path:?}\"");
920                fs::rename(old_router_cache_path, new_router_cache_path)
921                    .with_context(|| "Failed to migrate node data file")?;
922            }
923
924            if old_gateway_cache_path.exists() {
925                let new_gateway_cache_path = node_data_dir.gateway_peer_cache_path();
926                info!("Migrating node data file \"{old_gateway_cache_path:?}\" to \"{new_gateway_cache_path:?}\"");
927                fs::rename(old_gateway_cache_path, new_gateway_cache_path)
928                    .with_context(|| "Failed to migrate node data file")?;
929            }
930
931            if old_proposal_cache_path.exists() {
932                let new_proposal_cache_path = node_data_dir.current_proposal_cache_path();
933                info!("Migrating node data file \"{old_proposal_cache_path:?}\" to \"{new_proposal_cache_path:?}\"");
934                fs::rename(old_proposal_cache_path, new_proposal_cache_path)
935                    .with_context(|| "Failed to migrate node data file")?;
936            }
937
938            if old_jwt_secret_path.exists() {
939                let new_jwt_secret_path = node_data_dir.jwt_secret_path(&address);
940                info!("Migrating node data file \"{old_jwt_secret_path:?}\" to \"{new_jwt_secret_path:?}\"");
941                fs::rename(old_jwt_secret_path, new_jwt_secret_path)
942                    .with_context(|| "Failed to migrate node data file")?;
943            }
944        } else {
945            if old_router_cache_path.exists() {
946                let new_router_cache_path = node_data_dir.router_peer_cache_path();
947                bail!(
948                    "Please migrate the node data file \"{old_router_cache_path:?}\" to \"{new_router_cache_path:?}\" before restarting, or restart with `--auto-migrate-node-data`."
949                );
950            }
951
952            if old_gateway_cache_path.exists() {
953                let new_gateway_cache_path = node_data_dir.gateway_peer_cache_path();
954                bail!(
955                    "Please migrate the node data file \"{old_gateway_cache_path:?}\" to \"{new_gateway_cache_path:?}\" before restarting, or restart with `--auto-migrate-node-data`."
956                );
957            }
958
959            if old_proposal_cache_path.exists() {
960                let new_proposal_cache_path = node_data_dir.current_proposal_cache_path();
961                bail!(
962                    "Please migrate the node data file \"{old_proposal_cache_path:?}\" to \"{new_proposal_cache_path:?}\" before restarting, or restart with `--auto-migrate-node-data`."
963                );
964            }
965
966            if old_jwt_secret_path.exists() {
967                let new_jwt_secret_path = node_data_dir.jwt_secret_path(&address);
968                bail!(
969                    "Please migrate the node data file \"{old_jwt_secret_path:?}\" to \"{new_jwt_secret_path:?}\" before restarting, or restart with `--auto-migrate-node-data`."
970                );
971            }
972        }
973
974        Ok(())
975    }
976
977    /// Starts a rayon thread pool and tokio runtime for the node, and returns the tokio `Runtime`.
978    fn runtime() -> Runtime {
979        // Retrieve the number of cores.
980        let num_cores = num_cpus::get();
981
982        // Initialize the number of tokio worker threads, max tokio blocking threads, and rayon cores.
983        // Note: We intentionally set the number of tokio worker threads and number of rayon cores to be
984        // more than the number of physical cores, because the node is expected to be I/O-bound.
985        let (num_tokio_worker_threads, max_tokio_blocking_threads, num_rayon_cores_global) =
986            (2 * num_cores, 512, num_cores);
987
988        // Set up the rayon thread pool.
989        // A custom panic handler is not needed here, as rayon propagates the panic to the calling thread by default (except for `rayon::spawn` which we do not use).
990        rayon::ThreadPoolBuilder::new()
991            .stack_size(8 * 1024 * 1024)
992            .num_threads(num_rayon_cores_global)
993            .build_global()
994            .unwrap();
995
996        // Set up the tokio Runtime.
997        // TODO(kaimast): set up a panic handler here for each worker thread once [`tokio::runtime::Builder::unhandled_panic`](https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html#method.unhandled_panic) is stabilized.
998        runtime::Builder::new_multi_thread()
999            .enable_all()
1000            .thread_stack_size(8 * 1024 * 1024)
1001            .worker_threads(num_tokio_worker_threads)
1002            .max_blocking_threads(max_tokio_blocking_threads)
1003            .build()
1004            .expect("Failed to initialize a runtime for the router")
1005    }
1006}
1007
1008/// Checks whether a file can only be read/written by the owner. It also allows more restrictive permissions, where only the owner can read it.
1009fn check_permissions(path: &PathBuf) -> Result<(), snarkvm::prelude::Error> {
1010    #[cfg(target_family = "unix")]
1011    {
1012        use std::os::unix::fs::PermissionsExt;
1013        ensure!(path.exists(), "The file '{path:?}' does not exist");
1014        crate::check_parent_permissions(path)?;
1015
1016        let permissions = path.metadata()?.permissions().mode();
1017        ensure!(
1018            matches!(permissions & 0o777, 0o400 | 0o600),
1019            "The file {} must be readable and writable only by the owner (0600)",
1020            path.display()
1021        );
1022    }
1023    Ok(())
1024}
1025
1026/// Loads or computes the genesis block.
1027fn load_or_compute_genesis<N: Network>(
1028    genesis_private_key: PrivateKey<N>,
1029    committee: Committee<N>,
1030    public_balances: indexmap::IndexMap<Address<N>, u64>,
1031    bonded_balances: indexmap::IndexMap<Address<N>, (Address<N>, Address<N>, u64)>,
1032    rng: &mut ChaChaRng,
1033) -> Result<Block<N>> {
1034    // Construct the preimage.
1035    let mut preimage = Vec::new();
1036
1037    // Input the network ID.
1038    preimage.extend(&N::ID.to_le_bytes());
1039    // Input the genesis coinbase target.
1040    preimage.extend(&to_bytes_le![N::GENESIS_COINBASE_TARGET]?);
1041    // Input the genesis proof target.
1042    preimage.extend(&to_bytes_le![N::GENESIS_PROOF_TARGET]?);
1043
1044    // Input the genesis private key, committee, and public balances.
1045    preimage.extend(genesis_private_key.to_bytes_le()?);
1046    preimage.extend(committee.to_bytes_le()?);
1047    preimage.extend(&to_bytes_le![public_balances.iter().collect::<Vec<(_, _)>>()]?);
1048    preimage.extend(&to_bytes_le![
1049        bonded_balances
1050            .iter()
1051            .flat_map(|(staker, (validator, withdrawal, amount))| to_bytes_le![staker, validator, withdrawal, amount])
1052            .collect::<Vec<_>>()
1053    ]?);
1054
1055    // Input the parameters' metadata based on network
1056    match N::ID {
1057        snarkvm::console::network::MainnetV0::ID => {
1058            preimage.extend(snarkvm::parameters::mainnet::BondValidatorVerifier::METADATA.as_bytes());
1059            preimage.extend(snarkvm::parameters::mainnet::BondPublicVerifier::METADATA.as_bytes());
1060            preimage.extend(snarkvm::parameters::mainnet::UnbondPublicVerifier::METADATA.as_bytes());
1061            preimage.extend(snarkvm::parameters::mainnet::ClaimUnbondPublicVerifier::METADATA.as_bytes());
1062            preimage.extend(snarkvm::parameters::mainnet::SetValidatorStateVerifier::METADATA.as_bytes());
1063            preimage.extend(snarkvm::parameters::mainnet::TransferPrivateVerifier::METADATA.as_bytes());
1064            preimage.extend(snarkvm::parameters::mainnet::TransferPublicVerifier::METADATA.as_bytes());
1065            preimage.extend(snarkvm::parameters::mainnet::TransferPrivateToPublicVerifier::METADATA.as_bytes());
1066            preimage.extend(snarkvm::parameters::mainnet::TransferPublicToPrivateVerifier::METADATA.as_bytes());
1067            preimage.extend(snarkvm::parameters::mainnet::FeePrivateVerifier::METADATA.as_bytes());
1068            preimage.extend(snarkvm::parameters::mainnet::FeePublicVerifier::METADATA.as_bytes());
1069            preimage.extend(snarkvm::parameters::mainnet::InclusionVerifier::METADATA.as_bytes());
1070        }
1071        snarkvm::console::network::TestnetV0::ID => {
1072            preimage.extend(snarkvm::parameters::testnet::BondValidatorVerifier::METADATA.as_bytes());
1073            preimage.extend(snarkvm::parameters::testnet::BondPublicVerifier::METADATA.as_bytes());
1074            preimage.extend(snarkvm::parameters::testnet::UnbondPublicVerifier::METADATA.as_bytes());
1075            preimage.extend(snarkvm::parameters::testnet::ClaimUnbondPublicVerifier::METADATA.as_bytes());
1076            preimage.extend(snarkvm::parameters::testnet::SetValidatorStateVerifier::METADATA.as_bytes());
1077            preimage.extend(snarkvm::parameters::testnet::TransferPrivateVerifier::METADATA.as_bytes());
1078            preimage.extend(snarkvm::parameters::testnet::TransferPublicVerifier::METADATA.as_bytes());
1079            preimage.extend(snarkvm::parameters::testnet::TransferPrivateToPublicVerifier::METADATA.as_bytes());
1080            preimage.extend(snarkvm::parameters::testnet::TransferPublicToPrivateVerifier::METADATA.as_bytes());
1081            preimage.extend(snarkvm::parameters::testnet::FeePrivateVerifier::METADATA.as_bytes());
1082            preimage.extend(snarkvm::parameters::testnet::FeePublicVerifier::METADATA.as_bytes());
1083            preimage.extend(snarkvm::parameters::testnet::InclusionVerifier::METADATA.as_bytes());
1084        }
1085        snarkvm::console::network::CanaryV0::ID => {
1086            preimage.extend(snarkvm::parameters::canary::BondValidatorVerifier::METADATA.as_bytes());
1087            preimage.extend(snarkvm::parameters::canary::BondPublicVerifier::METADATA.as_bytes());
1088            preimage.extend(snarkvm::parameters::canary::UnbondPublicVerifier::METADATA.as_bytes());
1089            preimage.extend(snarkvm::parameters::canary::ClaimUnbondPublicVerifier::METADATA.as_bytes());
1090            preimage.extend(snarkvm::parameters::canary::SetValidatorStateVerifier::METADATA.as_bytes());
1091            preimage.extend(snarkvm::parameters::canary::TransferPrivateVerifier::METADATA.as_bytes());
1092            preimage.extend(snarkvm::parameters::canary::TransferPublicVerifier::METADATA.as_bytes());
1093            preimage.extend(snarkvm::parameters::canary::TransferPrivateToPublicVerifier::METADATA.as_bytes());
1094            preimage.extend(snarkvm::parameters::canary::TransferPublicToPrivateVerifier::METADATA.as_bytes());
1095            preimage.extend(snarkvm::parameters::canary::FeePrivateVerifier::METADATA.as_bytes());
1096            preimage.extend(snarkvm::parameters::canary::FeePublicVerifier::METADATA.as_bytes());
1097            preimage.extend(snarkvm::parameters::canary::InclusionVerifier::METADATA.as_bytes());
1098        }
1099        _ => {
1100            // Unrecognized Network ID
1101            bail!("Unrecognized Network ID: {}", N::ID);
1102        }
1103    }
1104
1105    // Initialize the hasher.
1106    let hasher = snarkvm::console::algorithms::BHP256::<N>::setup("aleo.dev.block")?;
1107    // Compute the hash.
1108    // NOTE: this is a fast-to-compute but *IMPERFECT* identifier for the genesis block;
1109    //       to know the actual genesis block hash, you need to compute the block itself.
1110    let hash = hasher.hash(&preimage.to_bits_le())?.to_string();
1111
1112    // A closure to load the block.
1113    let load_block = |file_path| -> Result<Block<N>> {
1114        // Attempts to load the genesis block file locally.
1115        let buffer = std::fs::read(file_path)?;
1116        // Return the genesis block.
1117        Block::from_bytes_le(&buffer)
1118    };
1119
1120    // Construct the file path.
1121    let file_path = std::env::temp_dir().join(hash);
1122    // Check if the genesis block exists.
1123    if file_path.exists() {
1124        // If the block loads successfully, return it.
1125        if let Ok(block) = load_block(&file_path) {
1126            return Ok(block);
1127        }
1128    }
1129
1130    /* Otherwise, compute the genesis block and store it. */
1131
1132    // Initialize a new VM.
1133    let vm = VM::from(ConsensusStore::<N, ConsensusMemory<N>>::open(StorageMode::new_test(None))?)?;
1134    // Initialize the genesis block.
1135    let block = vm.genesis_quorum(&genesis_private_key, committee, public_balances, bonded_balances, rng)?;
1136    // Write the genesis block to the file.
1137    std::fs::write(&file_path, block.to_bytes_le()?)?;
1138    // Return the genesis block.
1139    Ok(block)
1140}
1141
1142// Resolve socket addresses (not URLs) in a host:port format compliant with C::getaddrinfo.
1143fn resolve_potential_hostnames(ip_or_hostname: &str) -> Result<SocketAddr> {
1144    let trimmed = ip_or_hostname.trim();
1145    // Perform some basic validity checks.
1146    if !trimmed.contains(':') {
1147        bail!(
1148            "The supplied trusted hostname or IP ('{trimmed}') is malformed: missing colon separating the host from the port"
1149        );
1150    }
1151    if trimmed.contains("://") {
1152        bail!("The supplied trusted hostname or IP ('{trimmed}') is malformed: URLs are not supported");
1153    }
1154    match trimmed.to_socket_addrs() {
1155        Ok(mut ip_iter) => {
1156            // A hostname might resolve to multiple IP addresses. We will use only the first one,
1157            // assuming this aligns with the user's expectations.
1158            let Some(ip) = ip_iter.next() else {
1159                bail!("The supplied trusted hostname ('{trimmed}') does not reference any ip.");
1160            };
1161            Ok(ip)
1162        }
1163        Err(e) => Err(anyhow!("The supplied trusted hostname or IP ('{trimmed}') is malformed: {e}")),
1164    }
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169    use super::*;
1170    use crate::commands::{CLI, Command};
1171    use snarkvm::prelude::MainnetV0;
1172
1173    use ureq::http;
1174
1175    type CurrentNetwork = MainnetV0;
1176
1177    #[test]
1178    fn test_parse_trusted_addrs() {
1179        let config = Start::try_parse_from(["snarkos", "--peers", ""].iter()).unwrap();
1180        assert!(config.parse_trusted_addrs(&config.peers).is_ok());
1181        assert!(config.parse_trusted_addrs(&config.peers).unwrap().is_empty());
1182
1183        let config = Start::try_parse_from(["snarkos", "--peers", "1.2.3.4:5"].iter()).unwrap();
1184        assert!(config.parse_trusted_addrs(&config.peers).is_ok());
1185        assert_eq!(config.parse_trusted_addrs(&config.peers).unwrap(), vec![
1186            SocketAddr::from_str("1.2.3.4:5").unwrap()
1187        ]);
1188
1189        let config = Start::try_parse_from(["snarkos", "--peers", "1.2.3.4:5,6.7.8.9:0"].iter()).unwrap();
1190        assert!(config.parse_trusted_addrs(&config.peers).is_ok());
1191        assert_eq!(config.parse_trusted_addrs(&config.peers).unwrap(), vec![
1192            SocketAddr::from_str("1.2.3.4:5").unwrap(),
1193            SocketAddr::from_str("6.7.8.9:0").unwrap()
1194        ]);
1195    }
1196
1197    #[test]
1198    fn test_parse_trusted_validators() {
1199        let config = Start::try_parse_from(["snarkos", "--validators", ""].iter()).unwrap();
1200        assert!(config.parse_trusted_addrs(&config.validators).is_ok());
1201        assert!(config.parse_trusted_addrs(&config.validators).unwrap().is_empty());
1202
1203        let config = Start::try_parse_from(["snarkos", "--validators", "1.2.3.4:5"].iter()).unwrap();
1204        assert!(config.parse_trusted_addrs(&config.validators).is_ok());
1205        assert_eq!(config.parse_trusted_addrs(&config.validators).unwrap(), vec![
1206            SocketAddr::from_str("1.2.3.4:5").unwrap()
1207        ]);
1208
1209        let config = Start::try_parse_from(["snarkos", "--validators", "1.2.3.4:5,6.7.8.9:0"].iter()).unwrap();
1210        assert!(config.parse_trusted_addrs(&config.validators).is_ok());
1211        assert_eq!(config.parse_trusted_addrs(&config.validators).unwrap(), vec![
1212            SocketAddr::from_str("1.2.3.4:5").unwrap(),
1213            SocketAddr::from_str("6.7.8.9:0").unwrap()
1214        ]);
1215    }
1216
1217    #[test]
1218    fn test_parse_log_filter() {
1219        // Ensure we cannot set, both, log-filter and verbosity
1220        let result = Start::try_parse_from(["snarkos", "--verbosity=5", "--log-filter=warn"].iter());
1221        assert!(result.is_err(), "Must not be able to set log-filter and verbosity at the same time");
1222
1223        // Ensure the values are set correctly.
1224        let config = Start::try_parse_from(["snarkos", "--verbosity=5"].iter()).unwrap();
1225        assert_eq!(config.verbosity, 5);
1226        let config = Start::try_parse_from(["snarkos", "--log-filter=snarkos=warn"].iter()).unwrap();
1227        assert_eq!(config.log_filter, Some("snarkos=warn".to_string()));
1228    }
1229
1230    #[test]
1231    fn test_parse_cdn() -> Result<()> {
1232        // Validator (Prod)
1233        let config = Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx"].iter()).unwrap();
1234        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1235        let config =
1236            Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx", "--cdn", "url"].iter())
1237                .unwrap();
1238        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1239        let config = Start::try_parse_from(["snarkos", "--validator", "--private-key", "aleo1xx", "--nocdn"].iter())?;
1240        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1241
1242        // Validator (Dev)
1243        let config =
1244            Start::try_parse_from(["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx"].iter()).unwrap();
1245        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1246        let config = Start::try_parse_from(
1247            ["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
1248        )
1249        .unwrap();
1250        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1251        let config = Start::try_parse_from(
1252            ["snarkos", "--dev", "0", "--validator", "--private-key", "aleo1xx", "--nocdn"].iter(),
1253        )?;
1254        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1255
1256        // Prover (Prod)
1257        let config = Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx"].iter())?;
1258        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1259        let config = Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx", "--cdn", "url"].iter())?;
1260        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1261        let config = Start::try_parse_from(["snarkos", "--prover", "--private-key", "aleo1xx", "--nocdn"].iter())?;
1262        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1263
1264        // Prover (Dev)
1265        let config =
1266            Start::try_parse_from(["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx"].iter()).unwrap();
1267        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1268        let config = Start::try_parse_from(
1269            ["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
1270        )
1271        .unwrap();
1272        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1273        let config =
1274            Start::try_parse_from(["snarkos", "--dev", "0", "--prover", "--private-key", "aleo1xx", "--nocdn"].iter())
1275                .unwrap();
1276        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1277
1278        // Client (Prod)
1279        let config = Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx"].iter()).unwrap();
1280        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1281        let config =
1282            Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx", "--cdn", "url"].iter()).unwrap();
1283        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1284        let config =
1285            Start::try_parse_from(["snarkos", "--client", "--private-key", "aleo1xx", "--nocdn"].iter()).unwrap();
1286        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1287
1288        // Client (Dev)
1289        let config =
1290            Start::try_parse_from(["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx"].iter()).unwrap();
1291        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1292        let config = Start::try_parse_from(
1293            ["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx", "--cdn", "url"].iter(),
1294        )
1295        .unwrap();
1296        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1297        let config =
1298            Start::try_parse_from(["snarkos", "--dev", "0", "--client", "--private-key", "aleo1xx", "--nocdn"].iter())
1299                .unwrap();
1300        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1301
1302        // Default (Prod)
1303        let config = Start::try_parse_from(["snarkos"].iter()).unwrap();
1304        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1305        let config = Start::try_parse_from(["snarkos", "--cdn", "url"].iter()).unwrap();
1306        assert!(config.parse_cdn::<CurrentNetwork>()?.is_some());
1307        let config = Start::try_parse_from(["snarkos", "--nocdn"].iter()).unwrap();
1308        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1309
1310        // Default (Dev)
1311        let config = Start::try_parse_from(["snarkos", "--dev", "0"].iter()).unwrap();
1312        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1313        let config = Start::try_parse_from(["snarkos", "--dev", "0", "--cdn", "url"].iter()).unwrap();
1314        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1315        let config = Start::try_parse_from(["snarkos", "--dev", "0", "--nocdn"].iter()).unwrap();
1316        assert!(config.parse_cdn::<CurrentNetwork>()?.is_none());
1317
1318        Ok(())
1319    }
1320
1321    #[test]
1322    fn test_parse_development_and_genesis() {
1323        let prod_genesis = Block::from_bytes_le(CurrentNetwork::genesis_bytes()).unwrap();
1324
1325        let mut trusted_peers = vec![];
1326        let mut trusted_validators = vec![];
1327        let mut config = Start::try_parse_from(["snarkos"].iter()).unwrap();
1328        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1329        let candidate_genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
1330        assert_eq!(trusted_peers.len(), 0);
1331        assert_eq!(trusted_validators.len(), 0);
1332        assert_eq!(candidate_genesis, prod_genesis);
1333
1334        let _config = Start::try_parse_from(["snarkos", "--dev", ""].iter()).unwrap_err();
1335
1336        // Validator dev mode with default settings.
1337        let mut trusted_peers = vec![];
1338        let mut trusted_validators = vec![];
1339        let mut config = Start::try_parse_from(["snarkos", "--dev", "1", "--validator"].iter()).unwrap();
1340        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1341        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3031").unwrap()));
1342        assert_eq!(trusted_validators.len(), 3);
1343
1344        // Validator dev mode with `--rest` flag.
1345        let mut trusted_peers = vec![];
1346        let mut trusted_validators = vec![];
1347        let mut config =
1348            Start::try_parse_from(["snarkos", "--dev", "1", "--rest", "127.0.0.1:8080", "--validator"].iter()).unwrap();
1349        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1350        assert_eq!(config.rest, Some(SocketAddr::from_str("127.0.0.1:8080").unwrap()));
1351        assert_eq!(trusted_validators.len(), 3);
1352
1353        // Validator dev mode with `--norest` flag.
1354        let mut trusted_peers = vec![];
1355        let mut trusted_validators = vec![];
1356        let mut config = Start::try_parse_from(["snarkos", "--dev", "1", "--norest", "--validator"].iter()).unwrap();
1357        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1358        assert!(config.rest.is_none());
1359        assert_eq!(trusted_validators.len(), 3);
1360
1361        // Client dev node.
1362        let mut trusted_peers = vec![];
1363        let mut trusted_validators = vec![];
1364        let mut config = Start::try_parse_from(["snarkos", "--dev", "5"].iter()).unwrap();
1365        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1366        let expected_genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
1367        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4135").unwrap()));
1368        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3035").unwrap()));
1369        assert_eq!(trusted_peers.len(), 2);
1370        assert_eq!(trusted_validators.len(), 0);
1371        assert!(!config.validator);
1372        assert!(!config.prover);
1373        assert!(!config.client);
1374        assert_ne!(expected_genesis, prod_genesis);
1375
1376        // Validator dev node with `--private-key` flag.
1377        let mut trusted_peers = vec![];
1378        let mut trusted_validators = vec![];
1379        let mut config =
1380            Start::try_parse_from(["snarkos", "--dev", "1", "--validator", "--private-key", ""].iter()).unwrap();
1381        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1382        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
1383        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4131").unwrap()));
1384        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3031").unwrap()));
1385        assert_eq!(trusted_peers.len(), 0);
1386        assert_eq!(trusted_validators.len(), 3);
1387        assert!(config.validator);
1388        assert!(!config.prover);
1389        assert!(!config.client);
1390        assert_eq!(genesis, expected_genesis);
1391
1392        // Prover dev node with `--private-key` flag.
1393        let mut trusted_peers = vec![];
1394        let mut trusted_validators = vec![];
1395        let mut config =
1396            Start::try_parse_from(["snarkos", "--dev", "6", "--prover", "--private-key", ""].iter()).unwrap();
1397        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1398        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
1399        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4136").unwrap()));
1400        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3036").unwrap()));
1401        assert_eq!(trusted_peers.len(), 2);
1402        assert_eq!(trusted_validators.len(), 0);
1403        assert!(!config.validator);
1404        assert!(config.prover);
1405        assert!(!config.client);
1406        assert_eq!(genesis, expected_genesis);
1407
1408        // Client dev node with `--private-key` flag.
1409        let mut trusted_peers = vec![];
1410        let mut trusted_validators = vec![];
1411        let mut config =
1412            Start::try_parse_from(["snarkos", "--dev", "10", "--client", "--private-key", ""].iter()).unwrap();
1413        config.parse_development(&mut trusted_peers, &mut trusted_validators).unwrap();
1414        let genesis = config.parse_genesis::<CurrentNetwork>().unwrap();
1415        assert_eq!(config.node, Some(SocketAddr::from_str("0.0.0.0:4140").unwrap()));
1416        assert_eq!(config.rest, Some(SocketAddr::from_str("0.0.0.0:3040").unwrap()));
1417        assert_eq!(trusted_peers.len(), 2);
1418        assert_eq!(trusted_validators.len(), 0);
1419        assert!(!config.validator);
1420        assert!(!config.prover);
1421        assert!(config.client);
1422        assert_eq!(genesis, expected_genesis);
1423    }
1424
1425    /// Tests that you cannot pass the `--dev-num-clients` flag while also passing the `--peers` flag.
1426    #[test]
1427    fn test_parse_development_num_clients_and_peers() {
1428        let result = Start::try_parse_from(
1429            ["snarkos", "--validator", "--dev", "1", "--peers", "127.0.0.1:3030", "--dev-num-clients", "1"].iter(),
1430        );
1431        assert!(result.is_err());
1432    }
1433
1434    #[test]
1435    fn clap_snarkos_start() {
1436        let arg_vec = vec![
1437            "snarkos",
1438            "start",
1439            "--nodisplay",
1440            "--dev",
1441            "2",
1442            "--validator",
1443            "--private-key",
1444            "PRIVATE_KEY",
1445            "--cdn",
1446            "CDN",
1447            "--peers",
1448            "IP1,IP2,IP3",
1449            "--validators",
1450            "IP1,IP2,IP3",
1451            "--rest",
1452            "127.0.0.1:3030",
1453        ];
1454        let cli = CLI::parse_from(arg_vec);
1455
1456        let Command::Start(start) = cli.command else {
1457            panic!("Unexpected result of clap parsing!");
1458        };
1459
1460        assert!(start.nodisplay);
1461        assert_eq!(start.dev, Some(2));
1462        assert!(start.validator);
1463        assert_eq!(start.private_key.as_deref(), Some("PRIVATE_KEY"));
1464        assert_eq!(start.cdn, Some(http::Uri::try_from("CDN").unwrap()));
1465        assert_eq!(start.rest, Some("127.0.0.1:3030".parse().unwrap()));
1466        assert_eq!(start.network, 0);
1467        assert_eq!(start.peers, Some("IP1,IP2,IP3".to_string()));
1468        assert_eq!(start.validators, Some("IP1,IP2,IP3".to_string()));
1469    }
1470
1471    /// Ensure two clients do not connect to the same validators.
1472    #[test]
1473    fn test_parse_development_client_validators() {
1474        let mut client1_config =
1475            Start::try_parse_from(["snarkos", "--dev", "10", "--client", "--private-key", ""].iter()).unwrap();
1476        let mut trusted_peers1 = vec![];
1477        let mut trusted_validators1 = vec![];
1478        client1_config.parse_development(&mut trusted_peers1, &mut trusted_validators1).unwrap();
1479
1480        let mut client2_config =
1481            Start::try_parse_from(["snarkos", "--dev", "11", "--client", "--private-key", ""].iter()).unwrap();
1482        let mut trusted_peers2 = vec![];
1483        let mut trusted_validators2 = vec![];
1484        client2_config.parse_development(&mut trusted_peers2, &mut trusted_validators2).unwrap();
1485
1486        assert_ne!(trusted_peers1, trusted_peers2);
1487    }
1488
1489    #[test]
1490    fn parse_peers_when_ips() {
1491        let arg_vec = vec!["snarkos", "start", "--peers", "127.0.0.1:3030,127.0.0.2:3030"];
1492        let cli = CLI::parse_from(arg_vec);
1493
1494        if let Command::Start(start) = cli.command {
1495            let peers = start.parse_trusted_addrs(&start.peers);
1496            assert!(peers.is_ok());
1497            assert_eq!(peers.unwrap().len(), 2, "Expected two peers");
1498        } else {
1499            panic!("Unexpected result of clap parsing!");
1500        }
1501    }
1502
1503    #[test]
1504    fn parse_peers_when_hostnames() {
1505        let arg_vec = vec!["snarkos", "start", "--peers", "www.example.com:4130,www.google.com:4130"];
1506        let cli = CLI::parse_from(arg_vec);
1507
1508        if let Command::Start(start) = cli.command {
1509            let peers = start.parse_trusted_addrs(&start.peers);
1510            assert!(peers.is_ok());
1511            assert_eq!(peers.unwrap().len(), 2, "Expected two peers");
1512        } else {
1513            panic!("Unexpected result of clap parsing!");
1514        }
1515    }
1516
1517    #[test]
1518    fn parse_peers_when_mixed_and_with_whitespaces() {
1519        let arg_vec = vec!["snarkos", "start", "--peers", "  127.0.0.1:3030,  www.google.com:4130 "];
1520        let cli = CLI::parse_from(arg_vec);
1521
1522        if let Command::Start(start) = cli.command {
1523            let peers = start.parse_trusted_addrs(&start.peers);
1524            assert!(peers.is_ok());
1525            assert_eq!(peers.unwrap().len(), 2, "Expected two peers");
1526        } else {
1527            panic!("Unexpected result of clap parsing!");
1528        }
1529    }
1530
1531    #[test]
1532    fn parse_peers_when_unknown_hostname_gracefully() {
1533        let arg_vec = vec!["snarkos", "start", "--peers", "banana.cake.eafafdaeefasdfasd.com"];
1534        let cli = CLI::parse_from(arg_vec);
1535
1536        if let Command::Start(start) = cli.command {
1537            assert!(start.parse_trusted_addrs(&start.peers).is_err());
1538        } else {
1539            panic!("Unexpected result of clap parsing!");
1540        }
1541    }
1542}