ant-quic 0.26.10

QUIC transport protocol with advanced NAT traversal for P2P networks
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
// Copyright 2024 Saorsa Labs Ltd.
//
// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
//
// Full details available at https://saorsalabs.com/licenses

//! Connection strategy state machine for progressive NAT traversal fallback.
//!
//! This module implements a state machine that attempts connections using
//! progressively more aggressive NAT traversal techniques:
//!
//! 1. **Direct IPv4** - Simple direct connection (fastest when both peers have public IPv4)
//! 2. **Direct IPv6** - Many ISPs have native IPv6 even behind CGNAT
//! 3. **Hole-Punch** - Coordinated NAT traversal via a common peer
//! 4. **Relay** - MASQUE CONNECT-UDP relay (guaranteed connectivity)
//!
//! # Example
//!
//! ```rust,ignore
//! let config = StrategyConfig::default();
//! let mut strategy = ConnectionStrategy::new(config);
//!
//! loop {
//!     match strategy.current_stage() {
//!         ConnectionStage::DirectIPv4 { .. } => {
//!             // Try direct IPv4 connection
//!         }
//!         ConnectionStage::DirectIPv6 { .. } => {
//!             // Try direct IPv6 connection
//!         }
//!         ConnectionStage::HolePunching { .. } => {
//!             // Coordinate hole-punching via common peer
//!         }
//!         ConnectionStage::Relay { .. } => {
//!             // Connect via MASQUE relay
//!         }
//!         ConnectionStage::Connected { via } => {
//!             println!("Connected via {:?}", via);
//!             break;
//!         }
//!         ConnectionStage::Failed { errors } => {
//!             eprintln!("All strategies failed: {:?}", errors);
//!             break;
//!         }
//!     }
//! }
//! ```

use std::net::SocketAddr;
use std::time::{Duration, Instant};

/// How a connection was established
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionMethod {
    /// Direct IPv4 connection succeeded
    DirectIPv4,
    /// Direct IPv6 connection succeeded (NAT bypassed)
    DirectIPv6,
    /// Connection established via coordinated hole-punching
    HolePunched {
        /// The coordinator peer that helped with hole-punching
        coordinator: SocketAddr,
    },
    /// Connection established via relay
    Relayed {
        /// The relay server address
        relay: SocketAddr,
    },
}

impl std::fmt::Display for ConnectionMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConnectionMethod::DirectIPv4 => write!(f, "Direct IPv4"),
            ConnectionMethod::DirectIPv6 => write!(f, "Direct IPv6"),
            ConnectionMethod::HolePunched { coordinator } => {
                write!(f, "Hole-punched via {}", coordinator)
            }
            ConnectionMethod::Relayed { relay } => write!(f, "Relayed via {}", relay),
        }
    }
}

/// Error that occurred during a connection attempt
#[derive(Debug, Clone)]
pub struct ConnectionAttemptError {
    /// The method that was attempted
    pub method: AttemptedMethod,
    /// Description of the error
    pub error: String,
    /// When the attempt was made
    pub timestamp: Instant,
}

/// Which method was attempted
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttemptedMethod {
    /// Direct IPv4 connection
    DirectIPv4,
    /// Direct IPv6 connection
    DirectIPv6,
    /// Hole-punching with specified round
    HolePunch {
        /// The round number
        round: u32,
    },
    /// Relay connection
    Relay,
}

/// Current stage of the connection strategy
#[derive(Debug, Clone)]
pub enum ConnectionStage {
    /// Attempting direct IPv4 connection
    DirectIPv4 {
        /// When this stage started
        started: Instant,
    },
    /// Attempting direct IPv6 connection
    DirectIPv6 {
        /// When this stage started
        started: Instant,
    },
    /// Attempting hole-punching via a coordinator
    HolePunching {
        /// The coordinator peer address
        coordinator: SocketAddr,
        /// Current hole-punch round (starts at 1)
        round: u32,
        /// When this stage started
        started: Instant,
    },
    /// Attempting relay connection
    Relay {
        /// The relay server address being tried
        relay_addr: SocketAddr,
        /// Index into relay_addrs being tried
        relay_index: usize,
        /// When this stage started
        started: Instant,
    },
    /// Successfully connected
    Connected {
        /// How the connection was established
        via: ConnectionMethod,
    },
    /// All methods failed
    Failed {
        /// Errors from all attempted methods
        errors: Vec<ConnectionAttemptError>,
    },
}

