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
// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
// This file is part of the HotShot repository.

// You should have received a copy of the MIT License
// along with the HotShot repository. If not, see <https://mit-license.org/>.

use std::{
    collections::HashSet,
    env, fs,
    net::SocketAddr,
    num::NonZeroUsize,
    ops::Range,
    path::{Path, PathBuf},
    time::Duration,
    vec,
};

use clap::ValueEnum;
use hotshot_types::{
    constants::REQUEST_DATA_DELAY, traits::signature_key::SignatureKey, ExecutionType,
    HotShotConfig, PeerConfig, ValidatorConfig,
};
use libp2p::{Multiaddr, PeerId};
use serde_inline_default::serde_inline_default;
use surf_disco::Url;
use thiserror::Error;
use toml;
use tracing::{error, info};
use vec1::Vec1;

use crate::client::OrchestratorClient;

/// Configuration describing a libp2p node
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct Libp2pConfig {
    /// The bootstrap nodes to connect to (multiaddress, serialized public key)
    pub bootstrap_nodes: Vec<(PeerId, Multiaddr)>,
}

/// configuration for a web server
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct WebServerConfig {
    /// the url to run on
    pub url: Url,
    /// the time to wait between polls
    pub wait_between_polls: Duration,
}

/// configuration for combined network
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct CombinedNetworkConfig {
    /// delay duration before sending a message through the secondary network
    pub delay_duration: Duration,
}

/// a network configuration error
#[derive(Error, Debug)]
pub enum NetworkConfigError {
    /// Failed to read NetworkConfig from file
    #[error("Failed to read NetworkConfig from file")]
    ReadFromFileError(std::io::Error),
    /// Failed to deserialize loaded NetworkConfig
    #[error("Failed to deserialize loaded NetworkConfig")]
    DeserializeError(serde_json::Error),
    /// Failed to write NetworkConfig to file
    #[error("Failed to write NetworkConfig to file")]
    WriteToFileError(std::io::Error),
    /// Failed to serialize NetworkConfig
    #[error("Failed to serialize NetworkConfig")]
    SerializeError(serde_json::Error),
    /// Failed to recursively create path to NetworkConfig
    #[error("Failed to recursively create path to NetworkConfig")]
    FailedToCreatePath(std::io::Error),
}

#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize, Default, ValueEnum)]
/// configuration for builder type to use
pub enum BuilderType {
    /// Use external builder, [config.builder_url] must be
    /// set to correct builder address
    External,
    #[default]
    /// Simple integrated builder will be started and used by each hotshot node
    Simple,
    /// Random integrated builder will be started and used by each hotshot node
    Random,
}

/// Options controlling how the random builder generates blocks
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct RandomBuilderConfig {
    /// How many transactions to include in a block
    pub txn_in_block: u64,
    /// How many blocks to generate per second
    pub blocks_per_second: u32,
    /// Range of how big a transaction can be (in bytes)
    pub txn_size: Range<u32>,
}

impl Default for RandomBuilderConfig {
    fn default() -> Self {
        Self {
            txn_in_block: 100,
            blocks_per_second: 1,
            txn_size: 20..100,
        }
    }
}

