zlayer-overlay 0.10.80

Encrypted overlay networking for containers using boringtun userspace WireGuard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! Overlay network bootstrap functionality
//!
//! Provides initialization and joining capabilities for overlay networks,
//! including keypair generation, interface creation, and peer management.

use crate::allocator::IpAllocator;
use crate::config::PeerInfo;
use crate::dns::{peer_hostname, DnsConfig, DnsHandle, DnsServer, DEFAULT_DNS_PORT};
use crate::error::{OverlayError, Result};
#[cfg(feature = "nat")]
use crate::nat::{Candidate, ConnectionType, NatTraversal, RelayServer};
use crate::transport::OverlayTransport;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::{debug, info, warn};

/// Default overlay interface name for `ZLayer`
///
/// On macOS, this is `"utun"` which tells boringtun to let the kernel
/// auto-assign a `utunN` device. On Linux, a custom name is used.
#[cfg(target_os = "macos")]
pub const DEFAULT_INTERFACE_NAME: &str = "utun";
#[cfg(not(target_os = "macos"))]
pub const DEFAULT_INTERFACE_NAME: &str = "zl-overlay0";

/// Default overlay listen port (re-exported from `zlayer-core`).
pub use zlayer_core::DEFAULT_WG_PORT;

/// Default overlay network CIDR (IPv4)
pub const DEFAULT_OVERLAY_CIDR: &str = "10.200.0.0/16";

/// Default overlay network CIDR (IPv6)
///
/// Uses a ULA (Unique Local Address) prefix in the `fd00::/8` range.
/// The `fd00:200::/48` prefix mirrors the IPv4 `10.200.0.0/16` convention.
pub const DEFAULT_OVERLAY_CIDR_V6: &str = "fd00:200::/48";

/// Default persistent keepalive interval (seconds)
pub const DEFAULT_KEEPALIVE_SECS: u16 = 25;

/// Overlay network bootstrap configuration
///
/// Contains all configuration needed to initialize and manage
/// an overlay network on a node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapConfig {
    /// Network CIDR (e.g., "10.200.0.0/16")
    pub cidr: String,

    /// This node's overlay IP address (IPv4 or IPv6)
    pub node_ip: IpAddr,

    /// Overlay interface name
    pub interface: String,

    /// Overlay listen port
    pub port: u16,

    /// This node's overlay private key
    pub private_key: String,

    /// This node's overlay public key
    pub public_key: String,

    /// Whether this node is the cluster leader
    pub is_leader: bool,

    /// Creation timestamp (Unix epoch seconds)
    pub created_at: u64,
}

impl BootstrapConfig {
    /// Get the overlay IP with host prefix for allowed IPs
    ///
    /// Returns `/32` for IPv4 addresses and `/128` for IPv6 addresses.
    #[must_use]
    pub fn allowed_ip(&self) -> String {
        let prefix = match self.node_ip {
            IpAddr::V4(_) => 32,
            IpAddr::V6(_) => 128,
        };
        format!("{}/{}", self.node_ip, prefix)
    }
}

/// Peer configuration for overlay network
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerConfig {
    /// Peer's node ID (for identification)
    pub node_id: String,

    /// Peer's overlay public key
    pub public_key: String,

    /// Peer's public endpoint (host:port)
    pub endpoint: String,

    /// Peer's overlay IP address (IPv4 or IPv6)
    pub overlay_ip: IpAddr,

    /// Optional persistent keepalive interval in seconds
    #[serde(default)]
    pub keepalive: Option<u16>,

    /// Optional custom DNS hostname for this peer (without zone suffix)
    /// If provided, the peer will be registered with this name in addition
    /// to the auto-generated IP-based hostname.
    #[serde(default)]
    pub hostname: Option<String>,

    /// NAT traversal candidates for this peer
    #[serde(default)]
    #[cfg(feature = "nat")]
    pub candidates: Vec<Candidate>,

    /// How this peer is currently connected
    #[serde(default)]
    #[cfg(feature = "nat")]
    pub connection_type: ConnectionType,
}

impl PeerConfig {
    /// Create a new peer configuration
    #[must_use]
    pub fn new(node_id: String, public_key: String, endpoint: String, overlay_ip: IpAddr) -> Self {
        Self {
            node_id,
            public_key,
            endpoint,
            overlay_ip,
            keepalive: Some(DEFAULT_KEEPALIVE_SECS),
            hostname: None,
            #[cfg(feature = "nat")]
            candidates: Vec::new(),
            #[cfg(feature = "nat")]
            connection_type: ConnectionType::default(),
        }
    }

    /// Set a custom DNS hostname for this peer
    #[must_use]
    pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self {
        self.hostname = Some(hostname.into());
        self
    }