/// Configuration for connection strategy timeouts and behavior
#[derive(Debug, Clone)]
pub struct StrategyConfig {
    /// Timeout for direct IPv4 connection attempts
    pub ipv4_timeout: Duration,
    /// Timeout for direct IPv6 connection attempts
    pub ipv6_timeout: Duration,
    /// Timeout for each hole-punch round
    pub holepunch_timeout: Duration,
    /// Timeout for relay connection
    pub relay_timeout: Duration,
    /// Maximum number of hole-punch rounds before falling back to relay
    pub max_holepunch_rounds: u32,
    /// Whether to attempt IPv6 connections
    pub ipv6_enabled: bool,
    /// Whether to attempt relay connections as final fallback
    pub relay_enabled: bool,
    /// Optional coordinator address for hole-punching
    pub coordinator: Option<SocketAddr>,
    /// Relay server addresses for fallback (tried in order)
    pub relay_addrs: Vec<SocketAddr>,
}

impl Default for StrategyConfig {
    fn default() -> Self {
        Self {
            ipv4_timeout: Duration::from_secs(5),
            ipv6_timeout: Duration::from_secs(5),
            holepunch_timeout: Duration::from_secs(15),
            relay_timeout: Duration::from_secs(30),
            max_holepunch_rounds: 3,
            ipv6_enabled: true,
            relay_enabled: true,
            coordinator: None,
            relay_addrs: Vec::new(),
        }
    }
}

impl StrategyConfig {
    /// Create a new strategy config with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the IPv4 timeout
    pub fn with_ipv4_timeout(mut self, timeout: Duration) -> Self {
        self.ipv4_timeout = timeout;
        self
    }

    /// Set the IPv6 timeout
    pub fn with_ipv6_timeout(mut self, timeout: Duration) -> Self {
        self.ipv6_timeout = timeout;
        self
    }

    /// Set the hole-punch timeout
    pub fn with_holepunch_timeout(mut self, timeout: Duration) -> Self {
        self.holepunch_timeout = timeout;
        self
    }

    /// Set the relay timeout
    pub fn with_relay_timeout(mut self, timeout: Duration) -> Self {
        self.relay_timeout = timeout;
        self
    }

    /// Set the maximum number of hole-punch rounds
    pub fn with_max_holepunch_rounds(mut self, rounds: u32) -> Self {
        self.max_holepunch_rounds = rounds;
        self
    }

    /// Enable or disable IPv6 attempts
    pub fn with_ipv6_enabled(mut self, enabled: bool) -> Self {
        self.ipv6_enabled = enabled;
        self
    }

    /// Enable or disable relay fallback
    pub fn with_relay_enabled(mut self, enabled: bool) -> Self {
        self.relay_enabled = enabled;
        self
    }

    /// Set the coordinator address for hole-punching
    pub fn with_coordinator(mut self, addr: SocketAddr) -> Self {
        self.coordinator = Some(addr);
        self
    }

    /// Add a relay server address to the fallback list
    pub fn with_relay(mut self, addr: SocketAddr) -> Self {
        self.relay_addrs.push(addr);
        self
    }

    /// Set multiple relay server addresses for fallback
    pub fn with_relays(mut self, addrs: Vec<SocketAddr>) -> Self {
        self.relay_addrs = addrs;
        self
    }
}