/// a network configuration
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(bound(deserialize = ""))]
pub struct NetworkConfig<KEY: SignatureKey> {
    /// number of views to run
    pub rounds: usize,
    /// whether DA membership is determined by index.
    /// if true, the first k nodes to register form the DA committee
    /// if false, DA membership is requested by the nodes
    pub indexed_da: bool,
    /// number of transactions per view
    pub transactions_per_round: usize,
    /// password to have the orchestrator start the network,
    /// regardless of the number of nodes connected.
    pub manual_start_password: Option<String>,
    /// number of bootstrap nodes
    pub num_bootrap: usize,
    /// timeout before starting the next view
    pub next_view_timeout: u64,
    /// timeout before starting next view sync round
    pub view_sync_timeout: Duration,
    /// The maximum amount of time a leader can wait to get a block from a builder
    pub builder_timeout: Duration,
    /// time to wait until we request data associated with a proposal
    pub data_request_delay: Duration,
    /// global index of node (for testing purposes a uid)
    pub node_index: u64,
    /// unique seed (for randomness? TODO)
    pub seed: [u8; 32],
    /// size of transactions
    pub transaction_size: usize,
    /// delay before beginning consensus
    pub start_delay_seconds: u64,
    /// name of the key type (for debugging)
    pub key_type_name: String,
    /// the libp2p config
    pub libp2p_config: Option<Libp2pConfig>,
    /// the hotshot config
    pub config: HotShotConfig<KEY>,
    /// The address for the Push CDN's "marshal", A.K.A. load balancer
    pub cdn_marshal_address: Option<String>,
    /// combined network config
    pub combined_network_config: Option<CombinedNetworkConfig>,
    /// the commit this run is based on
    pub commit_sha: String,
    /// builder to use
    pub builder: BuilderType,
    /// random builder config
    pub random_builder: Option<RandomBuilderConfig>,
    /// The list of public keys that are allowed to connect to the orchestrator
    pub public_keys: HashSet<KEY>,
    /// Whether or not to disable registration verification.
    pub enable_registration_verification: bool,
}

/// the source of the network config
pub enum NetworkConfigSource {
    /// we source the network configuration from the orchestrator
    Orchestrator,
    /// we source the network configuration from a config file on disk
    File,
}

impl<K: SignatureKey> NetworkConfig<K> {
    /// Asynchronously retrieves a `NetworkConfig` either from a file or from an orchestrator.
    ///
    /// This function takes an `OrchestratorClient`, an optional file path, and Libp2p-specific parameters.
    ///
    /// If a file path is provided, the function will first attempt to load the `NetworkConfig` from the file.
    /// If the file does not exist or cannot be read, the function will fall back to retrieving the `NetworkConfig` from the orchestrator.
    /// In this case, if the path to the file does not exist, it will be created.
    /// The retrieved `NetworkConfig` is then saved back to the file for future use.
    ///
    /// If no file path is provided, the function will directly retrieve the `NetworkConfig` from the orchestrator.
    ///
    /// # Errors
    /// If we were unable to load the configuration.
    ///
    /// # Arguments
    ///
    /// * `client` - An `OrchestratorClient` used to retrieve the `NetworkConfig` from the orchestrator.
    /// * `identity` - A string representing the identity for which to retrieve the `NetworkConfig`.
    /// * `file` - An optional string representing the path to the file from which to load the `NetworkConfig`.
    /// * `libp2p_address` - An optional address specifying where other Libp2p nodes can reach us
    /// * `libp2p_public_key` - The public key in which other Libp2p nodes can reach us with
    ///
    /// # Returns
    ///
    /// This function returns a tuple containing a `NetworkConfig` and a `NetworkConfigSource`. The `NetworkConfigSource` indicates whether the `NetworkConfig` was loaded from a file or retrieved from the orchestrator.
    pub async fn from_file_or_orchestrator(
        client: &OrchestratorClient,
        file: Option<String>,
        libp2p_address: Option<SocketAddr>,
        libp2p_public_key: Option<PeerId>,
    ) -> anyhow::Result<(NetworkConfig<K>, NetworkConfigSource)> {
        if let Some(file) = file {
            info!("Retrieving config from the file");
            // if we pass in file, try there first
            match Self::from_file(file.clone()) {
                Ok(config) => Ok((config, NetworkConfigSource::File)),
                Err(e) => {
                    // fallback to orchestrator
                    error!("{e}, falling back to orchestrator");

                    let config = client
                        .get_config_without_peer(libp2p_address, libp2p_public_key)
                        .await?;

                    // save to file if we fell back
                    if let Err(e) = config.to_file(file) {
                        error!("{e}");
                    };

                    Ok((config, NetworkConfigSource::File))
                }
            }
        } else {
            info!("Retrieving config from the orchestrator");

            // otherwise just get from orchestrator
            Ok((
                client
                    .get_config_without_peer(libp2p_address, libp2p_public_key)
                    .await?,
                NetworkConfigSource::Orchestrator,
            ))
        }
    }

