1use crate::storage::MigrationConfig;
4use evmlib::Network as EvmNetwork;
5use serde::{Deserialize, Serialize};
6use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
7use std::path::{Path, PathBuf};
8
9pub const NODE_IDENTITY_FILENAME: &str = "node_identity.key";
11
12pub const NODES_SUBDIR: &str = "nodes";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum UpgradeChannel {
19 #[default]
21 Stable,
22 Beta,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
28#[serde(rename_all = "lowercase")]
29pub enum NetworkMode {
30 #[default]
32 Production,
33 Testnet,
36 Development,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct TestnetConfig {
48 #[serde(default = "default_testnet_max_per_ip")]
51 pub max_per_ip: Option<usize>,
52
53 #[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct NodeConfig {
83 #[serde(default = "default_root_dir")]
85 pub root_dir: PathBuf,
86
87 #[serde(default)]
89 pub port: u16,
90
91 #[serde(default)]
97 pub ipv4_only: bool,
98
99 #[serde(default)]
101 pub bootstrap: Vec<SocketAddr>,
102
103 #[serde(default)]
105 pub network_mode: NetworkMode,
106
107 #[serde(default)]
110 pub testnet: TestnetConfig,
111
112 #[serde(default)]
114 pub upgrade: UpgradeConfig,
115
116 #[serde(default)]
118 pub payment: PaymentConfig,
119
120 #[serde(default)]
122 pub storage: StorageConfig,
123
124 #[serde(default)]
129 pub close_group_cache_dir: Option<PathBuf>,
130
131 #[serde(default = "default_max_message_size")]
140 pub max_message_size: usize,
141
142 #[serde(default = "default_log_level")]
144 pub log_level: String,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct UpgradeConfig {
150 #[serde(default)]
152 pub channel: UpgradeChannel,
153
154 #[serde(default = "default_check_interval")]
156 pub check_interval_hours: u64,
157
158 #[serde(default = "default_github_repo")]
160 pub github_repo: String,
161
162 #[serde(default = "default_staged_rollout_hours")]
170 pub staged_rollout_hours: u64,
171
172 #[serde(default)]
179 pub stop_on_upgrade: bool,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
190#[serde(rename_all = "kebab-case", tag = "type")]
191pub enum EvmNetworkConfig {
192 #[default]
194 ArbitrumOne,
195 ArbitrumSepolia,
197 Custom {
200 rpc_url: String,
202 payment_token_address: String,
204 payment_vault_address: String,
206 },
207}
208
209impl EvmNetworkConfig {
210 #[must_use]
213 pub fn into_evm_network(self) -> EvmNetwork {
214 match self {
215 Self::ArbitrumOne => EvmNetwork::ArbitrumOne,
216 Self::ArbitrumSepolia => EvmNetwork::ArbitrumSepoliaTest,
217 Self::Custom {
218 rpc_url,
219 payment_token_address,
220 payment_vault_address,
221 } => EvmNetwork::new_custom(&rpc_url, &payment_token_address, &payment_vault_address),
222 }
223 }
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct PaymentConfig {
233 #[serde(default = "default_cache_capacity")]
235 pub cache_capacity: usize,
236
237 #[serde(default)]
240 pub rewards_address: Option<String>,
241
242 #[serde(default)]
244 pub evm_network: EvmNetworkConfig,
245
246 #[serde(default = "default_metrics_port")]
249 pub metrics_port: u16,
250}
251
252impl Default for PaymentConfig {
253 fn default() -> Self {
254 Self {
255 cache_capacity: default_cache_capacity(),
256 rewards_address: None,
257 evm_network: EvmNetworkConfig::default(),
258 metrics_port: default_metrics_port(),
259 }
260 }
261}
262
263const fn default_metrics_port() -> u16 {
264 9100
265}
266
267const fn default_cache_capacity() -> usize {
268 100_000
269}
270
271impl Default for NodeConfig {
272 fn default() -> Self {
273 Self {
274 root_dir: default_root_dir(),
275 port: 0,
276 ipv4_only: false,
277 bootstrap: Vec::new(),
278 network_mode: NetworkMode::default(),
279 testnet: TestnetConfig::default(),
280 upgrade: UpgradeConfig::default(),
281 payment: PaymentConfig::default(),
282 storage: StorageConfig::default(),
283 close_group_cache_dir: None,
284 max_message_size: default_max_message_size(),
285 log_level: default_log_level(),
286 }
287 }
288}
289
290impl NodeConfig {
291 #[must_use]
297 pub fn testnet() -> Self {
298 Self {
299 network_mode: NetworkMode::Testnet,
300 testnet: TestnetConfig::default(),
301 bootstrap: default_testnet_bootstrap(),
302 ..Self::default()
303 }
304 }
305
306 #[must_use]
310 pub fn development() -> Self {
311 Self {
312 network_mode: NetworkMode::Development,
313 testnet: TestnetConfig {
314 max_per_ip: Some(usize::MAX),
315 max_per_subnet: Some(usize::MAX),
316 },
317 ..Self::default()
318 }
319 }
320
321 #[must_use]
323 pub fn is_relaxed(&self) -> bool {
324 !matches!(self.network_mode, NetworkMode::Production)
325 }
326
327 pub fn from_file(path: &std::path::Path) -> crate::Result<Self> {
333 let content = std::fs::read_to_string(path)?;
334 toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
335 }
336
337 pub fn to_file(&self, path: &std::path::Path) -> crate::Result<()> {
343 let content =
344 toml::to_string_pretty(self).map_err(|e| crate::Error::Config(e.to_string()))?;
345 std::fs::write(path, content)?;
346 Ok(())
347 }
348}
349
350impl Default for UpgradeConfig {
351 fn default() -> Self {
352 Self {
353 channel: UpgradeChannel::default(),
354 check_interval_hours: default_check_interval(),
355 github_repo: default_github_repo(),
356 staged_rollout_hours: default_staged_rollout_hours(),
357 stop_on_upgrade: false,
358 }
359 }
360}
361
362fn default_github_repo() -> String {
363 "WithAutonomi/ant-node".to_string()
364}
365
366#[must_use]
368pub fn default_root_dir() -> PathBuf {
369 directories::ProjectDirs::from("", "", "ant").map_or_else(
370 || PathBuf::from(".ant"),
371 |dirs| dirs.data_dir().to_path_buf(),
372 )
373}
374
375#[must_use]
380pub fn default_nodes_dir() -> PathBuf {
381 default_root_dir().join(NODES_SUBDIR)
382}
383
384fn default_max_message_size() -> usize {
385 crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE
389 .max(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
390}
391
392fn default_log_level() -> String {
393 "info".to_string()
394}
395
396const fn default_check_interval() -> u64 {
397 1 }
399
400const fn default_staged_rollout_hours() -> u64 {
401 24 }
403
404#[derive(Debug, Clone, Serialize, Deserialize)]
415pub struct StorageConfig {
416 #[serde(default = "default_storage_enabled")]
419 pub enabled: bool,
420
421 #[serde(default = "default_storage_verify_on_read")]
424 pub verify_on_read: bool,
425
426 #[serde(default)]
432 pub db_size_gb: usize,
433
434 #[serde(default = "default_disk_reserve_mb")]
439 pub disk_reserve_mb: u64,
440
441 #[serde(default)]
446 pub migration: MigrationConfig,
447}
448
449impl Default for StorageConfig {
450 fn default() -> Self {
451 Self {
452 enabled: default_storage_enabled(),
453 verify_on_read: default_storage_verify_on_read(),
454 db_size_gb: 0,
455 disk_reserve_mb: default_disk_reserve_mb(),
456 migration: MigrationConfig::default(),
457 }
458 }
459}
460
461const fn default_disk_reserve_mb() -> u64 {
463 500
464}
465
466const fn default_storage_enabled() -> bool {
467 true
468}
469
470const fn default_storage_verify_on_read() -> bool {
471 true
472}
473
474pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
480
481pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
483
484#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct BootstrapPeersConfig {
489 #[serde(default)]
491 pub peers: Vec<SocketAddr>,
492}
493
494#[derive(Debug, Clone, PartialEq, Eq)]
496pub enum BootstrapSource {
497 Cli,
499 ConfigFile,
501 AutoDiscovered(PathBuf),
503 None,
505}
506
507impl BootstrapPeersConfig {
508 pub fn from_file(path: &Path) -> crate::Result<Self> {
514 let content = std::fs::read_to_string(path)?;
515 toml::from_str(&content).map_err(|e| crate::Error::Config(e.to_string()))
516 }
517
518 #[must_use]
530 pub fn discover() -> Option<(Self, PathBuf)> {
531 if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
532 return Self::load_non_empty_candidate(PathBuf::from(env_path));
533 }
534
535 for path in Self::search_paths() {
536 if let Some(discovered) = Self::load_non_empty_candidate(path) {
537 return Some(discovered);
538 }
539 }
540
541 None
542 }
543
544 fn load_non_empty_candidate(path: PathBuf) -> Option<(Self, PathBuf)> {
545 if !path.is_file() {
546 return None;
547 }
548
549 match Self::from_file(&path) {
550 Ok(config) if !config.peers.is_empty() => Some((config, path)),
551 Ok(_) => None,
552 Err(err) => {
553 crate::logging::warn!(
554 "Failed to load bootstrap peers from {}: {err}",
555 path.display(),
556 );
557 None
558 }
559 }
560 }
561
562 fn search_paths() -> Vec<PathBuf> {
564 let mut paths = Vec::new();
565
566 if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
568 paths.push(PathBuf::from(env_path));
569 }
570
571 if let Ok(exe) = std::env::current_exe() {
573 if let Some(exe_dir) = exe.parent() {
574 paths.push(exe_dir.join(BOOTSTRAP_PEERS_FILENAME));
575 }
576 }
577
578 if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
580 paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
581 }
582
583 #[cfg(unix)]
585 {
586 paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
587 }
588
589 paths
590 }
591}
592
593fn default_testnet_bootstrap() -> Vec<SocketAddr> {
599 vec![
600 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
602 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(164, 92, 111, 156), 12000)),
604 ]
605}
606
607#[cfg(test)]
608#[allow(clippy::unwrap_used, clippy::expect_used)]
609mod tests {
610
611 use super::*;
612 use serial_test::serial;
613
614 #[test]
615 fn the_shipped_storage_config_parses() {
616 let raw = include_str!("../config/production.toml");
622 let doc: toml::Value = toml::from_str(raw).expect("production.toml must be valid TOML");
623 let storage = doc.get("storage").expect("a [storage] section").clone();
624 let config: StorageConfig = storage.try_into().expect("[storage] must deserialize");
625
626 assert!(config.migration.enabled);
627 assert!(config.migration.dual_write_legacy);
628 assert_eq!(config.migration.shed_hold_hours, 72);
629 assert_eq!(config.migration.copier_throttle_mib_per_sec, 32);
630 assert_eq!(config.migration.copier_slack_mb, 2048);
631 let build = MigrationConfig::default();
634 assert_eq!(config.migration.retire_legacy, build.retire_legacy);
635 }
636
637 #[test]
638 fn test_default_config_has_cache_capacity() {
639 let config = PaymentConfig::default();
640 assert!(config.cache_capacity > 0, "Cache capacity must be positive");
641 }
642
643 #[test]
644 fn test_default_evm_network() {
645 use crate::payment::EvmVerifierConfig;
646 let _config = EvmVerifierConfig::default();
647 }
649
650 #[test]
651 fn test_bootstrap_peers_parse_valid_toml() {
652 let toml_str = r#"
653 peers = [
654 "127.0.0.1:10000",
655 "192.168.1.1:10001",
656 ]
657 "#;
658 let config: BootstrapPeersConfig =
659 toml::from_str(toml_str).expect("valid TOML should parse");
660 assert_eq!(config.peers.len(), 2);
661 assert_eq!(config.peers[0].port(), 10000);
662 assert_eq!(config.peers[1].port(), 10001);
663 }
664
665 #[test]
666 fn test_bootstrap_peers_parse_empty_peers() {
667 let toml_str = r"peers = []";
668 let config: BootstrapPeersConfig =
669 toml::from_str(toml_str).expect("empty peers should parse");
670 assert!(config.peers.is_empty());
671 }
672
673 #[test]
674 fn test_bootstrap_peers_parse_missing_peers_field() {
675 let toml_str = "";
676 let config: BootstrapPeersConfig =
677 toml::from_str(toml_str).expect("missing field should use default");
678 assert!(config.peers.is_empty());
679 }
680
681 #[test]
682 fn test_bootstrap_peers_from_file() {
683 let dir = tempfile::tempdir().expect("create temp dir");
684 let path = dir.path().join("bootstrap_peers.toml");
685 std::fs::write(&path, r#"peers = ["10.0.0.1:10000", "10.0.0.2:10000"]"#)
686 .expect("write file");
687
688 let config = BootstrapPeersConfig::from_file(&path).expect("load from file");
689 assert_eq!(config.peers.len(), 2);
690 }
691
692 #[test]
693 fn test_bootstrap_peers_from_file_invalid_toml() {
694 let dir = tempfile::tempdir().expect("create temp dir");
695 let path = dir.path().join("bootstrap_peers.toml");
696 std::fs::write(&path, "not valid toml [[[").expect("write file");
697
698 assert!(BootstrapPeersConfig::from_file(&path).is_err());
699 }
700
701 #[test]
704 #[serial]
705 fn test_bootstrap_peers_discover_env_var() {
706 {
708 let dir = tempfile::tempdir().expect("create temp dir");
709 let path = dir.path().join("bootstrap_peers.toml");
710 std::fs::write(&path, r#"peers = ["10.0.0.1:10000"]"#).expect("write file");
711
712 std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
713 let result = BootstrapPeersConfig::discover();
714 std::env::remove_var(BOOTSTRAP_PEERS_ENV);
715
716 let (config, discovered_path) = result.expect("should discover from env var");
717 assert_eq!(config.peers.len(), 1);
718 assert_eq!(discovered_path, path);
719 }
720
721 {
723 let dir = tempfile::tempdir().expect("create temp dir");
724 let path = dir.path().join("bootstrap_peers.toml");
725 std::fs::write(&path, r"peers = []").expect("write file");
726
727 std::env::set_var(BOOTSTRAP_PEERS_ENV, &path);
728 let result = BootstrapPeersConfig::discover();
729 std::env::remove_var(BOOTSTRAP_PEERS_ENV);
730
731 assert!(result.is_none(), "empty peers file should be skipped");
732 }
733 }
734
735 #[test]
736 fn test_bootstrap_peers_search_paths_contains_exe_dir() {
737 let paths = BootstrapPeersConfig::search_paths();
738 assert!(
740 paths
741 .iter()
742 .any(|p| p.file_name().is_some_and(|f| f == BOOTSTRAP_PEERS_FILENAME)),
743 "search paths should include a candidate with the bootstrap peers filename"
744 );
745 }
746}