/// Connection strategy state machine
///
/// Manages the progression through connection methods from fastest (direct)
/// to most reliable (relay).
#[derive(Debug)]
pub struct ConnectionStrategy {
    stage: ConnectionStage,
    config: StrategyConfig,
    errors: Vec<ConnectionAttemptError>,
}

impl ConnectionStrategy {
    /// Create a new connection strategy with the given configuration
    pub fn new(config: StrategyConfig) -> Self {
        Self {
            stage: ConnectionStage::DirectIPv4 {
                started: Instant::now(),
            },
            config,
            errors: Vec::new(),
        }
    }

    /// Get the current stage
    pub fn current_stage(&self) -> &ConnectionStage {
        &self.stage
    }

    /// Get the configuration
    pub fn config(&self) -> &StrategyConfig {
        &self.config
    }

    /// Get the IPv4 timeout
    pub fn ipv4_timeout(&self) -> Duration {
        self.config.ipv4_timeout
    }

    /// Get the IPv6 timeout
    pub fn ipv6_timeout(&self) -> Duration {
        self.config.ipv6_timeout
    }

    /// Get the hole-punch timeout
    pub fn holepunch_timeout(&self) -> Duration {
        self.config.holepunch_timeout
    }

    /// Get the relay timeout
    pub fn relay_timeout(&self) -> Duration {
        self.config.relay_timeout
    }

    /// Record an error and transition to IPv6 stage
    pub fn transition_to_ipv6(&mut self, error: impl Into<String>) {
        self.errors.push(ConnectionAttemptError {
            method: AttemptedMethod::DirectIPv4,
            error: error.into(),
            timestamp: Instant::now(),
        });

        if self.config.ipv6_enabled {
            self.stage = ConnectionStage::DirectIPv6 {
                started: Instant::now(),
            };
        } else {
            self.transition_to_holepunch_internal();
        }
    }

    /// Record an error and transition to hole-punching stage
    pub fn transition_to_holepunch(&mut self, error: impl Into<String>) {
        self.errors.push(ConnectionAttemptError {
            method: AttemptedMethod::DirectIPv6,
            error: error.into(),
            timestamp: Instant::now(),
        });
        self.transition_to_holepunch_internal();
    }

    fn transition_to_holepunch_internal(&mut self) {
        if let Some(coordinator) = self.config.coordinator {
            self.stage = ConnectionStage::HolePunching {
                coordinator,
                round: 1,
                started: Instant::now(),
            };
        } else {
            // No coordinator available, skip to relay
            self.transition_to_relay_internal();
        }
    }

    /// Record a hole-punch error and either retry or transition to relay
    pub fn record_holepunch_error(&mut self, round: u32, error: impl Into<String>) {
        self.errors.push(ConnectionAttemptError {
            method: AttemptedMethod::HolePunch { round },
            error: error.into(),
            timestamp: Instant::now(),
        });
    }

    /// Check if we should retry hole-punching
    pub fn should_retry_holepunch(&self) -> bool {
        if let ConnectionStage::HolePunching { round, .. } = &self.stage {
            *round < self.config.max_holepunch_rounds
        } else {
            false
        }
    }

    /// Change the coordinator for the next hole-punch round.
    pub fn set_coordinator(&mut self, coordinator: SocketAddr) {
        if let ConnectionStage::HolePunching { coordinator: c, .. } = &mut self.stage {
            *c = coordinator;
        }
        self.config.coordinator = Some(coordinator);
    }

    /// Increment the hole-punch round
    pub fn increment_round(&mut self) {
        if let ConnectionStage::HolePunching {
            coordinator, round, ..
        } = &self.stage
        {
            self.stage = ConnectionStage::HolePunching {
                coordinator: *coordinator,
                round: round + 1,
                started: Instant::now(),
            };
        }
    }

    /// Transition to relay stage
    pub fn transition_to_relay(&mut self, error: impl Into<String>) {
        if let ConnectionStage::HolePunching { round, .. } = &self.stage {
            self.errors.push(ConnectionAttemptError {
                method: AttemptedMethod::HolePunch { round: *round },
                error: error.into(),
                timestamp: Instant::now(),
            });
        }
        self.transition_to_relay_internal();
    }