    /// Get a temporary node index for generating a validator config
    pub async fn generate_init_validator_config(
        client: &OrchestratorClient,
        is_da: bool,
    ) -> ValidatorConfig<K> {
        // This cur_node_index is only used for key pair generation, it's not bound with the node,
        // lather the node with the generated key pair will get a new node_index from orchestrator.
        let cur_node_index = client.get_node_index_for_init_validator_config().await;
        ValidatorConfig::generated_from_seed_indexed([0u8; 32], cur_node_index.into(), 1, is_da)
    }

    /// Asynchronously retrieves a `NetworkConfig` from an orchestrator.
    /// The retrieved one includes correct `node_index` and peer's public config.
    ///
    /// # Errors
    /// If we are unable to get the configuration from the orchestrator
    pub async fn get_complete_config(
        client: &OrchestratorClient,
        my_own_validator_config: ValidatorConfig<K>,
        libp2p_address: Option<SocketAddr>,
        libp2p_public_key: Option<PeerId>,
    ) -> anyhow::Result<(NetworkConfig<K>, NetworkConfigSource)> {
        // get the configuration from the orchestrator
        let run_config: NetworkConfig<K> = client
            .post_and_wait_all_public_keys::<K>(
                my_own_validator_config,
                libp2p_address,
                libp2p_public_key,
            )
            .await;

        info!(
            "Retrieved config; our node index is {}. DA committee member: {}",
            run_config.node_index, run_config.config.my_own_validator_config.is_da
        );
        Ok((run_config, NetworkConfigSource::Orchestrator))
    }

    /// Loads a `NetworkConfig` from a file.
    ///
    /// This function takes a file path as a string, reads the file, and then deserializes the contents into a `NetworkConfig`.
    ///
    /// # Arguments
    ///
    /// * `file` - A string representing the path to the file from which to load the `NetworkConfig`.
    ///
    /// # Returns
    ///
    /// This function returns a `Result` that contains a `NetworkConfig` if the file was successfully read and deserialized, or a `NetworkConfigError` if an error occurred.
    ///
    /// # Errors
    ///
    /// This function will return an error if the file cannot be read or if the contents cannot be deserialized into a `NetworkConfig`.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use hotshot_orchestrator::config::NetworkConfig;
    /// # use hotshot_types::signature_key::BLSPubKey;
    /// // # use hotshot::traits::election::static_committee::StaticElectionConfig;
    /// let file = "/path/to/my/config".to_string();
    /// // NOTE: broken due to staticelectionconfig not being importable
    /// // cannot import staticelectionconfig from hotshot without creating circular dependency
    /// // making this work probably involves the `types` crate implementing a dummy
    /// // electionconfigtype just ot make this example work
    /// let config = NetworkConfig::<BLSPubKey, StaticElectionConfig>::from_file(file).unwrap();
    /// ```
    pub fn from_file(file: String) -> Result<Self, NetworkConfigError> {
        // read from file
        let data = match fs::read(file) {
            Ok(data) => data,
            Err(e) => {
                return Err(NetworkConfigError::ReadFromFileError(e));
            }
        };

        // deserialize
        match serde_json::from_slice(&data) {
            Ok(data) => Ok(data),
            Err(e) => Err(NetworkConfigError::DeserializeError(e)),
        }
    }

