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 webrtc_direct: WebRtcDirectConfig,
130
131 #[serde(default)]
136 pub close_group_cache_dir: Option<PathBuf>,
137
138 #[serde(default = "default_max_message_size")]
147 pub max_message_size: usize,
148
149 #[serde(default = "default_log_level")]
151 pub log_level: String,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(default)]
161pub struct WebRtcDirectConfig {
162 pub enabled: bool,
164
165 pub bind: SocketAddr,
167
168 pub advertised_addr: Option<SocketAddr>,
174
175 pub certificate_path: Option<PathBuf>,
180
181 pub max_connections: usize,
183
184 pub max_connections_per_ip: usize,
189
190 pub max_channels_per_connection: usize,
192
193 pub max_channels: usize,
198
199 pub max_concurrent_requests: usize,
201
202 pub max_requests_per_second: usize,
204
205 pub max_requests_per_second_per_ip: usize,
207
208 pub max_requests_per_second_per_connection: usize,
211
212 pub max_in_flight_bytes: usize,
215
216 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#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct UpgradeConfig {
289 #[serde(default)]
291 pub channel: UpgradeChannel,
292
293 #[serde(default = "default_check_interval")]
295 pub check_interval_hours: u64,
296
297 #[serde(default = "default_github_repo")]
299 pub github_repo: String,
300
301 #[serde(default = "default_staged_rollout_hours")]
309 pub staged_rollout_hours: u64,
310
311 #[serde(default)]
318 pub stop_on_upgrade: bool,
319}
320
321#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
329#[serde(rename_all = "kebab-case", tag = "type")]
330pub enum EvmNetworkConfig {
331 #[default]
333 ArbitrumOne,
334 ArbitrumSepolia,
336 Custom {
339 rpc_url: String,
341 payment_token_address: String,
343 payment_vault_address: String,
345 },
346}
347
348impl EvmNetworkConfig {
349 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct PaymentConfig {
372 #[serde(default = "default_cache_capacity")]
374 pub cache_capacity: usize,
375
376 #[serde(default)]
379 pub rewards_address: Option<String>,
380
381 #[serde(default)]
383 pub evm_network: EvmNetworkConfig,
384
385 #[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 #[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 #[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 #[must_use]
463 pub fn is_relaxed(&self) -> bool {
464 !matches!(self.network_mode, NetworkMode::Production)
465 }
466
467 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 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#[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#[must_use]
520pub fn default_nodes_dir() -> PathBuf {
521 default_root_dir().join(NODES_SUBDIR)
522}
523
524fn default_max_message_size() -> usize {
525 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 }
539
540const fn default_staged_rollout_hours() -> u64 {
541 24 }
543
544#[derive(Debug, Clone, Serialize, Deserialize)]
555pub struct StorageConfig {
556 #[serde(default = "default_storage_enabled")]
559 pub enabled: bool,
560
561 #[serde(default = "default_storage_verify_on_read")]
564 pub verify_on_read: bool,
565
566 #[serde(default)]
572 pub db_size_gb: usize,
573
574 #[serde(default = "default_disk_reserve_mb")]
579 pub disk_reserve_mb: u64,
580
581 #[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
601const 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
614pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
620
621pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
623
624#[derive(Debug, Clone, Serialize, Deserialize)]
628pub struct BootstrapPeersConfig {
629 #[serde(default)]
631 pub peers: Vec<SocketAddr>,
632}
633
634#[derive(Debug, Clone, PartialEq, Eq)]
636pub enum BootstrapSource {
637 Cli,
639 ConfigFile,
641 AutoDiscovered(PathBuf),
643 None,
645}
646
647impl BootstrapPeersConfig {
648 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 #[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 fn search_paths() -> Vec<PathBuf> {
704 let mut paths = Vec::new();
705
706 if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
708 paths.push(PathBuf::from(env_path));
709 }
710
711 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 if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
720 paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
721 }
722
723 #[cfg(unix)]
725 {
726 paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
727 }
728
729 paths
730 }
731}
732
733fn default_testnet_bootstrap() -> Vec<SocketAddr> {
739 vec![
740 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
742 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 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 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 }
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 #[test]
870 #[serial]
871 fn test_bootstrap_peers_discover_env_var() {
872 {
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 {
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 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}