    /// Convert to `PeerInfo` for overlay transport configuration
    ///
    /// # Errors
    ///
    /// Returns an error if the endpoint address cannot be parsed.
    pub fn to_peer_info(&self) -> std::result::Result<PeerInfo, Box<dyn std::error::Error>> {
        let endpoint: SocketAddr = self.endpoint.parse()?;
        let keepalive =
            Duration::from_secs(u64::from(self.keepalive.unwrap_or(DEFAULT_KEEPALIVE_SECS)));
        let prefix = match self.overlay_ip {
            IpAddr::V4(_) => 32,
            IpAddr::V6(_) => 128,
        };

        Ok(PeerInfo::new(
            self.public_key.clone(),
            endpoint,
            &format!("{}/{}", self.overlay_ip, prefix),
            keepalive,
        ))
    }
}

/// Persistent state for the overlay bootstrap
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapState {
    /// Bootstrap configuration
    pub config: BootstrapConfig,

    /// List of configured peers
    pub peers: Vec<PeerConfig>,

    /// IP allocator state (only for leader)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allocator_state: Option<crate::allocator::IpAllocatorState>,
}

/// Bootstrap manager for overlay network
///
/// Handles overlay network initialization, peer management,
/// and overlay transport interface configuration.
pub struct OverlayBootstrap {
    /// Bootstrap configuration
    config: BootstrapConfig,

    /// Configured peers
    peers: Vec<PeerConfig>,

    /// Data directory for persistent state
    data_dir: PathBuf,

    /// IP allocator (only for leader nodes)
    allocator: Option<IpAllocator>,

    /// DNS configuration (opt-in)
    dns_config: Option<DnsConfig>,

    /// DNS handle for managing records (available after `start()` if DNS enabled)
    dns_handle: Option<DnsHandle>,

    /// Overlay transport (boringtun device handle).
    ///
    /// Must be kept alive for the overlay network lifetime; dropping the
    /// transport destroys the TUN device.
    transport: Option<OverlayTransport>,

    /// NAT traversal orchestrator (available after `start()` if NAT is enabled)
    #[cfg(feature = "nat")]
    nat_traversal: Option<NatTraversal>,

    /// Built-in relay server (available after `start()` if relay is configured)
    #[cfg(feature = "nat")]
    relay_server: Option<RelayServer>,
}

impl OverlayBootstrap {
    /// Initialize as cluster leader (first node in the overlay)
    ///
    /// This generates a new overlay keypair, allocates the first IP
    /// in the CIDR range, and prepares the node as the overlay leader.
    ///
    /// # Arguments
    /// * `cidr` - Overlay network CIDR (e.g., "10.200.0.0/16")
    /// * `port` - Overlay listen port
    /// * `data_dir` - Directory for persistent state
    ///
    /// # Example
    /// ```ignore
    /// let bootstrap = OverlayBootstrap::init_leader(
    ///     "10.200.0.0/16",
    ///     51820,
    ///     Path::new("/var/lib/zlayer"),
    /// ).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if already initialized, key generation fails, or state cannot be saved.
    pub async fn init_leader(cidr: &str, port: u16, data_dir: &Path) -> Result<Self> {
        // Check if already initialized
        let config_path = data_dir.join("overlay_bootstrap.json");
        if config_path.exists() {
            return Err(OverlayError::AlreadyInitialized(
                config_path.display().to_string(),
            ));
        }

        // Ensure data directory exists
        tokio::fs::create_dir_all(data_dir).await?;

        // Generate overlay keypair
        info!("Generating overlay keypair for leader");
        let (private_key, public_key) = OverlayTransport::generate_keys()
            .await
            .map_err(|e| OverlayError::TransportCommand(e.to_string()))?;

        // Initialize IP allocator and allocate first IP for leader
        let mut allocator = IpAllocator::new(cidr)?;
        let node_ip = allocator.allocate_first()?;

        info!(node_ip = %node_ip, cidr = cidr, "Allocated leader IP");

        // Create config
        let config = BootstrapConfig {
            cidr: cidr.to_string(),
            node_ip,
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port,
            private_key,
            public_key,
            is_leader: true,
            created_at: current_timestamp(),
        };

        let bootstrap = Self {
            config,
            peers: Vec::new(),
            data_dir: data_dir.to_path_buf(),
            allocator: Some(allocator),
            dns_config: None,
            dns_handle: None,
            transport: None,
            #[cfg(feature = "nat")]
            nat_traversal: None,
            #[cfg(feature = "nat")]
            relay_server: None,
        };

        // Persist state
        bootstrap.save().await?;

        Ok(bootstrap)
    }