    /// Serializes the `NetworkConfig` and writes it to a file.
    ///
    /// This function takes a file path as a string, serializes the `NetworkConfig` into JSON format using `serde_json` and then writes the serialized data to the file.
    ///
    /// # Arguments
    ///
    /// * `file` - A string representing the path to the file where the `NetworkConfig` should be saved.
    ///
    /// # Returns
    ///
    /// This function returns a `Result` that contains `()` if the `NetworkConfig` was successfully serialized and written to the file, or a `NetworkConfigError` if an error occurred.
    ///
    /// # Errors
    ///
    /// This function will return an error if the `NetworkConfig` cannot be serialized or if the file cannot be written.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use hotshot_orchestrator::config::NetworkConfig;
    /// let file = "/path/to/my/config".to_string();
    /// let config = NetworkConfig::from_file(file);
    /// config.to_file(file).unwrap();
    /// ```
    pub fn to_file(&self, file: String) -> Result<(), NetworkConfigError> {
        // ensure the directory containing the config file exists
        if let Some(dir) = Path::new(&file).parent() {
            if let Err(e) = fs::create_dir_all(dir) {
                return Err(NetworkConfigError::FailedToCreatePath(e));
            }
        }

        // serialize
        let serialized = match serde_json::to_string_pretty(self) {
            Ok(data) => data,
            Err(e) => {
                return Err(NetworkConfigError::SerializeError(e));
            }
        };

        // write to file
        match fs::write(file, serialized) {
            Ok(()) => Ok(()),
            Err(e) => Err(NetworkConfigError::WriteToFileError(e)),
        }
    }
}

impl<K: SignatureKey> Default for NetworkConfig<K> {
    fn default() -> Self {
        Self {
            rounds: ORCHESTRATOR_DEFAULT_NUM_ROUNDS,
            indexed_da: true,
            transactions_per_round: ORCHESTRATOR_DEFAULT_TRANSACTIONS_PER_ROUND,
            node_index: 0,
            seed: [0u8; 32],
            transaction_size: ORCHESTRATOR_DEFAULT_TRANSACTION_SIZE,
            manual_start_password: None,
            libp2p_config: None,
            config: HotShotConfigFile::default().into(),
            start_delay_seconds: 60,
            key_type_name: std::any::type_name::<K>().to_string(),
            cdn_marshal_address: None,
            combined_network_config: None,
            next_view_timeout: 10,
            view_sync_timeout: Duration::from_secs(2),
            num_bootrap: 5,
            builder_timeout: Duration::from_secs(10),
            data_request_delay: Duration::from_millis(2500),
            commit_sha: String::new(),
            builder: BuilderType::default(),
            random_builder: None,
            public_keys: HashSet::new(),
            enable_registration_verification: true,
        }
    }
}

/// a network config stored in a file
#[serde_inline_default]
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
#[serde(bound(deserialize = ""))]
pub struct NetworkConfigFile<KEY: SignatureKey> {
    /// number of views to run
    #[serde_inline_default(ORCHESTRATOR_DEFAULT_NUM_ROUNDS)]
    pub rounds: usize,
    /// number of views to run
    #[serde(default)]
    pub indexed_da: bool,
    /// number of transactions per view
    #[serde_inline_default(ORCHESTRATOR_DEFAULT_TRANSACTIONS_PER_ROUND)]
    pub transactions_per_round: usize,
    /// password to have the orchestrator start the network,
    /// regardless of the number of nodes connected.
    #[serde(default)]
    pub manual_start_password: Option<String>,
    /// global index of node (for testing purposes a uid)
    #[serde(default)]
    pub node_index: u64,
    /// unique seed (for randomness? TODO)
    #[serde(default)]
    pub seed: [u8; 32],
    /// size of transactions
    #[serde_inline_default(ORCHESTRATOR_DEFAULT_TRANSACTION_SIZE)]
    pub transaction_size: usize,
    /// delay before beginning consensus
    #[serde_inline_default(ORCHESTRATOR_DEFAULT_START_DELAY_SECONDS)]
    pub start_delay_seconds: u64,
    /// the hotshot config file
    #[serde(default)]
    pub config: HotShotConfigFile<KEY>,
    /// The address of the Push CDN's "marshal", A.K.A. load balancer
    #[serde(default)]
    pub cdn_marshal_address: Option<String>,
    /// combined network config
    #[serde(default)]
    pub combined_network_config: Option<CombinedNetworkConfig>,
    /// builder to use
    #[serde(default)]
    pub builder: BuilderType,
    /// random builder configuration
    #[serde(default)]
    pub random_builder: Option<RandomBuilderConfig>,
    /// The list of public keys that are allowed to connect to the orchestrator
    #[serde(default)]
    pub public_keys: HashSet<KEY>,
    /// Whether or not to disable registration verification.
    #[serde(default)]
    pub enable_registration_verification: bool,
}

