ipfrs-network 0.2.0

Peer-to-peer networking layer with libp2p and QUIC for IPFRS
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
//! Peer Connection Limiter
//!
//! Rate-based connection limiting per peer and globally. Enforces per-peer
//! connection caps, a global connection ceiling, and a cooldown period
//! (measured in ticks) between successive connections from the same peer.

use std::collections::HashMap;

// ── Configuration ────────────────────────────────────────────────────────────

/// Configuration for [`PeerConnectionLimiter`].
#[derive(Debug, Clone)]
pub struct LimiterConfig {
    /// Maximum simultaneous connections allowed from a single peer.
    pub max_connections_per_peer: usize,
    /// Maximum total active connections across all peers.
    pub max_total_connections: usize,
    /// Minimum number of ticks that must elapse between connections from the
    /// same peer.
    pub cooldown_ticks: u64,
}

impl Default for LimiterConfig {
    fn default() -> Self {
        Self {
            max_connections_per_peer: 5,
            max_total_connections: 200,
            cooldown_ticks: 10,
        }
    }
}

// ── Per-peer tracking ────────────────────────────────────────────────────────

/// Per-peer connection information tracked by the limiter.
#[derive(Debug, Clone)]
pub struct PeerConnectionInfo {
    /// Identifier of the peer.
    pub peer_id: String,
    /// Number of currently active connections from this peer.
    pub active_connections: usize,
    /// Tick at which the most recent connection was accepted.
    pub last_connection_tick: u64,
    /// Lifetime count of accepted connections for this peer.
    pub total_connections: u64,
    /// Lifetime count of rejected connection attempts for this peer.
    pub total_rejections: u64,
}

impl PeerConnectionInfo {
    fn new(peer_id: String) -> Self {
        Self {
            peer_id,
            active_connections: 0,
            last_connection_tick: 0,
            total_connections: 0,
            total_rejections: 0,
        }
    }
}

// ── Aggregate statistics ─────────────────────────────────────────────────────

/// Aggregate statistics snapshot returned by [`PeerConnectionLimiter::stats`].
#[derive(Debug, Clone)]
pub struct LimiterStats {
    /// Total active connections across all peers.
    pub total_active: usize,
    /// Number of distinct peers being tracked.
    pub tracked_peers: usize,
    /// Lifetime count of accepted connections.
    pub total_accepted: u64,
    /// Lifetime count of rejected connection attempts.
    pub total_rejected: u64,
}

// ── Limiter ──────────────────────────────────────────────────────────────────

/// Rate-based connection limiter that enforces per-peer limits, a global cap,
/// and a cooldown period between connections from the same peer.
pub struct PeerConnectionLimiter {
    config: LimiterConfig,
    peers: HashMap<String, PeerConnectionInfo>,
    current_tick: u64,
    total_active: usize,
    total_accepted: u64,
    total_rejected: u64,
}

impl PeerConnectionLimiter {
    /// Create a new limiter with the given configuration.
    pub fn new(config: LimiterConfig) -> Self {
        Self {
            config,
            peers: HashMap::new(),
            current_tick: 0,
            total_active: 0,
            total_accepted: 0,
            total_rejected: 0,
        }
    }

    /// Attempt to accept a connection from `peer_id`.
    ///
    /// Returns `Ok(())` if the connection is accepted, or `Err` with a
    /// human-readable reason if rejected.
    pub fn try_connect(&mut self, peer_id: &str) -> Result<(), String> {
        // Global limit
        if self.total_active >= self.config.max_total_connections {
            self.record_rejection(peer_id);
            return Err(format!(
                "global connection limit reached ({}/{})",
                self.total_active, self.config.max_total_connections
            ));
        }

        let info = self
            .peers
            .entry(peer_id.to_string())
            .or_insert_with(|| PeerConnectionInfo::new(peer_id.to_string()));

        // Per-peer limit
        if info.active_connections >= self.config.max_connections_per_peer {
            info.total_rejections += 1;
            self.total_rejected += 1;
            return Err(format!(
                "per-peer connection limit reached for {} ({}/{})",
                peer_id, info.active_connections, self.config.max_connections_per_peer
            ));
        }

        // Cooldown check — only applies if the peer has had at least one
        // previous connection (total_connections > 0).
        if info.total_connections > 0 {
            let elapsed = self.current_tick.saturating_sub(info.last_connection_tick);
            if elapsed < self.config.cooldown_ticks {
                info.total_rejections += 1;
                self.total_rejected += 1;
                return Err(format!(
                    "cooldown active for {} ({} ticks remaining)",
                    peer_id,
                    self.config.cooldown_ticks - elapsed
                ));
            }
        }

        // Accept
        info.active_connections += 1;
        info.last_connection_tick = self.current_tick;
        info.total_connections += 1;
        self.total_active += 1;
        self.total_accepted += 1;

        Ok(())
    }