    /// Record a relay error and try the next relay, or fail if all exhausted
    pub fn transition_to_next_relay(&mut self, error: impl Into<String>) {
        if let ConnectionStage::Relay { relay_index, .. } = &self.stage {
            self.errors.push(ConnectionAttemptError {
                method: AttemptedMethod::Relay,
                error: error.into(),
                timestamp: Instant::now(),
            });

            let next_index = relay_index + 1;
            if next_index < self.config.relay_addrs.len() {
                self.stage = ConnectionStage::Relay {
                    relay_addr: self.config.relay_addrs[next_index],
                    relay_index: next_index,
                    started: Instant::now(),
                };
            } else {
                // All relays exhausted
                self.stage = ConnectionStage::Failed {
                    errors: std::mem::take(&mut self.errors),
                };
            }
        }
    }

    fn transition_to_relay_internal(&mut self) {
        if self.config.relay_enabled && !self.config.relay_addrs.is_empty() {
            self.stage = ConnectionStage::Relay {
                relay_addr: self.config.relay_addrs[0],
                relay_index: 0,
                started: Instant::now(),
            };
        } else if !self.config.relay_enabled {
            self.transition_to_failed("Relay disabled and all other methods failed");
        } else {
            self.transition_to_failed("No relay servers configured");
        }
    }

    /// Transition to failed state
    pub fn transition_to_failed(&mut self, error: impl Into<String>) {
        // Record the final error if we came from relay stage
        if let ConnectionStage::Relay { .. } = &self.stage {
            self.errors.push(ConnectionAttemptError {
                method: AttemptedMethod::Relay,
                error: error.into(),
                timestamp: Instant::now(),
            });
        }

        self.stage = ConnectionStage::Failed {
            errors: std::mem::take(&mut self.errors),
        };
    }

    /// Mark connection as successful via the specified method
    pub fn mark_connected(&mut self, method: ConnectionMethod) {
        self.stage = ConnectionStage::Connected { via: method };
    }

    /// Check if the strategy has reached a terminal state
    pub fn is_terminal(&self) -> bool {
        matches!(
            self.stage,
            ConnectionStage::Connected { .. } | ConnectionStage::Failed { .. }
        )
    }