impl<K: SignatureKey> From<NetworkConfigFile<K>> for NetworkConfig<K> {
    fn from(val: NetworkConfigFile<K>) -> Self {
        NetworkConfig {
            rounds: val.rounds,
            indexed_da: val.indexed_da,
            transactions_per_round: val.transactions_per_round,
            node_index: 0,
            num_bootrap: val.config.num_bootstrap,
            manual_start_password: val.manual_start_password,
            next_view_timeout: val.config.next_view_timeout,
            view_sync_timeout: val.config.view_sync_timeout,
            builder_timeout: val.config.builder_timeout,
            data_request_delay: val
                .config
                .data_request_delay
                .unwrap_or(Duration::from_millis(REQUEST_DATA_DELAY)),
            seed: val.seed,
            transaction_size: val.transaction_size,
            libp2p_config: Some(Libp2pConfig {
                bootstrap_nodes: Vec::new(),
            }),
            config: val.config.into(),
            key_type_name: std::any::type_name::<K>().to_string(),
            start_delay_seconds: val.start_delay_seconds,
            cdn_marshal_address: val.cdn_marshal_address,
            combined_network_config: val.combined_network_config,
            commit_sha: String::new(),
            builder: val.builder,
            random_builder: val.random_builder,
            public_keys: val.public_keys,
            enable_registration_verification: val.enable_registration_verification,
        }
    }
}

/// Default builder URL, used as placeholder
fn default_builder_urls() -> Vec1<Url> {
    vec1::vec1![Url::parse("http://0.0.0.0:3311").unwrap()]
}

/// Holds configuration for a `HotShot`
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(bound(deserialize = ""))]
pub struct HotShotConfigFile<KEY: SignatureKey> {
    /// The proportion of nodes required before the orchestrator issues the ready signal,
    /// expressed as (numerator, denominator)
    pub start_threshold: (u64, u64),
    /// Total number of staked nodes in the network
    pub num_nodes_with_stake: NonZeroUsize,
    #[serde(skip)]
    /// My own public key, secret key, stake value
    pub my_own_validator_config: ValidatorConfig<KEY>,
    #[serde(skip)]
    /// The known nodes' public key and stake value
    pub known_nodes_with_stake: Vec<PeerConfig<KEY>>,
    #[serde(skip)]
    /// The known DA nodes' public key and stake values
    pub known_da_nodes: Vec<PeerConfig<KEY>>,
    #[serde(skip)]
    /// The known non-staking nodes'
    pub known_nodes_without_stake: Vec<KEY>,
    /// Number of staking DA nodes
    pub staked_da_nodes: usize,
    /// Number of fixed leaders for GPU VID
    pub fixed_leader_for_gpuvid: usize,
    /// Base duration for next-view timeout, in milliseconds
    pub next_view_timeout: u64,
    /// Duration for view sync round timeout
    pub view_sync_timeout: Duration,
    /// The exponential backoff ration for the next-view timeout
    pub timeout_ratio: (u64, u64),
    /// The delay a leader inserts before starting pre-commit, in milliseconds
    pub round_start_delay: u64,
    /// Delay after init before starting consensus, in milliseconds
    pub start_delay: u64,
    /// Number of network bootstrap nodes
    pub num_bootstrap: usize,
    /// The maximum amount of time a leader can wait to get a block from a builder
    pub builder_timeout: Duration,
    /// Time to wait until we request data associated with a proposal
    pub data_request_delay: Option<Duration>,
    /// Builder API base URL
    #[serde(default = "default_builder_urls")]
    pub builder_urls: Vec1<Url>,
    /// Upgrade config
    pub upgrade: UpgradeConfig,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(bound(deserialize = ""))]