    /// Join an existing overlay network
    ///
    /// Generates a new overlay keypair and configures this node
    /// to connect to an existing overlay network.
    ///
    /// # Arguments
    /// * `leader_cidr` - Leader's overlay network CIDR
    /// * `leader_endpoint` - Leader's public endpoint (host:port)
    /// * `leader_public_key` - Leader's overlay public key
    /// * `leader_overlay_ip` - Leader's overlay IP address
    /// * `allocated_ip` - IP address allocated for this node by the leader
    /// * `port` - Overlay listen port for this node
    /// * `data_dir` - Directory for persistent state
    ///
    /// # Errors
    ///
    /// Returns an error if already initialized, key generation fails, or state cannot be saved.
    pub async fn join(
        leader_cidr: &str,
        leader_endpoint: &str,
        leader_public_key: &str,
        leader_overlay_ip: IpAddr,
        allocated_ip: IpAddr,
        port: u16,
        data_dir: &Path,
    ) -> Result<Self> {
        // Check if already initialized
        let config_path = data_dir.join("overlay_bootstrap.json");
        if config_path.exists() {
            return Err(OverlayError::AlreadyInitialized(
                config_path.display().to_string(),
            ));
        }

        // Ensure data directory exists
        tokio::fs::create_dir_all(data_dir).await?;

        // Generate overlay keypair for this node
        info!("Generating overlay keypair for joining node");
        let (private_key, public_key) = OverlayTransport::generate_keys()
            .await
            .map_err(|e| OverlayError::TransportCommand(e.to_string()))?;

        // Create config
        let config = BootstrapConfig {
            cidr: leader_cidr.to_string(),
            node_ip: allocated_ip,
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port,
            private_key,
            public_key,
            is_leader: false,
            created_at: current_timestamp(),
        };

        // Add leader as the first peer
        let leader_peer = PeerConfig {
            node_id: "leader".to_string(),
            public_key: leader_public_key.to_string(),
            endpoint: leader_endpoint.to_string(),
            overlay_ip: leader_overlay_ip,
            keepalive: Some(DEFAULT_KEEPALIVE_SECS),
            hostname: None, // Leader gets its own DNS alias "leader.zone"
            #[cfg(feature = "nat")]
            candidates: Vec::new(),
            #[cfg(feature = "nat")]
            connection_type: ConnectionType::default(),
        };

        info!(
            leader_endpoint = leader_endpoint,
            overlay_ip = %allocated_ip,
            "Configured leader as peer"
        );

        let bootstrap = Self {
            config,
            peers: vec![leader_peer],
            data_dir: data_dir.to_path_buf(),
            allocator: None, // Workers don't manage IP allocation
            dns_config: None,
            dns_handle: None,
            transport: None,
            #[cfg(feature = "nat")]
            nat_traversal: None,
            #[cfg(feature = "nat")]
            relay_server: None,
        };

        // Persist state
        bootstrap.save().await?;

        Ok(bootstrap)
    }

    /// Load existing bootstrap state from disk
    ///
    /// # Errors
    ///
    /// Returns an error if the state file is missing, unreadable, or invalid.
    pub async fn load(data_dir: &Path) -> Result<Self> {
        let config_path = data_dir.join("overlay_bootstrap.json");

        if !config_path.exists() {
            return Err(OverlayError::NotInitialized);
        }

        let contents = tokio::fs::read_to_string(&config_path).await?;
        let state: BootstrapState = serde_json::from_str(&contents)?;

        let allocator = if let Some(alloc_state) = state.allocator_state {
            Some(IpAllocator::from_state(alloc_state)?)
        } else {
            None
        };

        Ok(Self {
            config: state.config,
            peers: state.peers,
            data_dir: data_dir.to_path_buf(),
            allocator,
            dns_config: None, // DNS config must be re-enabled after load
            dns_handle: None,
            transport: None,
            #[cfg(feature = "nat")]
            nat_traversal: None,
            #[cfg(feature = "nat")]
            relay_server: None,
        })
    }

    /// Save bootstrap state to disk
    ///
    /// # Errors
    ///
    /// Returns an error if serialization or file writing fails.
    pub async fn save(&self) -> Result<()> {
        let config_path = self.data_dir.join("overlay_bootstrap.json");

        let state = BootstrapState {
            config: self.config.clone(),
            peers: self.peers.clone(),
            allocator_state: self
                .allocator
                .as_ref()
                .map(super::allocator::IpAllocator::to_state),
        };

        let contents = serde_json::to_string_pretty(&state)?;
        tokio::fs::write(&config_path, contents).await?;

        debug!(path = %config_path.display(), "Saved bootstrap state");
        Ok(())
    }