    /// Get all recorded errors
    pub fn errors(&self) -> &[ConnectionAttemptError] {
        &self.errors
    }
}

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

    #[test]
    fn test_default_config() {
        let config = StrategyConfig::default();
        assert_eq!(config.ipv4_timeout, Duration::from_secs(5));
        assert_eq!(config.ipv6_timeout, Duration::from_secs(5));
        assert_eq!(config.holepunch_timeout, Duration::from_secs(15));
        assert_eq!(config.relay_timeout, Duration::from_secs(30));
        assert_eq!(config.max_holepunch_rounds, 3);
        assert!(config.ipv6_enabled);
        assert!(config.relay_enabled);
    }

    #[test]
    fn test_config_builder() {
        let config = StrategyConfig::new()
            .with_ipv4_timeout(Duration::from_secs(3))
            .with_ipv6_timeout(Duration::from_secs(3))
            .with_max_holepunch_rounds(5)
            .with_ipv6_enabled(false);

        assert_eq!(config.ipv4_timeout, Duration::from_secs(3));
        assert_eq!(config.max_holepunch_rounds, 5);
        assert!(!config.ipv6_enabled);
    }

    #[test]
    fn test_initial_stage() {
        let strategy = ConnectionStrategy::new(StrategyConfig::default());
        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::DirectIPv4 { .. }
        ));
    }

    #[test]
    fn test_transition_ipv4_to_ipv6() {
        let mut strategy = ConnectionStrategy::new(StrategyConfig::default());

        strategy.transition_to_ipv6("Connection refused");

        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::DirectIPv6 { .. }
        ));
        assert_eq!(strategy.errors().len(), 1);
        assert!(matches!(
            strategy.errors()[0].method,
            AttemptedMethod::DirectIPv4
        ));
    }

    #[test]
    fn test_skip_ipv6_when_disabled() {
        let config = StrategyConfig::new()
            .with_ipv6_enabled(false)
            .with_coordinator("127.0.0.1:9000".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("Connection refused");

        // Should skip directly to hole-punching
        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::HolePunching { round: 1, .. }
        ));
    }

    #[test]
    fn test_transition_to_holepunch() {
        let config = StrategyConfig::new().with_coordinator("127.0.0.1:9000".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");

        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::HolePunching {
                round: 1,
                coordinator,
                ..
            } if coordinator.port() == 9000
        ));
    }

    #[test]
    fn test_holepunch_rounds() {
        let config = StrategyConfig::new()
            .with_coordinator("127.0.0.1:9000".parse().unwrap())
            .with_max_holepunch_rounds(3);
        let mut strategy = ConnectionStrategy::new(config);

        // Get to holepunch stage
        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");

        // Round 1
        assert!(strategy.should_retry_holepunch());
        strategy.record_holepunch_error(1, "Round 1 failed");
        strategy.increment_round();

        // Round 2
        if let ConnectionStage::HolePunching { round, .. } = strategy.current_stage() {
            assert_eq!(*round, 2);
        } else {
            panic!("Expected HolePunching stage");
        }
        assert!(strategy.should_retry_holepunch());
        strategy.record_holepunch_error(2, "Round 2 failed");
        strategy.increment_round();

        // Round 3 - last round
        if let ConnectionStage::HolePunching { round, .. } = strategy.current_stage() {
            assert_eq!(*round, 3);
        } else {
            panic!("Expected HolePunching stage");
        }
        assert!(!strategy.should_retry_holepunch());
    }

    #[test]
    fn test_transition_to_relay() {
        let config = StrategyConfig::new()
            .with_coordinator("127.0.0.1:9000".parse().unwrap())
            .with_relay("127.0.0.1:9001".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");
        strategy.transition_to_relay("Holepunch failed");

        if let ConnectionStage::Relay {
            relay_addr,
            relay_index,
            ..
        } = strategy.current_stage()
        {
            assert_eq!(relay_addr.port(), 9001);
            assert_eq!(*relay_index, 0);
        } else {
            panic!("Expected Relay stage");
        }
    }

    #[test]
    fn test_transition_to_failed() {
        let config = StrategyConfig::new()
            .with_coordinator("127.0.0.1:9000".parse().unwrap())
            .with_relay("127.0.0.1:9001".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");
        strategy.transition_to_relay("Holepunch failed");
        strategy.transition_to_failed("Relay failed");

        if let ConnectionStage::Failed { errors } = strategy.current_stage() {
            assert_eq!(errors.len(), 4);
        } else {
            panic!("Expected Failed stage");
        }
    }

    #[test]
    fn test_mark_connected() {
        let mut strategy = ConnectionStrategy::new(StrategyConfig::default());

        strategy.mark_connected(ConnectionMethod::DirectIPv4);

        if let ConnectionStage::Connected { via } = strategy.current_stage() {
            assert_eq!(*via, ConnectionMethod::DirectIPv4);
        } else {
            panic!("Expected Connected stage");
        }
        assert!(strategy.is_terminal());
    }

    #[test]
    fn test_connection_method_display() {
        assert_eq!(format!("{}", ConnectionMethod::DirectIPv4), "Direct IPv4");
        assert_eq!(format!("{}", ConnectionMethod::DirectIPv6), "Direct IPv6");
        assert_eq!(
            format!(
                "{}",
                ConnectionMethod::HolePunched {
                    coordinator: "1.2.3.4:9000".parse().unwrap()
                }
            ),
            "Hole-punched via 1.2.3.4:9000"
        );
        assert_eq!(
            format!(
                "{}",
                ConnectionMethod::Relayed {
                    relay: "5.6.7.8:9001".parse().unwrap()
                }
            ),
            "Relayed via 5.6.7.8:9001"
        );
    }

    #[test]
    fn test_no_coordinator_skips_to_relay() {
        let config = StrategyConfig::new().with_relay("127.0.0.1:9001".parse().unwrap());
        // No coordinator set
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");

        // Should skip hole-punching and go to relay
        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::Relay { .. }
        ));
    }

    #[test]
    fn test_no_relay_fails() {
        let config = StrategyConfig::new()
            .with_coordinator("127.0.0.1:9000".parse().unwrap())
            .with_relay_enabled(false);
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");
        strategy.transition_to_relay("Holepunch failed");

        // Should fail since relay is disabled
        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::Failed { .. }
        ));
    }

    #[test]
    fn test_multi_relay_fallback() {
        let config = StrategyConfig::new()
            .with_coordinator("127.0.0.1:9000".parse().unwrap())
            .with_relay("127.0.0.1:9001".parse().unwrap())
            .with_relay("127.0.0.1:9002".parse().unwrap())
            .with_relay("127.0.0.1:9003".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");
        strategy.transition_to_relay("Holepunch failed");

        // Should start at first relay
        if let ConnectionStage::Relay {
            relay_addr,
            relay_index,
            ..
        } = strategy.current_stage()
        {
            assert_eq!(relay_addr.port(), 9001);
            assert_eq!(*relay_index, 0);
        } else {
            panic!("Expected Relay stage");
        }

        // Fail first relay, try second
        strategy.transition_to_next_relay("Relay 1 failed");
        if let ConnectionStage::Relay {
            relay_addr,
            relay_index,
            ..
        } = strategy.current_stage()
        {
            assert_eq!(relay_addr.port(), 9002);
            assert_eq!(*relay_index, 1);
        } else {
            panic!("Expected Relay stage");
        }

        // Fail second relay, try third
        strategy.transition_to_next_relay("Relay 2 failed");
        if let ConnectionStage::Relay {
            relay_addr,
            relay_index,
            ..
        } = strategy.current_stage()
        {
            assert_eq!(relay_addr.port(), 9003);
            assert_eq!(*relay_index, 2);
        } else {
            panic!("Expected Relay stage");
        }

        // Fail third relay - all exhausted
        strategy.transition_to_next_relay("Relay 3 failed");
        if let ConnectionStage::Failed { errors } = strategy.current_stage() {
            // Should have errors from: IPv4, IPv6, holepunch, relay1, relay2, relay3
            assert_eq!(errors.len(), 6);
        } else {
            panic!("Expected Failed stage");
        }
    }

    #[test]
    fn test_with_relays_vec() {
        let relays: Vec<SocketAddr> = vec![
            "127.0.0.1:9001".parse().unwrap(),
            "127.0.0.1:9002".parse().unwrap(),
        ];
        let config = StrategyConfig::new().with_relays(relays);
        assert_eq!(config.relay_addrs.len(), 2);
    }

    #[test]
    fn test_single_relay_still_works() {
        // Verify backward compatibility - single with_relay() still works
        let config = StrategyConfig::new().with_relay("127.0.0.1:9001".parse().unwrap());
        let mut strategy = ConnectionStrategy::new(config);

        strategy.transition_to_ipv6("IPv4 failed");
        strategy.transition_to_holepunch("IPv6 failed");
        strategy.transition_to_relay("Holepunch failed");

        if let ConnectionStage::Relay { relay_addr, .. } = strategy.current_stage() {
            assert_eq!(relay_addr.port(), 9001);
        } else {
            panic!("Expected Relay stage");
        }

        strategy.transition_to_next_relay("Relay failed");
        assert!(matches!(
            strategy.current_stage(),
            ConnectionStage::Failed { .. }
        ));
    }
}