/// Holds configuration for the upgrade task.
pub struct UpgradeConfig {
    /// View to start proposing an upgrade
    pub start_proposing_view: u64,
    /// View to stop proposing an upgrade. To prevent proposing an upgrade, set stop_proposing_view <= start_proposing_view.
    pub stop_proposing_view: u64,
    /// View to start voting on an upgrade
    pub start_voting_view: u64,
    /// View to stop voting on an upgrade. To prevent voting on an upgrade, set stop_voting_view <= start_voting_view.
    pub stop_voting_view: u64,
    /// Unix time in seconds at which we start proposing an upgrade
    pub start_proposing_time: u64,
    /// Unix time in seconds at which we stop proposing an upgrade. To prevent proposing an upgrade, set stop_proposing_time <= start_proposing_time.
    pub stop_proposing_time: u64,
    /// Unix time in seconds at which we start voting on an upgrade
    pub start_voting_time: u64,
    /// Unix time in seconds at which we stop voting on an upgrade. To prevent voting on an upgrade, set stop_voting_time <= start_voting_time.
    pub stop_voting_time: u64,
}

// Explicitly implementing `Default` for clarity.
#[allow(clippy::derivable_impls)]
impl Default for UpgradeConfig {
    fn default() -> Self {
        UpgradeConfig {
            start_proposing_view: u64::MAX,
            stop_proposing_view: 0,
            start_voting_view: u64::MAX,
            stop_voting_view: 0,
            start_proposing_time: u64::MAX,
            stop_proposing_time: 0,
            start_voting_time: u64::MAX,
            stop_voting_time: 0,
        }
    }
}

/// Holds configuration for a validator node
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
#[serde(bound(deserialize = ""))]
pub struct ValidatorConfigFile {
    /// The validator's seed
    pub seed: [u8; 32],
    /// The validator's index, which can be treated as another input to the seed
    pub node_id: u64,
    // The validator's stake, commented for now
    // pub stake_value: u64,
    /// Whether or not we are DA
    pub is_da: bool,
}

impl ValidatorConfigFile {
    /// read the validator config from a file
    /// # Panics
    /// Panics if unable to get the current working directory
    pub fn from_file(dir_str: &str) -> Self {
        let current_working_dir = match env::current_dir() {
            Ok(dir) => dir,
            Err(e) => {
                error!("get_current_working_dir error: {:?}", e);
                PathBuf::from("")
            }
        };
        let filename =
            current_working_dir.into_os_string().into_string().unwrap() + "/../../" + dir_str;
        match fs::read_to_string(filename.clone()) {
            // If successful return the files text as `contents`.
            Ok(contents) => {
                let data: ValidatorConfigFile = match toml::from_str(&contents) {
                    // If successful, return data as `Data` struct.
                    // `d` is a local variable.
                    Ok(d) => d,
                    // Handle the `error` case.
                    Err(e) => {
                        // Write `msg` to `stderr`.
                        error!("Unable to load data from `{}`: {}", filename, e);
                        ValidatorConfigFile::default()
                    }
                };
                data
            }
            // Handle the `error` case.
            Err(e) => {
                // Write `msg` to `stderr`.
                error!("Could not read file `{}`: {}", filename, e);
                ValidatorConfigFile::default()
            }
        }
    }
}