    /// Enable DNS service discovery for the overlay network
    ///
    /// When DNS is enabled, peers are automatically registered with both:
    /// - An IP-based hostname: `node-X-Y.zone` (e.g., `node-0-5.overlay.local`)
    /// - A custom hostname if provided in `PeerConfig`
    ///
    /// The leader node additionally gets a `leader.zone` alias.
    ///
    /// # Arguments
    /// * `zone` - DNS zone (e.g., "overlay.local.")
    /// * `port` - DNS server port (default: 15353 to avoid conflicts)
    ///
    /// # Example
    /// ```ignore
    /// let bootstrap = OverlayBootstrap::init_leader(cidr, port, data_dir)
    ///     .await?
    ///     .with_dns("overlay.local.", 15353)?;
    /// bootstrap.start().await?;
    /// ```
    ///
    /// # Errors
    ///
    /// This method currently always succeeds but returns `Result` for API consistency.
    pub fn with_dns(mut self, zone: &str, port: u16) -> Result<Self> {
        self.dns_config = Some(DnsConfig {
            zone: zone.to_string(),
            port,
            bind_addr: self.config.node_ip,
        });
        Ok(self)
    }

    /// Enable DNS with default port (15353)
    ///
    /// # Errors
    ///
    /// This method currently always succeeds but returns `Result` for API consistency.
    pub fn with_dns_default(self, zone: &str) -> Result<Self> {
        self.with_dns(zone, DEFAULT_DNS_PORT)
    }

    /// Get the DNS handle for managing records
    ///
    /// Returns None if DNS is not enabled or `start()` hasn't been called yet.
    #[must_use]
    pub fn dns_handle(&self) -> Option<&DnsHandle> {
        self.dns_handle.as_ref()
    }

    /// Check if DNS is enabled
    #[must_use]
    pub fn dns_enabled(&self) -> bool {
        self.dns_config.is_some()
    }

    /// Start the overlay network (create and configure overlay transport)
    ///
    /// This creates the boringtun TUN interface, assigns the overlay IP,
    /// configures all known peers, and starts the DNS server if enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if interface creation, peer configuration, or DNS startup fails.
    pub async fn start(&mut self) -> Result<()> {
        info!(
            interface = %self.config.interface,
            overlay_ip = %self.config.node_ip,
            port = self.config.port,
            dns_enabled = self.dns_config.is_some(),
            "Starting overlay network"
        );

        // Convert our config to OverlayConfig
        let overlay_config = crate::config::OverlayConfig {
            local_endpoint: SocketAddr::new(
                std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
                self.config.port,
            ),
            private_key: self.config.private_key.clone(),
            public_key: self.config.public_key.clone(),
            overlay_cidr: self.config.allowed_ip(),
            peer_discovery_interval: Duration::from_secs(30),
            #[cfg(feature = "nat")]
            nat: crate::nat::NatConfig::default(),
        };

        #[cfg(feature = "nat")]
        let nat_config = overlay_config.nat.clone();

        // Create overlay transport
        let mut transport = OverlayTransport::new(overlay_config, self.config.interface.clone());

        // Create the interface
        transport
            .create_interface()
            .await
            .map_err(|e| OverlayError::TransportCommand(e.to_string()))?;

        // On macOS, the kernel assigns a utunN name that may differ from
        // the requested name. Update our config to reflect the actual name.
        let actual_name = transport.interface_name().to_string();
        if actual_name != self.config.interface {
            info!(
                requested = %self.config.interface,
                actual = %actual_name,
                "Interface name resolved by kernel"
            );
            self.config.interface = actual_name;
        }

        // Convert peers to PeerInfo
        let peer_infos: Vec<PeerInfo> = self
            .peers
            .iter()
            .filter_map(|p| match p.to_peer_info() {
                Ok(info) => Some(info),
                Err(e) => {
                    warn!(peer = %p.node_id, error = %e, "Failed to parse peer info");
                    None
                }
            })
            .collect();

        // Configure transport with peers
        transport
            .configure(&peer_infos)
            .await
            .map_err(|e| OverlayError::TransportCommand(e.to_string()))?;

        // Store the transport so the TUN device stays alive for the overlay
        // lifetime. Dropping the OverlayTransport destroys the boringtun device.
        self.transport = Some(transport);

        // NAT traversal: gather candidates and connect to peers
        #[cfg(feature = "nat")]
        self.start_nat_traversal(nat_config).await;

        // Start DNS server if configured
        self.start_dns().await?;

        info!("Overlay network started successfully");
        Ok(())
    }

