1use evmlib::Network as EvmNetwork;
4use serde::{Deserialize, Serialize};
5use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
6use std::path::{Path, PathBuf};
7
8pub const NODE_IDENTITY_FILENAME: &str = "node_identity.key";
10
11pub const NODES_SUBDIR: &str = "nodes";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum UpgradeChannel {
18 #[default]
20 Stable,
21 Beta,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
27#[serde(rename_all = "lowercase")]
28pub enum NetworkMode {
29 #[default]
31 Production,
32 Testnet,
35 Development,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct TestnetConfig {
47 #[serde(default = "default_testnet_max_per_ip")]
50 pub max_per_ip: Option<usize>,
51
52 #[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct NodeConfig {
82 #[serde(default = "default_root_dir")]
84 pub root_dir: PathBuf,
85
86 #[serde(default)]
88 pub port: u16,
89
90 #[serde(default)]
96 pub ipv4_only: bool,
97
98 #[serde(default)]
100 pub bootstrap: Vec<SocketAddr>,
101
102 #[serde(default)]
104 pub network_mode: NetworkMode,
105
106 #[serde(default)]
109 pub testnet: TestnetConfig,
110
111 #[serde(default)]
113 pub upgrade: UpgradeConfig,
114
115 #[serde(default)]
117 pub payment: PaymentConfig,
118
119 #[serde(default)]
121 pub storage: StorageConfig,
122
123 #[serde(default)]
128 pub webrtc_direct: WebRtcDirectConfig,
129
130 #[serde(default)]
135 pub close_group_cache_dir: Option<PathBuf>,
136
137 #[serde(default = "default_max_message_size")]
146 pub max_message_size: usize,
147
148 #[serde(default = "default_log_level")]
150 pub log_level: String,
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
159#[serde(default)]
160pub struct WebRtcDirectConfig {
161 pub enabled: bool,
163
164 pub bind: SocketAddr,
166
167 pub advertised_addr: Option<SocketAddr>,
179
180 pub certificate_path: Option<PathBuf>,
185
186 pub max_connections: usize,
188
189 pub max_connections_per_ip: usize,
194
195 pub max_channels_per_connection: usize,
197
198 pub max_channels: usize,
203
204 pub max_concurrent_requests: usize,
206
207 pub max_requests_per_second: usize,
209
210 pub max_requests_per_second_per_ip: usize,
212
213 pub max_requests_per_second_per_connection: usize,
216
217 pub max_in_flight_bytes: usize,
220
221 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#[derive(Debug, Clone, Serialize, Deserialize)]
293pub struct UpgradeConfig {
294 #[serde(default)]
296 pub channel: UpgradeChannel,
297
298 #[serde(default = "default_check_interval")]
300 pub check_interval_hours: u64,
301
302 #[serde(default = "default_github_repo")]
304 pub github_repo: String,
305
306 #[serde(default = "default_staged_rollout_hours")]
314 pub staged_rollout_hours: u64,
315
316 #[serde(default)]
323 pub stop_on_upgrade: bool,
324}
325
326#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
334#[serde(rename_all = "kebab-case", tag = "type")]
335pub enum EvmNetworkConfig {
336 #[default]
338 ArbitrumOne,
339 ArbitrumSepolia,
341 Custom {
344 rpc_url: String,
346 payment_token_address: String,
348 payment_vault_address: String,
350 },
351}
352
353impl EvmNetworkConfig {
354 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct PaymentConfig {
377 #[serde(default = "default_cache_capacity")]
379 pub cache_capacity: usize,
380
381 #[serde(default)]
384 pub rewards_address: Option<String>,
385
386 #[serde(default)]
388 pub evm_network: EvmNetworkConfig,
389
390 #[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 #[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 #[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 #[must_use]
468 pub fn is_relaxed(&self) -> bool {
469 !matches!(self.network_mode, NetworkMode::Production)
470 }
471
472 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 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#[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#[must_use]
525pub fn default_nodes_dir() -> PathBuf {
526 default_root_dir().join(NODES_SUBDIR)
527}
528
529fn default_max_message_size() -> usize {
530 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 }
544
545const fn default_staged_rollout_hours() -> u64 {
546 24 }
548
549#[derive(Debug, Clone, Serialize, Deserialize)]
560pub struct StorageConfig {
561 #[serde(default = "default_storage_enabled")]
564 pub enabled: bool,
565
566 #[serde(default = "default_storage_verify_on_read")]
569 pub verify_on_read: bool,
570
571 #[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
589const 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
602pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
608
609pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
611
612#[derive(Debug, Clone, Serialize, Deserialize)]
616pub struct BootstrapPeersConfig {
617 #[serde(default)]
619 pub peers: Vec<SocketAddr>,
620}
621
622#[derive(Debug, Clone, PartialEq, Eq)]
624pub enum BootstrapSource {
625 Cli,
627 ConfigFile,
629 AutoDiscovered(PathBuf),
631 None,
633}
634
635impl BootstrapPeersConfig {
636 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 #[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 fn search_paths() -> Vec<PathBuf> {
692 let mut paths = Vec::new();
693
694 if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
696 paths.push(PathBuf::from(env_path));
697 }
698
699 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 if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
708 paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
709 }
710
711 #[cfg(unix)]
713 {
714 paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
715 }
716
717 paths
718 }
719}
720
721fn default_testnet_bootstrap() -> Vec<SocketAddr> {
727 vec![
728 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
730 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 #[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 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 }
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 #[test]
885 #[serial]
886 fn test_bootstrap_peers_discover_env_var() {
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 = ["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 {
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 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}