impl<KEY: SignatureKey> From<HotShotConfigFile<KEY>> for HotShotConfig<KEY> {
    fn from(val: HotShotConfigFile<KEY>) -> Self {
        HotShotConfig {
            execution_type: ExecutionType::Continuous,
            start_threshold: val.start_threshold,
            num_nodes_with_stake: val.num_nodes_with_stake,
            known_da_nodes: val.known_da_nodes,
            known_nodes_with_stake: val.known_nodes_with_stake,
            known_nodes_without_stake: val.known_nodes_without_stake,
            my_own_validator_config: val.my_own_validator_config,
            da_staked_committee_size: val.staked_da_nodes,
            fixed_leader_for_gpuvid: val.fixed_leader_for_gpuvid,
            next_view_timeout: val.next_view_timeout,
            view_sync_timeout: val.view_sync_timeout,
            timeout_ratio: val.timeout_ratio,
            round_start_delay: val.round_start_delay,
            start_delay: val.start_delay,
            num_bootstrap: val.num_bootstrap,
            builder_timeout: val.builder_timeout,
            data_request_delay: val
                .data_request_delay
                .unwrap_or(Duration::from_millis(REQUEST_DATA_DELAY)),
            builder_urls: val.builder_urls,
            start_proposing_view: val.upgrade.start_proposing_view,
            stop_proposing_view: val.upgrade.stop_proposing_view,
            start_voting_view: val.upgrade.start_voting_view,
            stop_voting_view: val.upgrade.stop_voting_view,
            start_proposing_time: val.upgrade.start_proposing_time,
            stop_proposing_time: val.upgrade.stop_proposing_time,
            start_voting_time: val.upgrade.start_voting_time,
            stop_voting_time: val.upgrade.stop_voting_time,
        }
    }
}
/// default number of rounds to run
pub const ORCHESTRATOR_DEFAULT_NUM_ROUNDS: usize = 100;
/// default number of transactions per round
pub const ORCHESTRATOR_DEFAULT_TRANSACTIONS_PER_ROUND: usize = 10;
/// default size of transactions
pub const ORCHESTRATOR_DEFAULT_TRANSACTION_SIZE: usize = 100;
/// default delay before beginning consensus
pub const ORCHESTRATOR_DEFAULT_START_DELAY_SECONDS: u64 = 60;

impl<K: SignatureKey> From<ValidatorConfigFile> for ValidatorConfig<K> {
    fn from(val: ValidatorConfigFile) -> Self {
        // here stake_value is set to 1, since we don't input stake_value from ValidatorConfigFile for now
        ValidatorConfig::generated_from_seed_indexed(val.seed, val.node_id, 1, val.is_da)
    }
}
impl<KEY: SignatureKey> From<ValidatorConfigFile> for HotShotConfig<KEY> {
    fn from(value: ValidatorConfigFile) -> Self {
        let mut config: HotShotConfig<KEY> = HotShotConfigFile::default().into();
        config.my_own_validator_config = value.into();
        config
    }
}

impl<KEY: SignatureKey> Default for HotShotConfigFile<KEY> {
    fn default() -> Self {
        // The default number of nodes is 5
        let staked_da_nodes: usize = 5;

        // Aggregate the DA nodes
        let mut known_da_nodes = Vec::new();

        let gen_known_nodes_with_stake = (0..10)
            .map(|node_id| {
                let mut cur_validator_config: ValidatorConfig<KEY> =
                    ValidatorConfig::generated_from_seed_indexed([0u8; 32], node_id, 1, false);

                // Add to DA nodes based on index
                if node_id < staked_da_nodes as u64 {
                    known_da_nodes.push(cur_validator_config.public_config());
                    cur_validator_config.is_da = true;
                }

                cur_validator_config.public_config()
            })
            .collect();

        Self {
            num_nodes_with_stake: NonZeroUsize::new(10).unwrap(),
            start_threshold: (1, 1),
            my_own_validator_config: ValidatorConfig::default(),
            known_nodes_with_stake: gen_known_nodes_with_stake,
            known_nodes_without_stake: vec![],
            staked_da_nodes,
            known_da_nodes,
            fixed_leader_for_gpuvid: 1,
            next_view_timeout: 10000,
            view_sync_timeout: Duration::from_millis(1000),
            timeout_ratio: (11, 10),
            round_start_delay: 1,
            start_delay: 1,
            num_bootstrap: 5,
            builder_timeout: Duration::from_secs(10),
            data_request_delay: Some(Duration::from_millis(REQUEST_DATA_DELAY)),
            builder_urls: default_builder_urls(),
            upgrade: UpgradeConfig::default(),
        }
    }
}