    /// Start the DNS server and register all known peers.
    async fn start_dns(&mut self) -> Result<()> {
        let Some(dns_config) = &self.dns_config else {
            return Ok(());
        };

        info!(
            zone = %dns_config.zone,
            port = dns_config.port,
            "Starting DNS server for overlay"
        );

        let dns_server =
            DnsServer::from_config(dns_config).map_err(|e| OverlayError::Dns(e.to_string()))?;

        // Register self with IP-based hostname
        let self_hostname = peer_hostname(self.config.node_ip);
        dns_server
            .add_record(&self_hostname, self.config.node_ip)
            .await
            .map_err(|e| OverlayError::Dns(e.to_string()))?;

        // If leader, also register "leader" alias
        if self.config.is_leader {
            dns_server
                .add_record("leader", self.config.node_ip)
                .await
                .map_err(|e| OverlayError::Dns(e.to_string()))?;
            debug!(ip = %self.config.node_ip, "Registered leader.{}", dns_config.zone);
        }

        // Register existing peers
        for peer in &self.peers {
            // Always register IP-based hostname
            let hostname = peer_hostname(peer.overlay_ip);
            dns_server
                .add_record(&hostname, peer.overlay_ip)
                .await
                .map_err(|e| OverlayError::Dns(e.to_string()))?;

            // Also register custom hostname if provided
            if let Some(custom) = &peer.hostname {
                dns_server
                    .add_record(custom, peer.overlay_ip)
                    .await
                    .map_err(|e| OverlayError::Dns(e.to_string()))?;
                debug!(
                    hostname = custom,
                    ip = %peer.overlay_ip,
                    "Registered custom hostname"
                );
            }
        }

        // Start the DNS server and store the handle
        let handle = dns_server
            .start()
            .await
            .map_err(|e| OverlayError::Dns(e.to_string()))?;
        self.dns_handle = Some(handle);

        info!("DNS server started successfully");
        Ok(())
    }

    /// Initialize NAT traversal, gather candidates, and connect to known peers.
    #[cfg(feature = "nat")]
    async fn start_nat_traversal(&mut self, nat_config: crate::nat::NatConfig) {
        if !nat_config.enabled {
            return;
        }

        // Optionally start built-in relay server
        if let Some(ref relay_config) = nat_config.relay_server {
            let relay = RelayServer::new(relay_config, &self.config.private_key);
            match relay.start().await {
                Ok(()) => {
                    info!("Built-in relay server started");
                    self.relay_server = Some(relay);
                }
                Err(e) => {
                    warn!(error = %e, "Failed to start relay server");
                }
            }
        }

        let mut nat = NatTraversal::new(nat_config, self.config.port);
        match nat.gather_candidates().await {
            Ok(candidates) => {
                info!(count = candidates.len(), "Gathered NAT candidates");
                if let Some(ref transport) = self.transport {
                    for peer in &mut self.peers {
                        if !peer.candidates.is_empty() {
                            match nat
                                .connect_to_peer(transport, &peer.public_key, &peer.candidates)
                                .await
                            {
                                Ok(ct) => {
                                    peer.connection_type = ct;
                                    info!(
                                        peer = %peer.node_id,
                                        connection = %ct,
                                        "NAT traversal succeeded"
                                    );
                                }
                                Err(e) => warn!(
                                    peer = %peer.node_id,
                                    error = %e,
                                    "NAT traversal failed"
                                ),
                            }
                        }
                    }
                }
                self.nat_traversal = Some(nat);
            }
            Err(e) => warn!(error = %e, "NAT candidate gathering failed"),
        }
    }

    /// Stop the overlay network (shut down the boringtun transport)
    ///
    /// # Errors
    ///
    /// This method currently always succeeds but returns `Result` for API consistency.
    #[allow(clippy::unused_async)]
    pub async fn stop(&mut self) -> Result<()> {
        info!(interface = %self.config.interface, "Stopping overlay network");

        if let Some(mut transport) = self.transport.take() {
            transport.shutdown();
        }

        Ok(())
    }

