Skip to main content

ant_node/
config.rs

1//! Configuration for ant-node.
2
3use crate::storage::MigrationConfig;
4use evmlib::Network as EvmNetwork;
5use serde::{Deserialize, Serialize};
6use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
7use std::path::{Path, PathBuf};
8
9/// Filename for the persisted node identity keypair.
10pub const NODE_IDENTITY_FILENAME: &str = "node_identity.key";
11
12/// Subdirectory under the root dir that contains per-node data directories.
13pub const NODES_SUBDIR: &str = "nodes";
14
15/// Upgrade channel for auto-updates.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum UpgradeChannel {
19    /// Stable releases only.
20    #[default]
21    Stable,
22    /// Beta releases (includes stable).
23    Beta,
24}
25
26/// Network mode for different deployment scenarios.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
28#[serde(rename_all = "lowercase")]
29pub enum NetworkMode {
30    /// Production mode with full anti-Sybil protection.
31    #[default]
32    Production,
33    /// Testnet mode with relaxed diversity requirements.
34    /// Suitable for single-provider deployments (e.g., Digital Ocean).
35    Testnet,
36    /// Development mode with minimal restrictions.
37    /// Only use for local testing.
38    Development,
39}
40
41/// Testnet-specific configuration for relaxed IP diversity limits.
42///
43/// saorsa-core uses a simple 2-tier model: per-exact-IP and per-subnet
44/// (/24 IPv4, /64 IPv6) limits.  Testnet defaults are permissive so
45/// nodes co-located on a single provider (e.g. Digital Ocean) can join.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct TestnetConfig {
48    /// Maximum nodes sharing an exact IP address.
49    /// Default: `usize::MAX` (effectively unlimited for testnet).
50    #[serde(default = "default_testnet_max_per_ip")]
51    pub max_per_ip: Option<usize>,
52
53    /// Maximum nodes in the same /24 (IPv4) or /64 (IPv6) subnet.
54    /// Default: `usize::MAX` (effectively unlimited for testnet).
55    #[serde(default = "default_testnet_max_per_subnet")]
56    pub max_per_subnet: Option<usize>,
57}
58
59impl Default for TestnetConfig {
60    fn default() -> Self {
61        Self {
62            max_per_ip: default_testnet_max_per_ip(),
63            max_per_subnet: default_testnet_max_per_subnet(),
64        }
65    }
66}
67
68// These return `Option` because `serde(default = "...")` requires the function's
69// return type to match the field type (`Option<usize>`).
70#[allow(clippy::unnecessary_wraps)]
71const fn default_testnet_max_per_ip() -> Option<usize> {
72    Some(usize::MAX)
73}
74
75#[allow(clippy::unnecessary_wraps)]
76const fn default_testnet_max_per_subnet() -> Option<usize> {
77    Some(usize::MAX)
78}
79
80/// Node configuration.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct NodeConfig {
83    /// Root directory for node data.
84    #[serde(default = "default_root_dir")]
85    pub root_dir: PathBuf,
86
87    /// Listening port (0 for auto-select).
88    #[serde(default)]
89    pub port: u16,
90
91    /// Force IPv4-only mode.
92    ///
93    /// When true, the node binds only on IPv4 instead of dual-stack.
94    /// Use this on hosts without working IPv6 to avoid advertising
95    /// unreachable addresses to the DHT.
96    #[serde(default)]
97    pub ipv4_only: bool,
98
99    /// Bootstrap peer addresses.
100    #[serde(default)]
101    pub bootstrap: Vec<SocketAddr>,
102
103    /// Network mode (production, testnet, or development).
104    #[serde(default)]
105    pub network_mode: NetworkMode,
106
107    /// Testnet-specific configuration.
108    /// Only used when `network_mode` is `Testnet`.
109    #[serde(default)]
110    pub testnet: TestnetConfig,
111
112    /// Upgrade configuration.
113    #[serde(default)]
114    pub upgrade: UpgradeConfig,
115
116    /// Payment verification configuration.
117    #[serde(default)]
118    pub payment: PaymentConfig,
119
120    /// Storage configuration for chunk persistence.
121    #[serde(default)]
122    pub storage: StorageConfig,
123
124    /// Directory for persisting the close group cache.
125    ///
126    /// When `None` (default), the node's `root_dir` is used — the cache
127    /// file lands alongside `node_identity.key`.
128    #[serde(default)]
129    pub close_group_cache_dir: Option<PathBuf>,
130
131    /// Maximum application-layer message size in bytes.
132    ///
133    /// Tunes the QUIC stream receive window and per-stream read buffer.
134    /// Default: the larger of
135    /// [`MAX_WIRE_MESSAGE_SIZE`](crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE) (5 MiB)
136    /// and [`MAX_REPLICATION_MESSAGE_SIZE`](crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE)
137    /// (10 MiB), so both chunk and replication traffic fit within the transport
138    /// ceiling.
139    #[serde(default = "default_max_message_size")]
140    pub max_message_size: usize,
141
142    /// Log level.
143    #[serde(default = "default_log_level")]
144    pub log_level: String,
145}
146
147/// Auto-upgrade configuration.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct UpgradeConfig {
150    /// Release channel.
151    #[serde(default)]
152    pub channel: UpgradeChannel,
153
154    /// Check interval in hours.
155    #[serde(default = "default_check_interval")]
156    pub check_interval_hours: u64,
157
158    /// GitHub repository in "owner/repo" format for release monitoring.
159    #[serde(default = "default_github_repo")]
160    pub github_repo: String,
161
162    /// Staged rollout window in hours.
163    ///
164    /// When a new version is detected, each node waits a deterministic delay
165    /// based on its node ID before applying the upgrade. This prevents mass
166    /// restarts and ensures network stability during upgrades.
167    ///
168    /// Set to 0 to disable staged rollout (apply upgrades immediately).
169    #[serde(default = "default_staged_rollout_hours")]
170    pub staged_rollout_hours: u64,
171
172    /// Exit cleanly on upgrade instead of spawning a new process.
173    ///
174    /// When true, the node exits after applying an upgrade and relies on
175    /// an external service manager (systemd, launchd, Windows Service) to
176    /// restart it. When false (default), the node spawns the new binary
177    /// as a child process before exiting.
178    #[serde(default)]
179    pub stop_on_upgrade: bool,
180}
181
182/// EVM network for payment processing.
183///
184/// `Custom` is used by the local-Anvil testnet flow in
185/// `deploy/testnet-v2/`: when an operator stands up a private Anvil
186/// instance with the ANT token + payment vault contracts deployed,
187/// every node points at the Anvil RPC and the deployed addresses
188/// instead of one of the public Arbitrum networks.
189#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
190#[serde(rename_all = "kebab-case", tag = "type")]
191pub enum EvmNetworkConfig {
192    /// Arbitrum One mainnet.
193    #[default]
194    ArbitrumOne,
195    /// Arbitrum Sepolia testnet.
196    ArbitrumSepolia,
197    /// Local / private EVM (e.g. Anvil) with operator-supplied
198    /// contract addresses.
199    Custom {
200        /// HTTP RPC URL of the EVM node (e.g. `http://1.2.3.4:8545`).
201        rpc_url: String,
202        /// Deployed ANT token (ERC-20) contract address.
203        payment_token_address: String,
204        /// Deployed payment vault contract address.
205        payment_vault_address: String,
206    },
207}
208
209impl EvmNetworkConfig {
210    /// Resolve this config into the concrete `evmlib` network used by
211    /// the payment verifier and the rewards wallet.
212    #[must_use]
213    pub fn into_evm_network(self) -> EvmNetwork {
214        match self {
215            Self::ArbitrumOne => EvmNetwork::ArbitrumOne,
216            Self::ArbitrumSepolia => EvmNetwork::ArbitrumSepoliaTest,
217            Self::Custom {
218                rpc_url,
219                payment_token_address,
220                payment_vault_address,
221            } => EvmNetwork::new_custom(&rpc_url, &payment_token_address, &payment_vault_address),
222        }
223    }
224}
225
226/// Payment verification configuration.
227///
228/// All new data requires EVM payment on Arbitrum — there is no way to
229/// disable payment verification. The cache stores previously verified
230/// payments to avoid redundant on-chain lookups.
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct PaymentConfig {
233    /// Cache capacity for verified `XorNames`.
234    #[serde(default = "default_cache_capacity")]
235    pub cache_capacity: usize,
236
237    /// EVM wallet address for receiving payments (e.g., "0x...").
238    /// If not set, the node will not be able to receive payments.
239    #[serde(default)]
240    pub rewards_address: Option<String>,
241
242    /// EVM network for payment processing.
243    #[serde(default)]
244    pub evm_network: EvmNetworkConfig,
245
246    /// Metrics port for Prometheus scraping.
247    /// Set to 0 to disable metrics endpoint.
248    #[serde(default = "default_metrics_port")]
249    pub metrics_port: u16,
250}
251
252impl Default for PaymentConfig {
253    fn default() -> Self {
254        Self {
255            cache_capacity: default_cache_capacity(),
256            rewards_address: None,
257            evm_network: EvmNetworkConfig::default(),
258            metrics_port: default_metrics_port(),
259        }
260    }
261}
262
263const fn default_metrics_port() -> u16 {
264    9100
265}
266
267const fn default_cache_capacity() -> usize {
268    100_000
269}
270
271impl Default for NodeConfig {
272    fn default() -> Self {
273        Self {
274            root_dir: default_root_dir(),
275            port: 0,
276            ipv4_only: false,
277            bootstrap: Vec::new(),
278            network_mode: NetworkMode::default(),
279            testnet: TestnetConfig::default(),
280            upgrade: UpgradeConfig::default(),
281            payment: PaymentConfig::default(),
282            storage: StorageConfig::default(),
283            close_group_cache_dir: None,
284            max_message_size: default_max_message_size(),
285            log_level: default_log_level(),
286        }
287    }
288}
289
290impl NodeConfig {
291    /// Create a testnet configuration preset.
292    ///
293    /// This is a convenience method for setting up a testnet node with
294    /// relaxed anti-Sybil protection, suitable for single-provider deployments.
295    /// Includes default bootstrap nodes for the Autonomi testnet.
296    #[must_use]
297    pub fn testnet() -> Self {
298        Self {
299            network_mode: NetworkMode::Testnet,
300            testnet: TestnetConfig::default(),
301            bootstrap: default_testnet_bootstrap(),
302            ..Self::default()
303        }
304    }
305
306    /// Create a development configuration preset.
307    ///
308    /// This has minimal restrictions and is only suitable for local testing.
309    #[must_use]
310    pub fn development() -> Self {
311        Self {
312            network_mode: NetworkMode::Development,
313            testnet: TestnetConfig {
314                max_per_ip: Some(usize::MAX),
315                max_per_subnet: Some(usize::MAX),
316            },
317            ..Self::default()
318        }
319    }
320
321    /// Check if this configuration is using relaxed security settings.
322    #[must_use]
323    pub fn is_relaxed(&self) -> bool {
324        !matches!(self.network_mode, NetworkMode::Production)
325    }
326
327    /// Load configuration from a TOML file.
328    ///
329    /// # Errors
330    ///
331    /// Returns an error if the file cannot be read or parsed.
332    pub fn from_file(path: &std::path::Path) -> crate::Result<Self> {
333        let content = std::fs::read_to_string(path)?;
334        toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
335    }
336
337    /// Save configuration to a TOML file.
338    ///
339    /// # Errors
340    ///
341    /// Returns an error if the file cannot be written.
342    pub fn to_file(&self, path: &std::path::Path) -> crate::Result<()> {
343        let content =
344            toml::to_string_pretty(self).map_err(|e| crate::Error::Config(e.to_string()))?;
345        std::fs::write(path, content)?;
346        Ok(())
347    }
348}
349
350impl Default for UpgradeConfig {
351    fn default() -> Self {
352        Self {
353            channel: UpgradeChannel::default(),
354            check_interval_hours: default_check_interval(),
355            github_repo: default_github_repo(),
356            staged_rollout_hours: default_staged_rollout_hours(),
357            stop_on_upgrade: false,
358        }
359    }
360}
361
362fn default_github_repo() -> String {
363    "WithAutonomi/ant-node".to_string()
364}
365
366/// Default base directory for node data (platform data dir for "ant").
367#[must_use]
368pub fn default_root_dir() -> PathBuf {
369    directories::ProjectDirs::from("", "", "ant").map_or_else(
370        || PathBuf::from(".ant"),
371        |dirs| dirs.data_dir().to_path_buf(),
372    )
373}
374
375/// Default directory containing per-node data subdirectories.
376///
377/// Each node gets `{default_root_dir}/nodes/{peer_id}/` where `peer_id` is the
378/// full 64-character hex-encoded node ID.
379#[must_use]
380pub fn default_nodes_dir() -> PathBuf {
381    default_root_dir().join(NODES_SUBDIR)
382}
383
384fn default_max_message_size() -> usize {
385    // Use the larger of the chunk protocol and replication protocol ceilings
386    // so that replication hint batches (up to 10 MiB) are not silently dropped
387    // by the transport layer.
388    crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE
389        .max(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
390}
391
392fn default_log_level() -> String {
393    "info".to_string()
394}
395
396const fn default_check_interval() -> u64 {
397    1 // 1 hour
398}
399
400const fn default_staged_rollout_hours() -> u64 {
401    24 // 24 hour window for staged rollout
402}
403
404// ============================================================================
405// Storage Configuration
406// ============================================================================
407
408/// Storage configuration for chunk persistence.
409///
410/// Controls how chunks are stored, including:
411/// - Whether storage is enabled
412/// - Content verification on read
413/// - Database size limits (auto-scales with available disk by default)
414#[derive(Debug, Clone, Serialize, Deserialize)]
415pub struct StorageConfig {
416    /// Enable chunk storage.
417    /// Default: true
418    #[serde(default = "default_storage_enabled")]
419    pub enabled: bool,
420
421    /// Verify content hash matches address on read.
422    /// Default: true
423    #[serde(default = "default_storage_verify_on_read")]
424    pub verify_on_read: bool,
425
426    /// Explicit LMDB database size cap in GiB.
427    ///
428    /// When set to 0 (default), the map size is computed automatically from
429    /// available disk space at startup and grows on demand when the operator
430    /// adds storage.  Set a non-zero value to impose a hard cap.
431    #[serde(default)]
432    pub db_size_gb: usize,
433
434    /// Minimum free disk space (in MiB) to preserve on the storage partition.
435    ///
436    /// Writes are refused when available space drops below this threshold,
437    /// preventing the node from filling the disk completely.  Default: 500 MiB.
438    #[serde(default = "default_disk_reserve_mb")]
439    pub disk_reserve_mb: u64,
440
441    /// Controls for moving this node off the legacy LMDB chunk store.
442    ///
443    /// The two release switches inside it are deliberately not serialised: see
444    /// [`MigrationConfig`].
445    #[serde(default)]
446    pub migration: MigrationConfig,
447}
448
449impl Default for StorageConfig {
450    fn default() -> Self {
451        Self {
452            enabled: default_storage_enabled(),
453            verify_on_read: default_storage_verify_on_read(),
454            db_size_gb: 0,
455            disk_reserve_mb: default_disk_reserve_mb(),
456            migration: MigrationConfig::default(),
457        }
458    }
459}
460
461/// Default: 500 MiB — matches `DEFAULT_DISK_RESERVE` in `storage::lmdb`.
462const fn default_disk_reserve_mb() -> u64 {
463    500
464}
465
466const fn default_storage_enabled() -> bool {
467    true
468}
469
470const fn default_storage_verify_on_read() -> bool {
471    true
472}
473
474// ============================================================================
475// Bootstrap Peers Configuration (shipped config file)
476// ============================================================================
477
478/// The filename for the bootstrap peers configuration file.
479pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
480
481/// Environment variable that overrides the bootstrap peers file search path.
482pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
483
484/// Bootstrap peers loaded from a shipped configuration file.
485///
486/// This file provides initial peers for first-time network joins.
487#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct BootstrapPeersConfig {
489    /// The bootstrap peer socket addresses.
490    #[serde(default)]
491    pub peers: Vec<SocketAddr>,
492}
493
494/// The source from which bootstrap peers were resolved.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub enum BootstrapSource {
497    /// Provided via `--bootstrap` CLI argument or `ANT_BOOTSTRAP` env var.
498    Cli,
499    /// Loaded from an explicit `--config` file.
500    ConfigFile,
501    /// Auto-discovered from a `bootstrap_peers.toml` file.
502    AutoDiscovered(PathBuf),
503    /// No bootstrap peers were found from any source.
504    None,
505}
506
507impl BootstrapPeersConfig {
508    /// Load bootstrap peers from a TOML file at the given path.
509    ///
510    /// # Errors
511    ///
512    /// Returns an error if the file cannot be read or contains invalid TOML.
513    pub fn from_file(path: &Path) -> crate::Result<Self> {
514        let content = std::fs::read_to_string(path)?;
515        toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
516    }
517
518    /// Search well-known locations for a `bootstrap_peers.toml` file and load it.
519    ///
520    /// Search order (first match wins):
521    /// 1. `$ANT_BOOTSTRAP_PEERS_PATH` environment variable (path to file)
522    /// 2. Same directory as the running executable
523    /// 3. Platform config directory (`~/.config/ant/` on Linux,
524    ///    `~/Library/Application Support/ant/` on macOS,
525    ///    `%APPDATA%\ant\` on Windows)
526    /// 4. System config: `/etc/ant/` (Unix only)
527    ///
528    /// Returns `None` if no file is found in any location.
529    #[must_use]
530    pub fn discover() -> Option<(Self, PathBuf)> {
531        if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
532            return Self::load_non_empty_candidate(PathBuf::from(env_path));
533        }
534
535        for path in Self::search_paths() {
536            if let Some(discovered) = Self::load_non_empty_candidate(path) {
537                return Some(discovered);
538            }
539        }
540
541        None
542    }
543
544    fn load_non_empty_candidate(path: PathBuf) -> Option<(Self, PathBuf)> {
545        if !path.is_file() {
546            return None;
547        }
548
549        match Self::from_file(&path) {
550            Ok(config) if !config.peers.is_empty() => Some((config, path)),
551            Ok(_) => None,
552            Err(err) => {
553                crate::logging::warn!(
554                    "Failed to load bootstrap peers from {}: {err}",
555                    path.display(),
556                );
557                None
558            }
559        }
560    }
561
562    /// Build the ordered list of candidate paths to search.
563    fn search_paths() -> Vec<PathBuf> {
564        let mut paths = Vec::new();
565
566        // 1. Environment variable override.
567        if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
568            paths.push(PathBuf::from(env_path));
569        }
570
571        // 2. Next to the running executable.
572        if let Ok(exe) = std::env::current_exe() {
573            if let Some(exe_dir) = exe.parent() {
574                paths.push(exe_dir.join(BOOTSTRAP_PEERS_FILENAME));
575            }
576        }
577
578        // 3. Platform config directory.
579        if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
580            paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
581        }
582
583        // 4. System config (Unix only).
584        #[cfg(unix)]
585        {
586            paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
587        }
588
589        paths
590    }
591}
592
593/// Default testnet bootstrap nodes.
594///
595/// These are well-known bootstrap nodes for the Autonomi testnet.
596/// - ant-bootstrap-1 (NYC): 165.22.4.178:12000
597/// - ant-bootstrap-2 (SFO): 164.92.111.156:12000
598fn default_testnet_bootstrap() -> Vec<SocketAddr> {
599    vec![
600        // ant-bootstrap-1 (Digital Ocean NYC1)
601        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
602        // ant-bootstrap-2 (Digital Ocean SFO3)
603        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(164, 92, 111, 156), 12000)),
604    ]
605}
606
607#[cfg(test)]
608#[allow(clippy::unwrap_used, clippy::expect_used)]
609mod tests {
610
611    use super::*;
612    use serial_test::serial;
613
614    #[test]
615    fn the_shipped_storage_config_parses() {
616        // The migration section is operator-facing, so a typo in it would only surface on
617        // a node that had already shipped. Only `[storage]` is checked: the rest of
618        // `production.toml` does not currently deserialize as a `NodeConfig` (its
619        // `evm_network` is a bare string where an internally tagged enum is expected),
620        // which is a separate, pre-existing problem.
621        let raw = include_str!("../config/production.toml");
622        let doc: toml::Value = toml::from_str(raw).expect("production.toml must be valid TOML");
623        let storage = doc.get("storage").expect("a [storage] section").clone();
624        let config: StorageConfig = storage.try_into().expect("[storage] must deserialize");
625
626        assert!(config.migration.enabled);
627        assert!(config.migration.dual_write_legacy);
628        assert_eq!(config.migration.shed_hold_hours, 72);
629        assert_eq!(config.migration.copier_throttle_mib_per_sec, 32);
630        assert_eq!(config.migration.copier_slack_mb, 2048);
631        // The release switches are absent from the file on purpose, so they come from the
632        // build rather than from whatever an operator's config last recorded.
633        let build = MigrationConfig::default();
634        assert_eq!(config.migration.retire_legacy, build.retire_legacy);
635    }
636
637    #[test]
638    fn test_default_config_has_cache_capacity() {
639        let config = PaymentConfig::default();
640        assert!(config.cache_capacity > 0, "Cache capacity must be positive");
641    }
642
643    #[test]
644    fn test_default_evm_network() {
645        use crate::payment::EvmVerifierConfig;
646        let _config = EvmVerifierConfig::default();
647        // EVM verification is always on — no enabled field
648    }
649
650    #[test]
651    fn test_bootstrap_peers_parse_valid_toml() {
652        let toml_str = r#"
653            peers = [
654                "127.0.0.1:10000",
655                "192.168.1.1:10001",
656            ]
657        "#;
658        let config: BootstrapPeersConfig =
659            toml::from_str(toml_str).expect("valid TOML should parse");
660        assert_eq!(config.peers.len(), 2);
661        assert_eq!(config.peers[0].port(), 10000);
662        assert_eq!(config.peers[1].port(), 10001);
663    }
664
665    #[test]
666    fn test_bootstrap_peers_parse_empty_peers() {
667        let toml_str = r"peers = []";
668        let config: BootstrapPeersConfig =
669            toml::from_str(toml_str).expect("empty peers should parse");
670        assert!(config.peers.is_empty());
671    }
672
673    #[test]
674    fn test_bootstrap_peers_parse_missing_peers_field() {
675        let toml_str = "";
676        let config: BootstrapPeersConfig =
677            toml::from_str(toml_str).expect("missing field should use default");
678        assert!(config.peers.is_empty());
679    }
680
681    #[test]
682    fn test_bootstrap_peers_from_file() {
683        let dir = tempfile::tempdir().expect("create temp dir");
684        let path = dir.path().join("bootstrap_peers.toml");
685        std::fs::write(&path, r#"peers = ["10.0.0.1:10000", "10.0.0.2:10000"]"#)
686            .expect("write file");
687
688        let config = BootstrapPeersConfig::from_file(&path).expect("load from file");
689        assert_eq!(config.peers.len(), 2);
690    }
691
692    #[test]
693    fn test_bootstrap_peers_from_file_invalid_toml() {
694        let dir = tempfile::tempdir().expect("create temp dir");
695        let path = dir.path().join("bootstrap_peers.toml");
696        std::fs::write(&path, "not valid toml [[[").expect("write file");
697
698        assert!(BootstrapPeersConfig::from_file(&path).is_err());
699    }
700
701    /// Env-var-based discovery tests must run serially because they mutate
702    /// a shared process-wide environment variable.
703    #[test]
704    #[serial]
705    fn test_bootstrap_peers_discover_env_var() {
706        // Sub-test 1: valid file with peers is discovered.
707        {
708            let dir = tempfile::tempdir().expect("create temp dir");
709            let path = dir.path().join("bootstrap_peers.toml");
710            std::fs::write(&path, r#"peers = ["10.0.0.1:10000"]"#).expect("write file");
711
712            std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
713            let result = BootstrapPeersConfig::discover();
714            std::env::remove_var(BOOTSTRAP_PEERS_ENV);
715
716            let (config, discovered_path) = result.expect("should discover from env var");
717            assert_eq!(config.peers.len(), 1);
718            assert_eq!(discovered_path, path);
719        }
720
721        // Sub-test 2: file with empty peers list is skipped.
722        {
723            let dir = tempfile::tempdir().expect("create temp dir");
724            let path = dir.path().join("bootstrap_peers.toml");
725            std::fs::write(&path, r"peers = []").expect("write file");
726
727            std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
728            let result = BootstrapPeersConfig::discover();
729            std::env::remove_var(BOOTSTRAP_PEERS_ENV);
730
731            assert!(result.is_none(), "empty peers file should be skipped");
732        }
733    }
734
735    #[test]
736    fn test_bootstrap_peers_search_paths_contains_exe_dir() {
737        let paths = BootstrapPeersConfig::search_paths();
738        // At minimum, the exe-dir candidate should be present.
739        assert!(
740            paths
741                .iter()
742                .any(|p| p.file_name().is_some_and(|f| f == BOOTSTRAP_PEERS_FILENAME)),
743            "search paths should include a candidate with the bootstrap peers filename"
744        );
745    }
746}