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>,
173
174 pub certificate_path: Option<PathBuf>,
179
180 pub max_connections: usize,
182
183 pub max_connections_per_ip: usize,
188
189 pub max_channels_per_connection: usize,
191
192 pub max_channels: usize,
197
198 pub max_concurrent_requests: usize,
200
201 pub max_requests_per_second: usize,
203
204 pub max_requests_per_second_per_ip: usize,
206
207 pub max_requests_per_second_per_connection: usize,
210
211 pub max_in_flight_bytes: usize,
214
215 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 256
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 512
259}
260
261const fn default_webrtc_direct_max_concurrent_requests() -> usize {
262 512
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#[derive(Debug, Clone, Serialize, Deserialize)]
287pub struct UpgradeConfig {
288 #[serde(default)]
290 pub channel: UpgradeChannel,
291
292 #[serde(default = "default_check_interval")]
294 pub check_interval_hours: u64,
295
296 #[serde(default = "default_github_repo")]
298 pub github_repo: String,
299
300 #[serde(default = "default_staged_rollout_hours")]
308 pub staged_rollout_hours: u64,
309
310 #[serde(default)]
317 pub stop_on_upgrade: bool,
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
328#[serde(rename_all = "kebab-case", tag = "type")]
329pub enum EvmNetworkConfig {
330 #[default]
332 ArbitrumOne,
333 ArbitrumSepolia,
335 Custom {
338 rpc_url: String,
340 payment_token_address: String,
342 payment_vault_address: String,
344 },
345}
346
347impl EvmNetworkConfig {
348 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct PaymentConfig {
371 #[serde(default = "default_cache_capacity")]
373 pub cache_capacity: usize,
374
375 #[serde(default)]
378 pub rewards_address: Option<String>,
379
380 #[serde(default)]
382 pub evm_network: EvmNetworkConfig,
383
384 #[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 #[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 #[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 #[must_use]
462 pub fn is_relaxed(&self) -> bool {
463 !matches!(self.network_mode, NetworkMode::Production)
464 }
465
466 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 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#[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#[must_use]
519pub fn default_nodes_dir() -> PathBuf {
520 default_root_dir().join(NODES_SUBDIR)
521}
522
523fn default_max_message_size() -> usize {
524 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 }
538
539const fn default_staged_rollout_hours() -> u64 {
540 24 }
542
543#[derive(Debug, Clone, Serialize, Deserialize)]
554pub struct StorageConfig {
555 #[serde(default = "default_storage_enabled")]
558 pub enabled: bool,
559
560 #[serde(default = "default_storage_verify_on_read")]
563 pub verify_on_read: bool,
564
565 #[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
583const 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
596pub const BOOTSTRAP_PEERS_FILENAME: &str = "bootstrap_peers.toml";
602
603pub const BOOTSTRAP_PEERS_ENV: &str = "ANT_BOOTSTRAP_PEERS_PATH";
605
606#[derive(Debug, Clone, Serialize, Deserialize)]
610pub struct BootstrapPeersConfig {
611 #[serde(default)]
613 pub peers: Vec<SocketAddr>,
614}
615
616#[derive(Debug, Clone, PartialEq, Eq)]
618pub enum BootstrapSource {
619 Cli,
621 ConfigFile,
623 AutoDiscovered(PathBuf),
625 None,
627}
628
629impl BootstrapPeersConfig {
630 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 #[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 fn search_paths() -> Vec<PathBuf> {
686 let mut paths = Vec::new();
687
688 if let Ok(env_path) = std::env::var(BOOTSTRAP_PEERS_ENV) {
690 paths.push(PathBuf::from(env_path));
691 }
692
693 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 if let Some(proj_dirs) = directories::ProjectDirs::from("", "", "ant") {
702 paths.push(proj_dirs.config_dir().join(BOOTSTRAP_PEERS_FILENAME));
703 }
704
705 #[cfg(unix)]
707 {
708 paths.push(PathBuf::from("/etc/ant").join(BOOTSTRAP_PEERS_FILENAME));
709 }
710
711 paths
712 }
713}
714
715fn default_testnet_bootstrap() -> Vec<SocketAddr> {
721 vec![
722 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(165, 22, 4, 178), 12000)),
724 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 #[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 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 }
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 #[test]
879 #[serial]
880 fn test_bootstrap_peers_discover_env_var() {
881 {
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 {
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 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}