    /// Record a disconnection for `peer_id`.
    ///
    /// Returns `Err` if the peer has no active connections or is unknown.
    pub fn disconnect(&mut self, peer_id: &str) -> Result<(), String> {
        let info = self
            .peers
            .get_mut(peer_id)
            .ok_or_else(|| format!("unknown peer: {peer_id}"))?;

        if info.active_connections == 0 {
            return Err(format!("no active connections for peer: {peer_id}"));
        }

        info.active_connections -= 1;
        self.total_active -= 1;
        Ok(())
    }

    /// Check whether a connection from `peer_id` would be allowed **without**
    /// modifying any state.
    pub fn is_allowed(&self, peer_id: &str) -> bool {
        if self.total_active >= self.config.max_total_connections {
            return false;
        }

        if let Some(info) = self.peers.get(peer_id) {
            if info.active_connections >= self.config.max_connections_per_peer {
                return false;
            }
            if info.total_connections > 0 {
                let elapsed = self.current_tick.saturating_sub(info.last_connection_tick);
                if elapsed < self.config.cooldown_ticks {
                    return false;
                }
            }
        }

        true
    }

    /// Return the number of active connections for the given peer, or `0` if
    /// the peer is not tracked.
    pub fn active_for_peer(&self, peer_id: &str) -> usize {
        self.peers.get(peer_id).map_or(0, |i| i.active_connections)
    }

    /// Return the total number of active connections across all peers.
    pub fn total_active(&self) -> usize {
        self.total_active
    }

    /// Advance the internal clock by one tick.
    pub fn tick(&mut self) {
        self.current_tick += 1;
    }

    /// Clear all connection info for the specified peer. The peer is removed
    /// from the internal tracking map and the global active count is adjusted.
    pub fn reset_peer(&mut self, peer_id: &str) {
        if let Some(info) = self.peers.remove(peer_id) {
            self.total_active = self.total_active.saturating_sub(info.active_connections);
        }
    }

    /// Return an aggregate statistics snapshot.
    pub fn stats(&self) -> LimiterStats {
        LimiterStats {
            total_active: self.total_active,
            tracked_peers: self.peers.len(),
            total_accepted: self.total_accepted,
            total_rejected: self.total_rejected,
        }
    }

    /// Return a reference to the current configuration.
    pub fn config(&self) -> &LimiterConfig {
        &self.config
    }

    /// Return the current tick value.
    pub fn current_tick(&self) -> u64 {
        self.current_tick
    }

    /// Return a reference to a peer's info, if tracked.
    pub fn peer_info(&self, peer_id: &str) -> Option<&PeerConnectionInfo> {
        self.peers.get(peer_id)
    }

    // ── helpers ──────────────────────────────────────────────────────────