    /// Add a new peer to the overlay network
    ///
    /// For leader nodes, this also allocates an IP address for the peer.
    ///
    /// # Errors
    ///
    /// Returns an error if no IPs are available, DNS registration fails, or state cannot be saved.
    pub async fn add_peer(&mut self, mut peer: PeerConfig) -> Result<IpAddr> {
        // If we're the leader, allocate an IP for this peer
        let overlay_ip = if let Some(ref mut allocator) = self.allocator {
            let ip = allocator.allocate().ok_or(OverlayError::NoAvailableIps)?;
            peer.overlay_ip = ip;
            ip
        } else {
            peer.overlay_ip
        };

        // Add peer to overlay transport via UAPI
        if let Ok(peer_info) = peer.to_peer_info() {
            // Prefer the stored transport; fall back to a temporary instance
            // (UAPI calls work via the Unix socket regardless of DeviceHandle)
            let transport_ref: Option<&OverlayTransport> = self.transport.as_ref();

            let result = if let Some(t) = transport_ref {
                t.add_peer(&peer_info).await
            } else {
                let overlay_config = crate::config::OverlayConfig {
                    local_endpoint: SocketAddr::new(
                        std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
                        self.config.port,
                    ),
                    private_key: self.config.private_key.clone(),
                    public_key: self.config.public_key.clone(),
                    overlay_cidr: self.config.allowed_ip(),
                    peer_discovery_interval: Duration::from_secs(30),
                    #[cfg(feature = "nat")]
                    nat: crate::nat::NatConfig::default(),
                };
                let tmp = OverlayTransport::new(overlay_config, self.config.interface.clone());
                tmp.add_peer(&peer_info).await
            };

            match result {
                Ok(()) => debug!(peer = %peer.node_id, "Added peer to overlay"),
                Err(e) => {
                    warn!(peer = %peer.node_id, error = %e, "Failed to add peer to overlay (interface may not be up)");
                }
            }
        }

        // Register peer in DNS if enabled
        if let Some(ref dns_handle) = self.dns_handle {
            // IP-based hostname
            let hostname = peer_hostname(overlay_ip);
            dns_handle
                .add_record(&hostname, overlay_ip)
                .await
                .map_err(|e| OverlayError::Dns(e.to_string()))?;
            debug!(hostname = %hostname, ip = %overlay_ip, "Registered peer in DNS");

            // Custom hostname alias if provided
            if let Some(ref custom) = peer.hostname {
                dns_handle
                    .add_record(custom, overlay_ip)
                    .await
                    .map_err(|e| OverlayError::Dns(e.to_string()))?;
                debug!(hostname = %custom, ip = %overlay_ip, "Registered custom hostname in DNS");
            }
        }

        // NAT traversal for new peer
        #[cfg(feature = "nat")]
        {
            if let (Some(ref nat), Some(ref transport)) = (&self.nat_traversal, &self.transport) {
                if !peer.candidates.is_empty() {
                    match nat
                        .connect_to_peer(transport, &peer.public_key, &peer.candidates)
                        .await
                    {
                        Ok(ct) => {
                            peer.connection_type = ct;
                            info!(
                                peer = %peer.node_id,
                                connection = %ct,
                                "NAT traversal for new peer"
                            );
                        }
                        Err(e) => warn!(
                            peer = %peer.node_id,
                            error = %e,
                            "NAT failed for new peer"
                        ),
                    }
                }
            }
        }

        // Add to peer list
        self.peers.push(peer);

        // Persist state
        self.save().await?;

        info!(peer_ip = %overlay_ip, "Added peer to overlay");
        Ok(overlay_ip)
    }

    /// Remove a peer from the overlay network
    ///
    /// # Errors
    ///
    /// Returns an error if the peer is not found, DNS removal fails, or state cannot be saved.
    pub async fn remove_peer(&mut self, public_key: &str) -> Result<()> {
        // Find the peer
        let peer_idx = self
            .peers
            .iter()
            .position(|p| p.public_key == public_key)
            .ok_or_else(|| OverlayError::PeerNotFound(public_key.to_string()))?;

        let peer = &self.peers[peer_idx];

        // Capture peer info for DNS removal before we lose the reference
        let peer_overlay_ip = peer.overlay_ip;
        let peer_custom_hostname = peer.hostname.clone();

        // Release IP if we're managing allocation
        if let Some(ref mut allocator) = self.allocator {
            allocator.release(peer_overlay_ip);
        }

        // Remove from DNS if enabled
        if let Some(ref dns_handle) = self.dns_handle {
            // Remove IP-based hostname
            let hostname = peer_hostname(peer_overlay_ip);
            dns_handle
                .remove_record(&hostname)
                .await
                .map_err(|e| OverlayError::Dns(e.to_string()))?;
            debug!(hostname = %hostname, "Removed peer from DNS");

            // Remove custom hostname if it was set
            if let Some(ref custom) = peer_custom_hostname {
                dns_handle
                    .remove_record(custom)
                    .await
                    .map_err(|e| OverlayError::Dns(e.to_string()))?;
                debug!(hostname = %custom, "Removed custom hostname from DNS");
            }
        }

        // Remove peer from overlay transport via UAPI
        let transport_ref: Option<&OverlayTransport> = self.transport.as_ref();

        let result = if let Some(t) = transport_ref {
            t.remove_peer(public_key).await
        } else {
            let overlay_config = crate::config::OverlayConfig {
                local_endpoint: SocketAddr::new(
                    std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
                    self.config.port,
                ),
                private_key: self.config.private_key.clone(),
                public_key: self.config.public_key.clone(),
                overlay_cidr: self.config.allowed_ip(),
                peer_discovery_interval: Duration::from_secs(30),
                #[cfg(feature = "nat")]
                nat: crate::nat::NatConfig::default(),
            };
            let tmp = OverlayTransport::new(overlay_config, self.config.interface.clone());
            tmp.remove_peer(public_key).await
        };

        match result {
            Ok(()) => debug!(public_key = public_key, "Removed peer from overlay"),
            Err(e) => {
                warn!(public_key = public_key, error = %e, "Failed to remove peer from overlay");
            }
        }

        // Remove from peer list
        self.peers.remove(peer_idx);

        // Persist state
        self.save().await?;

        info!(public_key = public_key, "Removed peer from overlay");
        Ok(())
    }

