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