Skip to main content

ant_node/
config.rs

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