    /// Get this node's public key
    #[must_use]
    pub fn public_key(&self) -> &str {
        &self.config.public_key
    }

    /// Get this node's overlay IP (IPv4 or IPv6)
    #[must_use]
    pub fn node_ip(&self) -> IpAddr {
        self.config.node_ip
    }

    /// Get the overlay CIDR
    #[must_use]
    pub fn cidr(&self) -> &str {
        &self.config.cidr
    }

    /// Get the overlay interface name
    #[must_use]
    pub fn interface(&self) -> &str {
        &self.config.interface
    }

    /// Get the overlay listen port
    #[must_use]
    pub fn port(&self) -> u16 {
        self.config.port
    }

    /// Check if this node is the leader
    #[must_use]
    pub fn is_leader(&self) -> bool {
        self.config.is_leader
    }

    /// Get configured peers
    #[must_use]
    pub fn peers(&self) -> &[PeerConfig] {
        &self.peers
    }

    /// Get the bootstrap config
    #[must_use]
    pub fn config(&self) -> &BootstrapConfig {
        &self.config
    }

    /// Allocate an IP for a new peer (leader only)
    ///
    /// This is used by the control plane when processing join requests.
    ///
    /// # Errors
    ///
    /// Returns an error if this node is not a leader or no IPs are available.
    pub fn allocate_peer_ip(&mut self) -> Result<IpAddr> {
        let allocator = self
            .allocator
            .as_mut()
            .ok_or(OverlayError::Config("Not a leader node".to_string()))?;

        allocator.allocate().ok_or(OverlayError::NoAvailableIps)
    }

    /// Get IP allocation statistics (leader only)
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn allocation_stats(&self) -> Option<(u32, u32)> {
        self.allocator
            .as_ref()
            .map(|a| (a.allocated_count() as u32, a.total_hosts()))
    }

    /// Perform NAT maintenance: refresh STUN, attempt relay upgrades.
    ///
    /// Call this periodically from the runtime's main loop. Re-probes
    /// STUN servers to detect reflexive address changes and attempts
    /// to upgrade relayed connections to direct or hole-punched.
    ///
    /// # Errors
    ///
    /// Returns an error if STUN refresh fails.
    #[cfg(feature = "nat")]
    pub async fn nat_maintenance_tick(&mut self) -> Result<()> {
        let (Some(nat), Some(transport)) = (&mut self.nat_traversal, &self.transport) else {
            return Ok(());
        };

        if nat.refresh().await? {
            info!("Reflexive address changed");
        }

        for peer in &mut self.peers {
            if peer.connection_type == ConnectionType::Relayed && !peer.candidates.is_empty() {
                if let Ok(Some(upgraded)) = nat
                    .attempt_upgrade(transport, &peer.public_key, &peer.candidates)
                    .await
                {
                    peer.connection_type = upgraded;
                    info!(
                        peer = %peer.node_id,
                        connection = %upgraded,
                        "Upgraded relayed connection"
                    );
                }
            }
        }

        Ok(())
    }

    /// Get this node's NAT candidates for sharing with peers.
    ///
    /// Returns an empty vec if NAT traversal has not been initialized
    /// or no candidates were gathered.
    #[cfg(feature = "nat")]
    #[must_use]
    pub fn nat_candidates(&self) -> Vec<Candidate> {
        self.nat_traversal
            .as_ref()
            .map(|n| n.local_candidates().to_vec())
            .unwrap_or_default()
    }
}