    /// Record a rejection for global-limit hits (peer may not exist yet).
    fn record_rejection(&mut self, peer_id: &str) {
        self.peers
            .entry(peer_id.to_string())
            .or_insert_with(|| PeerConnectionInfo::new(peer_id.to_string()))
            .total_rejections += 1;
        self.total_rejected += 1;
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    fn default_limiter() -> PeerConnectionLimiter {
        PeerConnectionLimiter::new(LimiterConfig::default())
    }

    // --- per-peer limit ---

    #[test]
    fn per_peer_limit_allows_up_to_max() {
        let mut lim = default_limiter();
        // Advance past cooldown for each connection
        for _ in 0..5 {
            lim.tick(); // ensure cooldown passes between each
            for _ in 0..lim.config.cooldown_ticks {
                lim.tick();
            }
            assert!(lim.try_connect("peer-a").is_ok());
        }
        assert_eq!(lim.active_for_peer("peer-a"), 5);
    }

    #[test]
    fn per_peer_limit_rejects_excess() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 2,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.try_connect("p").is_ok());
        let err = lim.try_connect("p").unwrap_err();
        assert!(err.contains("per-peer"));
    }

    #[test]
    fn per_peer_limit_after_disconnect() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 1,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.try_connect("p").is_err());
        assert!(lim.disconnect("p").is_ok());
        assert!(lim.try_connect("p").is_ok());
    }

    // --- global limit ---

    #[test]
    fn global_limit_rejects_excess() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 100,
            max_total_connections: 3,
            cooldown_ticks: 0,
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("c").is_ok());
        let err = lim.try_connect("d").unwrap_err();
        assert!(err.contains("global"));
    }

    #[test]
    fn global_limit_allows_after_disconnect() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 100,
            max_total_connections: 2,
            cooldown_ticks: 0,
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("c").is_err());
        assert!(lim.disconnect("a").is_ok());
        assert!(lim.try_connect("c").is_ok());
    }

    // --- cooldown ---

    #[test]
    fn cooldown_enforced() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 10,
            max_total_connections: 100,
            cooldown_ticks: 5,
        });
        assert!(lim.try_connect("p").is_ok());
        // Immediately try again — should be rejected due to cooldown
        let err = lim.try_connect("p").unwrap_err();
        assert!(err.contains("cooldown"));
    }

    #[test]
    fn cooldown_passes_after_enough_ticks() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 10,
            max_total_connections: 100,
            cooldown_ticks: 3,
        });
        assert!(lim.try_connect("p").is_ok());
        for _ in 0..3 {
            lim.tick();
        }
        assert!(lim.try_connect("p").is_ok());
    }

    #[test]
    fn cooldown_still_active_one_tick_short() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 10,
            max_total_connections: 100,
            cooldown_ticks: 5,
        });
        assert!(lim.try_connect("p").is_ok());
        for _ in 0..4 {
            lim.tick();
        }
        assert!(lim.try_connect("p").is_err());
        lim.tick();
        assert!(lim.try_connect("p").is_ok());
    }

    #[test]
    fn cooldown_zero_allows_immediate() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.try_connect("p").is_ok());
    }

    // --- disconnect ---

    #[test]
    fn disconnect_decrements_active() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.try_connect("p").is_ok());
        assert_eq!(lim.active_for_peer("p"), 2);
        assert!(lim.disconnect("p").is_ok());
        assert_eq!(lim.active_for_peer("p"), 1);
    }

    #[test]
    fn disconnect_unknown_peer_errors() {
        let mut lim = default_limiter();
        assert!(lim.disconnect("ghost").is_err());
    }

    #[test]
    fn disconnect_zero_active_errors() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.disconnect("p").is_ok());
        let err = lim.disconnect("p").unwrap_err();
        assert!(err.contains("no active"));
    }

    #[test]
    fn disconnect_updates_total_active() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert_eq!(lim.total_active(), 2);
        assert!(lim.disconnect("a").is_ok());
        assert_eq!(lim.total_active(), 1);
    }

    // --- is_allowed ---

    #[test]
    fn is_allowed_true_for_new_peer() {
        let lim = default_limiter();
        assert!(lim.is_allowed("new-peer"));
    }

    #[test]
    fn is_allowed_false_when_per_peer_full() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 1,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(!lim.is_allowed("p"));
    }

    #[test]
    fn is_allowed_false_when_global_full() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_total_connections: 1,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(!lim.is_allowed("b"));
    }

    #[test]
    fn is_allowed_false_during_cooldown() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 5,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(!lim.is_allowed("p"));
    }

    #[test]
    fn is_allowed_does_not_mutate_state() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        let before = lim.stats();
        let _ = lim.is_allowed("p");
        let after = lim.stats();
        assert_eq!(before.total_accepted, after.total_accepted);
        assert_eq!(before.total_rejected, after.total_rejected);
    }

    // --- stats ---

    #[test]
    fn stats_tracking_accepted() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        let s = lim.stats();
        assert_eq!(s.total_accepted, 2);
        assert_eq!(s.total_rejected, 0);
        assert_eq!(s.total_active, 2);
        assert_eq!(s.tracked_peers, 2);
    }

    #[test]
    fn stats_tracking_rejected() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 1,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        let _ = lim.try_connect("p"); // rejected
        let s = lim.stats();
        assert_eq!(s.total_accepted, 1);
        assert_eq!(s.total_rejected, 1);
    }

    #[test]
    fn stats_global_rejection_counted() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_total_connections: 1,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("a").is_ok());
        let _ = lim.try_connect("b");
        let s = lim.stats();
        assert_eq!(s.total_rejected, 1);
    }

    // --- reset_peer ---

    #[test]
    fn reset_peer_removes_tracking() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        assert!(lim.try_connect("p").is_ok());
        lim.reset_peer("p");
        assert_eq!(lim.active_for_peer("p"), 0);
        assert_eq!(lim.total_active(), 0);
        assert!(lim.peer_info("p").is_none());
    }

    #[test]
    fn reset_peer_unknown_is_noop() {
        let mut lim = default_limiter();
        lim.reset_peer("ghost"); // should not panic
        assert_eq!(lim.total_active(), 0);
    }

    // --- tick ---

    #[test]
    fn tick_advances_clock() {
        let mut lim = default_limiter();
        assert_eq!(lim.current_tick(), 0);
        lim.tick();
        assert_eq!(lim.current_tick(), 1);
        for _ in 0..9 {
            lim.tick();
        }
        assert_eq!(lim.current_tick(), 10);
    }

    // --- multiple peers ---

    #[test]
    fn multiple_peers_independent_limits() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 2,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("a").is_err());
        assert!(lim.try_connect("b").is_err());
        assert_eq!(lim.total_active(), 4);
    }

    #[test]
    fn multiple_peers_share_global_limit() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 10,
            max_total_connections: 3,
            cooldown_ticks: 0,
        });
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("c").is_ok());
        assert!(lim.try_connect("d").is_err());
    }

    // --- edge cases ---

    #[test]
    fn zero_max_per_peer_always_rejects() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 0,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_err());
    }

    #[test]
    fn zero_max_global_always_rejects() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_total_connections: 0,
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_err());
    }

    #[test]
    fn default_config_values() {
        let cfg = LimiterConfig::default();
        assert_eq!(cfg.max_connections_per_peer, 5);
        assert_eq!(cfg.max_total_connections, 200);
        assert_eq!(cfg.cooldown_ticks, 10);
    }

    #[test]
    fn peer_info_returns_none_for_unknown() {
        let lim = default_limiter();
        assert!(lim.peer_info("unknown").is_none());
    }

    #[test]
    fn peer_info_returns_correct_data() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 0,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        let info = lim.peer_info("p").expect("peer should be tracked");
        assert_eq!(info.active_connections, 1);
        assert_eq!(info.total_connections, 1);
        assert_eq!(info.total_rejections, 0);
    }

    #[test]
    fn mixed_accept_reject_stats() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 1,
            max_total_connections: 10,
            cooldown_ticks: 0,
        });
        // accept 3
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        assert!(lim.try_connect("c").is_ok());
        // reject 2
        let _ = lim.try_connect("a");
        let _ = lim.try_connect("b");
        let s = lim.stats();
        assert_eq!(s.total_accepted, 3);
        assert_eq!(s.total_rejected, 2);
        assert_eq!(s.total_active, 3);
        assert_eq!(s.tracked_peers, 3);
    }

    #[test]
    fn cooldown_independent_per_peer() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            max_connections_per_peer: 10,
            max_total_connections: 100,
            cooldown_ticks: 3,
        });
        assert!(lim.try_connect("a").is_ok());
        // Advance 3 ticks
        for _ in 0..3 {
            lim.tick();
        }
        // "a" cooldown is over, "b" is fresh
        assert!(lim.try_connect("a").is_ok());
        assert!(lim.try_connect("b").is_ok());
        // "b" is now on cooldown, "a" is too
        assert!(lim.try_connect("a").is_err());
        assert!(lim.try_connect("b").is_err());
    }

    #[test]
    fn reset_then_reconnect() {
        let mut lim = PeerConnectionLimiter::new(LimiterConfig {
            cooldown_ticks: 100,
            ..LimiterConfig::default()
        });
        assert!(lim.try_connect("p").is_ok());
        // Cooldown would block reconnection
        assert!(lim.try_connect("p").is_err());
        // Reset clears everything — including cooldown history
        lim.reset_peer("p");
        assert!(lim.try_connect("p").is_ok());
    }
}