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    /// Direct-browser WebRTC Direct listener.
125    ///
126    /// This is enabled automatically when the binary includes the default
127    /// `webrtc-direct` feature. Minimal native-only builds leave it disabled.
128    #[serde(default)]
129    pub webrtc_direct: WebRtcDirectConfig,
130
131    /// Directory for persisting the close group cache.
132    ///
133    /// When `None` (default), the node's `root_dir` is used — the cache
134    /// file lands alongside `node_identity.key`.
135    #[serde(default)]
136    pub close_group_cache_dir: Option<PathBuf>,
137
138    /// Maximum application-layer message size in bytes.
139    ///
140    /// Tunes the QUIC stream receive window and per-stream read buffer.
141    /// Default: the larger of
142    /// [`MAX_WIRE_MESSAGE_SIZE`](crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE) (5 MiB)
143    /// and [`MAX_REPLICATION_MESSAGE_SIZE`](crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE)
144    /// (10 MiB), so both chunk and replication traffic fit within the transport
145    /// ceiling.
146    #[serde(default = "default_max_message_size")]
147    pub max_message_size: usize,
148
149    /// Log level.
150    #[serde(default = "default_log_level")]
151    pub log_level: String,
152}
153
154/// Configuration for the ADR-0015 WebRTC Direct browser listener.
155///
156/// This listener is deliberately separate from the native Saorsa QUIC port.
157/// It exposes local closest-node lookup, immutable chunk reads, and paid
158/// content-addressed writes through the ordinary payment verifier.
159#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(default)]
161pub struct WebRtcDirectConfig {
162    /// Enable the browser listener.
163    pub enabled: bool,
164
165    /// UDP address for the WebRTC Direct listener. Port zero asks the OS to choose.
166    pub bind: SocketAddr,
167
168    /// Literal public UDP address advertised to browsers.
169    ///
170    /// When omitted, a wildcard listener uses the native self-address view's
171    /// first non-relay IP in the bind family and the actual WebRTC bound port.
172    /// Publication waits when native address discovery has no usable IP.
173    pub advertised_addr: Option<SocketAddr>,
174
175    /// PEM file used to persist the stable DTLS certificate and private key.
176    ///
177    /// Relative paths are resolved against the node root directory by the
178    /// caller. The default is `webrtc-direct.pem` beside the node identity.
179    pub certificate_path: Option<PathBuf>,
180
181    /// Maximum simultaneously accepted browser sessions.
182    pub max_connections: usize,
183
184    /// Maximum simultaneously accepted browser sessions from one IPv4 address or IPv6 /64.
185    ///
186    /// This must be lower than [`Self::max_connections`] so one public source
187    /// cannot occupy every listener slot.
188    pub max_connections_per_ip: usize,
189
190    /// Maximum simultaneously active `DataChannels` on one browser session.
191    pub max_channels_per_connection: usize,
192
193    /// Maximum simultaneously active `DataChannels` across the listener.
194    ///
195    /// Every admitted channel owns one handler task, so this is also the hard
196    /// global channel-task bound.
197    pub max_channels: usize,
198
199    /// Maximum requests being read or processed across the listener.
200    pub max_concurrent_requests: usize,
201
202    /// Token-bucket request rate across the listener, in requests per second.
203    pub max_requests_per_second: usize,
204
205    /// Token-bucket request rate for one IPv4 address or IPv6 /64, in requests per second.
206    pub max_requests_per_second_per_ip: usize,
207
208    /// Token-bucket request rate for one browser session, in requests per
209    /// second.
210    pub max_requests_per_second_per_connection: usize,
211
212    /// Maximum bytes reserved by frames being assembled, decrypted, or sent
213    /// across the listener.
214    pub max_in_flight_bytes: usize,
215
216    /// Maximum in-flight frame bytes attributable to one IPv4 address or IPv6 /64.
217    pub max_in_flight_bytes_per_ip: usize,
218}
219
220impl Default for WebRtcDirectConfig {
221    fn default() -> Self {
222        Self {
223            enabled: cfg!(feature = "webrtc-direct"),
224            bind: default_webrtc_direct_bind(),
225            advertised_addr: None,
226            certificate_path: None,
227            max_connections: default_webrtc_direct_max_connections(),
228            max_connections_per_ip: default_webrtc_direct_max_connections_per_ip(),
229            max_channels_per_connection: default_webrtc_direct_max_channels_per_connection(),
230            max_channels: default_webrtc_direct_max_channels(),
231            max_concurrent_requests: default_webrtc_direct_max_concurrent_requests(),
232            max_requests_per_second: default_webrtc_direct_max_requests_per_second(),
233            max_requests_per_second_per_ip: default_webrtc_direct_max_requests_per_second_per_ip(),
234            max_requests_per_second_per_connection:
235                default_webrtc_direct_max_requests_per_second_per_connection(),
236            max_in_flight_bytes: default_webrtc_direct_max_in_flight_bytes(),
237            max_in_flight_bytes_per_ip: default_webrtc_direct_max_in_flight_bytes_per_ip(),
238        }
239    }
240}
241
242fn default_webrtc_direct_bind() -> SocketAddr {
243    SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0))
244}
245
246const fn default_webrtc_direct_max_connections() -> usize {
247    32
248}
249
250const fn default_webrtc_direct_max_connections_per_ip() -> usize {
251    4
252}
253
254const fn default_webrtc_direct_max_channels_per_connection() -> usize {
255    2
256}
257
258const fn default_webrtc_direct_max_channels() -> usize {
259    32
260}
261
262const fn default_webrtc_direct_max_concurrent_requests() -> usize {
263    16
264}
265
266const fn default_webrtc_direct_max_requests_per_second() -> usize {
267    256
268}
269
270const fn default_webrtc_direct_max_requests_per_second_per_ip() -> usize {
271    32
272}
273
274const fn default_webrtc_direct_max_requests_per_second_per_connection() -> usize {
275    16
276}
277
278const fn default_webrtc_direct_max_in_flight_bytes() -> usize {
279    64 * 1024 * 1024
280}
281
282const fn default_webrtc_direct_max_in_flight_bytes_per_ip() -> usize {
283    16 * 1024 * 1024
284}
285
286/// Auto-upgrade configuration.
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct UpgradeConfig {
289    /// Release channel.
290    #[serde(default)]
291    pub channel: UpgradeChannel,
292
293    /// Check interval in hours.
294    #[serde(default = "default_check_interval")]
295    pub check_interval_hours: u64,
296
297    /// GitHub repository in "owner/repo" format for release monitoring.
298    #[serde(default = "default_github_repo")]
299    pub github_repo: String,
300
301    /// Staged rollout window in hours.
302    ///
303    /// When a new version is detected, each node waits a deterministic delay
304    /// based on its node ID before applying the upgrade. This prevents mass
305    /// restarts and ensures network stability during upgrades.
306    ///
307    /// Set to 0 to disable staged rollout (apply upgrades immediately).
308    #[serde(default = "default_staged_rollout_hours")]
309    pub staged_rollout_hours: u64,
310
311    /// Exit cleanly on upgrade instead of spawning a new process.
312    ///
313    /// When true, the node exits after applying an upgrade and relies on
314    /// an external service manager (systemd, launchd, Windows Service) to
315    /// restart it. When false (default), the node spawns the new binary
316    /// as a child process before exiting.
317    #[serde(default)]
318    pub stop_on_upgrade: bool,
319}
320
321/// EVM network for payment processing.
322///
323/// `Custom` is used by the local-Anvil testnet flow in
324/// `deploy/testnet-v2/`: when an operator stands up a private Anvil
325/// instance with the ANT token + payment vault contracts deployed,
326/// every node points at the Anvil RPC and the deployed addresses
327/// instead of one of the public Arbitrum networks.
328#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
329#[serde(rename_all = "kebab-case", tag = "type")]
330pub enum EvmNetworkConfig {
331    /// Arbitrum One mainnet.
332    #[default]
333    ArbitrumOne,
334    /// Arbitrum Sepolia testnet.
335    ArbitrumSepolia,
336    /// Local / private EVM (e.g. Anvil) with operator-supplied
337    /// contract addresses.
338    Custom {
339        /// HTTP RPC URL of the EVM node (e.g. `http://1.2.3.4:8545`).
340        rpc_url: String,
341        /// Deployed ANT token (ERC-20) contract address.
342        payment_token_address: String,
343        /// Deployed payment vault contract address.
344        payment_vault_address: String,
345    },
346}
347
348impl EvmNetworkConfig {
349    /// Resolve this config into the concrete `evmlib` network used by
350    /// the payment verifier and the rewards wallet.
351    #[must_use]
352    pub fn into_evm_network(self) -> EvmNetwork {
353        match self {
354            Self::ArbitrumOne => EvmNetwork::ArbitrumOne,
355            Self::ArbitrumSepolia => EvmNetwork::ArbitrumSepoliaTest,
356            Self::Custom {
357                rpc_url,
358                payment_token_address,
359                payment_vault_address,
360            } => EvmNetwork::new_custom(&rpc_url, &payment_token_address, &payment_vault_address),
361        }
362    }
363}
364
365/// Payment verification configuration.
366///
367/// All new data requires EVM payment on Arbitrum — there is no way to
368/// disable payment verification. The cache stores previously verified
369/// payments to avoid redundant on-chain lookups.
370#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct PaymentConfig {
372    /// Cache capacity for verified `XorNames`.
373    #[serde(default = "default_cache_capacity")]
374    pub cache_capacity: usize,
375
376    /// EVM wallet address for receiving payments (e.g., "0x...").
377    /// If not set, the node will not be able to receive payments.
378    #[serde(default)]
379    pub rewards_address: Option<String>,
380
381    /// EVM network for payment processing.
382    #[serde(default)]
383    pub evm_network: EvmNetworkConfig,
384
385    /// Metrics port for Prometheus scraping.
386    /// Set to 0 to disable metrics endpoint.
387    #[serde(default = "default_metrics_port")]
388    pub metrics_port: u16,
389}
390
391impl Default for PaymentConfig {
392    fn default() -> Self {
393        Self {
394            cache_capacity: default_cache_capacity(),
395            rewards_address: None,
396            evm_network: EvmNetworkConfig::default(),
397            metrics_port: default_metrics_port(),
398        }
399    }
400}
401
402const fn default_metrics_port() -> u16 {
403    9100
404}
405
406const fn default_cache_capacity() -> usize {
407    100_000
408}
409
410impl Default for NodeConfig {
411    fn default() -> Self {
412        Self {
413            root_dir: default_root_dir(),
414            port: 0,
415            ipv4_only: false,
416            bootstrap: Vec::new(),
417            network_mode: NetworkMode::default(),
418            testnet: TestnetConfig::default(),
419            upgrade: UpgradeConfig::default(),
420            payment: PaymentConfig::default(),
421            storage: StorageConfig::default(),
422            webrtc_direct: WebRtcDirectConfig::default(),
423            close_group_cache_dir: None,
424            max_message_size: default_max_message_size(),
425            log_level: default_log_level(),
426        }
427    }
428}
429
430impl NodeConfig {
431    /// Create a testnet configuration preset.
432    ///
433    /// This is a convenience method for setting up a testnet node with
434    /// relaxed anti-Sybil protection, suitable for single-provider deployments.
435    /// Includes default bootstrap nodes for the Autonomi testnet.
436    #[must_use]
437    pub fn testnet() -> Self {
438        Self {
439            network_mode: NetworkMode::Testnet,
440            testnet: TestnetConfig::default(),
441            bootstrap: default_testnet_bootstrap(),
442            ..Self::default()
443        }
444    }
445
446    /// Create a development configuration preset.
447    ///
448    /// This has minimal restrictions and is only suitable for local testing.
449    #[must_use]
450    pub fn development() -> Self {
451        Self {
452            network_mode: NetworkMode::Development,
453            testnet: TestnetConfig {
454                max_per_ip: Some(usize::MAX),
455                max_per_subnet: Some(usize::MAX),
456            },
457            ..Self::default()
458        }
459    }
460
461    /// Check if this configuration is using relaxed security settings.
462    #[must_use]
463    pub fn is_relaxed(&self) -> bool {
464        !matches!(self.network_mode, NetworkMode::Production)
465    }
466
467    /// Load configuration from a TOML file.
468    ///
469    /// # Errors
470    ///
471    /// Returns an error if the file cannot be read or parsed.
472    pub fn from_file(path: &std::path::Path) -> crate::Result<Self> {
473        let content = std::fs::read_to_string(path)?;
474        toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
475    }
476
477    /// Save configuration to a TOML file.
478    ///
479    /// # Errors
480    ///
481    /// Returns an error if the file cannot be written.
482    pub fn to_file(&self, path: &std::path::Path) -> crate::Result<()> {
483        let content =
484            toml::to_string_pretty(self).map_err(|e| crate::Error::Config(e.to_string()))?;
485        std::fs::write(path, content)?;
486        Ok(())
487    }
488}
489
490impl Default for UpgradeConfig {
491    fn default() -> Self {
492        Self {
493            channel: UpgradeChannel::default(),
494            check_interval_hours: default_check_interval(),
495            github_repo: default_github_repo(),
496            staged_rollout_hours: default_staged_rollout_hours(),
497            stop_on_upgrade: false,
498        }
499    }
500}
501
502fn default_github_repo() -> String {
503    "WithAutonomi/ant-node".to_string()
504}
505
506/// Default base directory for node data (platform data dir for "ant").
507#[must_use]
508pub fn default_root_dir() -> PathBuf {
509    directories::ProjectDirs::from("", "", "ant").map_or_else(
510        || PathBuf::from(".ant"),
511        |dirs| dirs.data_dir().to_path_buf(),
512    )
513}
514
515/// Default directory containing per-node data subdirectories.
516///
517/// Each node gets `{default_root_dir}/nodes/{peer_id}/` where `peer_id` is the
518/// full 64-character hex-encoded node ID.
519#[must_use]
520pub fn default_nodes_dir() -> PathBuf {
521    default_root_dir().join(NODES_SUBDIR)
522}
523
524fn default_max_message_size() -> usize {
525    // Use the larger of the chunk protocol and replication protocol ceilings
526    // so that replication hint batches (up to 10 MiB) are not silently dropped
527    // by the transport layer.
528    crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE
529        .max(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
530}
531
532fn default_log_level() -> String {
533    "info".to_string()
534}
535
536const fn default_check_interval() -> u64 {
537    1 // 1 hour
538}
539
540const fn default_staged_rollout_hours() -> u64 {
541    24 // 24 hour window for staged rollout
542}
543
544// ============================================================================
545// Storage Configuration
546// ============================================================================
547
548/// Storage configuration for chunk persistence.
549///
550/// Controls how chunks are stored, including:
551/// - Whether storage is enabled
552/// - Content verification on read
553/// - Database size limits (auto-scales with available disk by default)
554#[derive(Debug, Clone, Serialize, Deserialize)]
555pub struct StorageConfig {
556    /// Enable chunk storage.
557    /// Default: true
558    #[serde(default = "default_storage_enabled")]
559    pub enabled: bool,
560
561    /// Verify content hash matches address on read.
562    /// Default: true
563    #[serde(default = "default_storage_verify_on_read")]
564    pub verify_on_read: bool,
565
566    /// Explicit LMDB database size cap in GiB.
567    ///
568    /// When set to 0 (default), the map size is computed automatically from
569    /// available disk space at startup and grows on demand when the operator
570    /// adds storage.  Set a non-zero value to impose a hard cap.
571    #[serde(default)]
572    pub db_size_gb: usize,
573
574    /// Minimum free disk space (in MiB) to preserve on the storage partition.
575    ///
576    /// Writes are refused when available space drops below this threshold,
577    /// preventing the node from filling the disk completely.  Default: 500 MiB.
578    #[serde(default = "default_disk_reserve_mb")]
579    pub disk_reserve_mb: u64,
580
581    /// Controls for moving this node off the legacy LMDB chunk store.
582    ///
583    /// The two release switches inside it are deliberately not serialised: see
584    /// [`MigrationConfig`].
585    #[serde(default)]
586    pub migration: MigrationConfig,
587}
588
589impl Default for StorageConfig {
590    fn default() -> Self {
591        Self {
592            enabled: default_storage_enabled(),
593            verify_on_read: default_storage_verify_on_read(),
594            db_size_gb: 0,
595            disk_reserve_mb: default_disk_reserve_mb(),
596            migration: MigrationConfig::default(),
597        }
598    }
599}
600
601/// Default: 500 MiB — matches `DEFAULT_DISK_RESERVE` in `storage::lmdb`.
602const fn default_disk_reserve_mb() -> u64 {
603    500
604}
605
606const fn default_storage_enabled() -> bool {
607    true
608}
609
610const fn default_storage_verify_on_read() -> bool {
611    true
612}
613
614// ============================================================================
615// Bootstrap Peers Configuration (shipped config file)
616// ============================================================================
617
618/// The filename for the bootstrap peers configuration file.
619pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
620
621/// Environment variable that overrides the bootstrap peers file search path.
622pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
623
624/// Bootstrap peers loaded from a shipped configuration file.
625///
626/// This file provides initial peers for first-time network joins.
627#[derive(Debug, Clone, Serialize, Deserialize)]
628pub struct BootstrapPeersConfig {
629    /// The bootstrap peer socket addresses.
630    #[serde(default)]
631    pub peers: Vec<SocketAddr>,
632}
633
634/// The source from which bootstrap peers were resolved.
635#[derive(Debug, Clone, PartialEq, Eq)]
636pub enum BootstrapSource {
637    /// Provided via `--bootstrap` CLI argument or `ANT_BOOTSTRAP` env var.
638    Cli,
639    /// Loaded from an explicit `--config` file.
640    ConfigFile,
641    /// Auto-discovered from a `bootstrap_peers.toml` file.
642    AutoDiscovered(PathBuf),
643    /// No bootstrap peers were found from any source.
644    None,
645}
646
647impl BootstrapPeersConfig {
648    /// Load bootstrap peers from a TOML file at the given path.
649    ///
650    /// # Errors
651    ///
652    /// Returns an error if the file cannot be read or contains invalid TOML.
653    pub fn from_file(path: &Path) -> crate::Result<Self> {
654        let content = std::fs::read_to_string(path)?;
655        toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
656    }
657
658    /// Search well-known locations for a `bootstrap_peers.toml` file and load it.
659    ///
660    /// Search order (first match wins):
661    /// 1. `$ANT_BOOTSTRAP_PEERS_PATH` environment variable (path to file)
662    /// 2. Same directory as the running executable
663    /// 3. Platform config directory (`~/.config/ant/` on Linux,
664    ///    `~/Library/Application Support/ant/` on macOS,
665    ///    `%APPDATA%\ant\` on Windows)
666    /// 4. System config: `/etc/ant/` (Unix only)
667    ///
668    /// Returns `None` if no file is found in any location.
669    #[must_use]
670    pub fn discover() -> Option<(Self, PathBuf)> {
671        if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
672            return Self::load_non_empty_candidate(PathBuf::from(env_path));
673        }
674
675        for path in Self::search_paths() {
676            if let Some(discovered) = Self::load_non_empty_candidate(path) {
677                return Some(discovered);
678            }
679        }
680
681        None
682    }
683
684    fn load_non_empty_candidate(path: PathBuf) -> Option<(Self, PathBuf)> {
685        if !path.is_file() {
686            return None;
687        }
688
689        match Self::from_file(&path) {
690            Ok(config) if !config.peers.is_empty() => Some((config, path)),
691            Ok(_) => None,
692            Err(err) => {
693                crate::logging::warn!(
694                    "Failed to load bootstrap peers from {}: {err}",
695                    path.display(),
696                );
697                None
698            }
699        }
700    }
701
702    /// Build the ordered list of candidate paths to search.
703    fn search_paths() -> Vec<PathBuf> {
704        let mut paths = Vec::new();
705
706        // 1. Environment variable override.
707        if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
708            paths.push(PathBuf::from(env_path));
709        }
710
711        // 2. Next to the running executable.
712        if let Ok(exe) = std::env::current_exe() {
713            if let Some(exe_dir) = exe.parent() {
714                paths.push(exe_dir.join(BOOTSTRAP_PEERS_FILENAME));
715            }
716        }
717
718        // 3. Platform config directory.
719        if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
720            paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
721        }
722
723        // 4. System config (Unix only).
724        #[cfg(unix)]
725        {
726            paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
727        }
728
729        paths
730    }
731}
732
733/// Default testnet bootstrap nodes.
734///
735/// These are well-known bootstrap nodes for the Autonomi testnet.
736/// - ant-bootstrap-1 (NYC): 165.22.4.178:12000
737/// - ant-bootstrap-2 (SFO): 164.92.111.156:12000
738fn default_testnet_bootstrap() -> Vec<SocketAddr> {
739    vec![
740        // ant-bootstrap-1 (Digital Ocean NYC1)
741        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
742        // ant-bootstrap-2 (Digital Ocean SFO3)
743        SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(164, 92, 111, 156), 12000)),
744    ]
745}
746
747#[cfg(test)]
748#[allow(clippy::unwrap_used, clippy::expect_used)]
749mod tests {
750
751    use super::*;
752    use serial_test::serial;
753
754    #[test]
755    fn the_shipped_storage_config_parses() {
756        // The migration section is operator-facing, so a typo in it would only surface on
757        // a node that had already shipped. Only `[storage]` is checked: the rest of
758        // `production.toml` does not currently deserialize as a `NodeConfig` (its
759        // `evm_network` is a bare string where an internally tagged enum is expected),
760        // which is a separate, pre-existing problem.
761        let raw = include_str!("../config/production.toml");
762        let doc: toml::Value = toml::from_str(raw).expect("production.toml must be valid TOML");
763        let storage = doc.get("storage").expect("a [storage] section").clone();
764        let config: StorageConfig = storage.try_into().expect("[storage] must deserialize");
765
766        assert!(config.migration.enabled);
767        assert!(config.migration.dual_write_legacy);
768        assert_eq!(config.migration.shed_hold_hours, 72);
769        assert_eq!(config.migration.copier_throttle_mib_per_sec, 32);
770        assert_eq!(config.migration.copier_slack_mb, 2048);
771        // The release switches are absent from the file on purpose, so they come from the
772        // build rather than from whatever an operator's config last recorded.
773        let build = MigrationConfig::default();
774        assert_eq!(config.migration.retire_legacy, build.retire_legacy);
775    }
776
777    #[test]
778    fn test_default_config_has_cache_capacity() {
779        let config = PaymentConfig::default();
780        assert!(config.cache_capacity > 0, "Cache capacity must be positive");
781    }
782
783    #[test]
784    fn default_webrtc_listener_tracks_compile_time_feature() {
785        let config = WebRtcDirectConfig::default();
786        assert_eq!(config.enabled, cfg!(feature = "webrtc-direct"));
787        assert_eq!(config.bind, "0.0.0.0:0".parse().expect("wildcard bind"));
788    }
789
790    #[test]
791    fn partial_webrtc_config_preserves_defaults_and_explicit_disable() {
792        let absent: NodeConfig = toml::from_str("").unwrap();
793        let partial: NodeConfig = toml::from_str("[webrtc_direct]\nmax_connections = 48").unwrap();
794        assert_eq!(partial.webrtc_direct.enabled, absent.webrtc_direct.enabled);
795        assert_eq!(partial.webrtc_direct.bind, absent.webrtc_direct.bind);
796        assert_eq!(partial.webrtc_direct.max_connections, 48);
797        let disabled: NodeConfig = toml::from_str("[webrtc_direct]\nenabled = false").unwrap();
798        assert!(!disabled.webrtc_direct.enabled);
799    }
800
801    #[test]
802    fn test_default_evm_network() {
803        use crate::payment::EvmVerifierConfig;
804        let _config = EvmVerifierConfig::default();
805        // EVM verification is always on — no enabled field
806    }
807
808    #[test]
809    fn test_bootstrap_peers_parse_valid_toml() {
810        let toml_str = r#"
811            peers = [
812                "127.0.0.1:10000",
813                "192.168.1.1:10001",
814            ]
815        "#;
816        let config: BootstrapPeersConfig =
817            toml::from_str(toml_str).expect("valid TOML should parse");
818        assert_eq!(config.peers.len(), 2);
819        assert_eq!(config.peers[0].port(), 10000);
820        assert_eq!(config.peers[1].port(), 10001);
821    }
822
823    #[test]
824    fn test_bootstrap_peers_parse_empty_peers() {
825        let toml_str = r"peers = []";
826        let config: BootstrapPeersConfig =
827            toml::from_str(toml_str).expect("empty peers should parse");
828        assert!(
829            config.peers.is_empty(),
830            "expected no peers, got {:?}",
831            config.peers
832        );
833    }
834
835    #[test]
836    fn test_bootstrap_peers_parse_missing_peers_field() {
837        let toml_str = "";
838        let config: BootstrapPeersConfig =
839            toml::from_str(toml_str).expect("missing field should use default");
840        assert!(
841            config.peers.is_empty(),
842            "expected no peers, got {:?}",
843            config.peers
844        );
845    }
846
847    #[test]
848    fn test_bootstrap_peers_from_file() {
849        let dir = tempfile::tempdir().expect("create temp dir");
850        let path = dir.path().join("bootstrap_peers.toml");
851        std::fs::write(&path, r#"peers = ["10.0.0.1:10000", "10.0.0.2:10000"]"#)
852            .expect("write file");
853
854        let config = BootstrapPeersConfig::from_file(&path).expect("load from file");
855        assert_eq!(config.peers.len(), 2);
856    }
857
858    #[test]
859    fn test_bootstrap_peers_from_file_invalid_toml() {
860        let dir = tempfile::tempdir().expect("create temp dir");
861        let path = dir.path().join("bootstrap_peers.toml");
862        std::fs::write(&path, "not valid toml [[[").expect("write file");
863
864        assert!(BootstrapPeersConfig::from_file(&path).is_err());
865    }
866
867    /// Env-var-based discovery tests must run serially because they mutate
868    /// a shared process-wide environment variable.
869    #[test]
870    #[serial]
871    fn test_bootstrap_peers_discover_env_var() {
872        // Sub-test 1: valid file with peers is discovered.
873        {
874            let dir = tempfile::tempdir().expect("create temp dir");
875            let path = dir.path().join("bootstrap_peers.toml");
876            std::fs::write(&path, r#"peers = ["10.0.0.1:10000"]"#).expect("write file");
877
878            std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
879            let result = BootstrapPeersConfig::discover();
880            std::env::remove_var(BOOTSTRAP_PEERS_ENV);
881
882            let (config, discovered_path) = result.expect("should discover from env var");
883            assert_eq!(config.peers.len(), 1);
884            assert_eq!(discovered_path, path);
885        }
886
887        // Sub-test 2: file with empty peers list is skipped.
888        {
889            let dir = tempfile::tempdir().expect("create temp dir");
890            let path = dir.path().join("bootstrap_peers.toml");
891            std::fs::write(&path, r"peers = []").expect("write file");
892
893            std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
894            let result = BootstrapPeersConfig::discover();
895            std::env::remove_var(BOOTSTRAP_PEERS_ENV);
896
897            assert!(result.is_none(), "empty peers file should be skipped");
898        }
899    }
900
901    #[test]
902    fn test_bootstrap_peers_search_paths_contains_exe_dir() {
903        let paths = BootstrapPeersConfig::search_paths();
904        // At minimum, the exe-dir candidate should be present.
905        assert!(
906            paths
907                .iter()
908                .any(|p| p.file_name().is_some_and(|f| f == BOOTSTRAP_PEERS_FILENAME)),
909            "search paths should include a candidate with the bootstrap peers filename"
910        );
911    }
912}