/// Get current Unix timestamp
fn current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;

    #[test]
    fn test_bootstrap_config_allowed_ip_v4() {
        let config = BootstrapConfig {
            cidr: "10.200.0.0/16".to_string(),
            node_ip: IpAddr::V4(Ipv4Addr::new(10, 200, 0, 1)),
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port: DEFAULT_WG_PORT,
            private_key: "test_private".to_string(),
            public_key: "test_public".to_string(),
            is_leader: true,
            created_at: 0,
        };

        assert_eq!(config.allowed_ip(), "10.200.0.1/32");
    }

    #[test]
    fn test_bootstrap_config_allowed_ip_v6() {
        let config = BootstrapConfig {
            cidr: "fd00:200::/48".to_string(),
            node_ip: "fd00:200::1".parse::<IpAddr>().unwrap(),
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port: DEFAULT_WG_PORT,
            private_key: "test_private".to_string(),
            public_key: "test_public".to_string(),
            is_leader: true,
            created_at: 0,
        };

        assert_eq!(config.allowed_ip(), "fd00:200::1/128");
    }

    #[test]
    fn test_peer_config_new_v4() {
        let peer = PeerConfig::new(
            "node-1".to_string(),
            "pubkey123".to_string(),
            "192.168.1.100:51820".to_string(),
            IpAddr::V4(Ipv4Addr::new(10, 200, 0, 5)),
        );

        assert_eq!(peer.node_id, "node-1");
        assert_eq!(peer.keepalive, Some(DEFAULT_KEEPALIVE_SECS));
        assert_eq!(peer.hostname, None);
    }

    #[test]
    fn test_peer_config_new_v6() {
        let peer = PeerConfig::new(
            "node-1".to_string(),
            "pubkey123".to_string(),
            "[::1]:51820".to_string(),
            "fd00:200::5".parse::<IpAddr>().unwrap(),
        );

        assert_eq!(peer.node_id, "node-1");
        assert_eq!(peer.keepalive, Some(DEFAULT_KEEPALIVE_SECS));
        assert_eq!(peer.hostname, None);
    }

    #[test]
    fn test_peer_config_with_hostname() {
        let peer = PeerConfig::new(
            "node-1".to_string(),
            "pubkey123".to_string(),
            "192.168.1.100:51820".to_string(),
            IpAddr::V4(Ipv4Addr::new(10, 200, 0, 5)),
        )
        .with_hostname("web-server");

        assert_eq!(peer.hostname, Some("web-server".to_string()));
    }

    #[test]
    fn test_peer_config_to_peer_info_v4() {
        let peer = PeerConfig::new(
            "node-1".to_string(),
            "pubkey123".to_string(),
            "192.168.1.100:51820".to_string(),
            IpAddr::V4(Ipv4Addr::new(10, 200, 0, 5)),
        );

        let peer_info = peer.to_peer_info().unwrap();
        assert_eq!(peer_info.public_key, "pubkey123");
        assert_eq!(peer_info.allowed_ips, "10.200.0.5/32");
    }

    #[test]
    fn test_peer_config_to_peer_info_v6() {
        let peer = PeerConfig::new(
            "node-1".to_string(),
            "pubkey123".to_string(),
            "[::1]:51820".to_string(),
            "fd00:200::5".parse::<IpAddr>().unwrap(),
        );

        let peer_info = peer.to_peer_info().unwrap();
        assert_eq!(peer_info.public_key, "pubkey123");
        assert_eq!(peer_info.allowed_ips, "fd00:200::5/128");
    }

    #[test]
    fn test_bootstrap_state_serialization_v4() {
        let config = BootstrapConfig {
            cidr: "10.200.0.0/16".to_string(),
            node_ip: IpAddr::V4(Ipv4Addr::new(10, 200, 0, 1)),
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port: DEFAULT_WG_PORT,
            private_key: "private".to_string(),
            public_key: "public".to_string(),
            is_leader: true,
            created_at: 1_234_567_890,
        };

        let state = BootstrapState {
            config,
            peers: vec![],
            allocator_state: None,
        };

        let json = serde_json::to_string_pretty(&state).unwrap();
        let deserialized: BootstrapState = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.config.cidr, "10.200.0.0/16");
        assert_eq!(deserialized.config.node_ip.to_string(), "10.200.0.1");
    }

    #[test]
    fn test_bootstrap_state_serialization_v6() {
        let config = BootstrapConfig {
            cidr: "fd00:200::/48".to_string(),
            node_ip: "fd00:200::1".parse::<IpAddr>().unwrap(),
            interface: DEFAULT_INTERFACE_NAME.to_string(),
            port: DEFAULT_WG_PORT,
            private_key: "private".to_string(),
            public_key: "public".to_string(),
            is_leader: true,
            created_at: 1_234_567_890,
        };

        let state = BootstrapState {
            config,
            peers: vec![],
            allocator_state: None,
        };

        let json = serde_json::to_string_pretty(&state).unwrap();
        let deserialized: BootstrapState = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.config.cidr, "fd00:200::/48");
        assert_eq!(deserialized.config.node_ip.to_string(), "fd00:200::1");
    }

    #[test]
    fn test_default_overlay_cidr_v6_constant() {
        // Verify the IPv6 CIDR constant is valid
        let net: ipnet::IpNet = DEFAULT_OVERLAY_CIDR_V6.parse().unwrap();
        assert!(matches!(net, ipnet::IpNet::V6(_)));
        assert_eq!(net.prefix_len(), 48);
    }
}