commonware-p2p 2026.4.0

Communicate with authenticated peers over encrypted connections.
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
use crate::{
    authenticated::{
        dialing::{DialStatus, ReserveResult},
        discovery::types::Info,
    },
    Ingress,
};
use commonware_cryptography::PublicKey;
use commonware_runtime::Clock;
use commonware_utils::SystemTimeExt;
use rand::Rng;
use std::time::{Duration, SystemTime};
use tracing::trace;

/// Represents information known about a peer's address.
#[derive(Clone, Debug)]
pub enum Address<C: PublicKey> {
    /// Peer address is not yet known.
    /// Can be upgraded to `Discovered`.
    Unknown,

    /// Peer is the local node.
    Myself(Info<C>),

    /// Address is provided during initialization.
    /// Can be upgraded to `Discovered`.
    Bootstrapper(Ingress),

    /// Discovered this peer's address from other peers.
    ///
    /// The `usize` indicates the number of times dialing this record has failed.
    Discovered(Info<C>, usize),
}

/// Represents the connection status of a peer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Status {
    /// Initial state. The peer is not yet connected.
    /// Will be upgraded to [Status::Reserved] when a reservation is made.
    Inert,

    /// The peer connection is reserved by an actor that is attempting to establish a connection.
    /// Will either be upgraded to [Status::Active] or downgraded to [Status::Inert].
    Reserved,

    /// The peer is connected.
    /// Must return to [Status::Inert] after the connection is closed.
    Active,
}

/// Represents a record of a peer's address and associated information.
#[derive(Clone, Debug)]
pub struct Record<C: PublicKey> {
    /// Address state of the peer.
    address: Address<C>,

    /// Connection status of the peer.
    status: Status,

    /// Number of primary peer sets this peer is part of.
    primary_sets: usize,

    /// Number of secondary peer sets this peer is part of.
    secondary_sets: usize,

    /// If `true`, the record should persist even if the peer is not part of any peer sets.
    persistent: bool,

    /// The earliest time we are willing to reserve this peer again.
    next_reservable_at: SystemTime,

    /// The earliest time we are willing to dial this peer.
    next_dial_at: SystemTime,
}

impl<C: PublicKey> Record<C> {
    // ---------- Constructors ----------

    /// Create a new record with an unknown address.
    pub const fn unknown() -> Self {
        Self {
            address: Address::Unknown,
            status: Status::Inert,
            primary_sets: 0,
            secondary_sets: 0,
            persistent: false,
            next_reservable_at: SystemTime::UNIX_EPOCH,
            next_dial_at: SystemTime::UNIX_EPOCH,
        }
    }

    /// Create a new record with the local node's information.
    pub const fn myself(info: Info<C>) -> Self {
        Self {
            address: Address::Myself(info),
            status: Status::Inert,
            primary_sets: 0,
            secondary_sets: 0,
            persistent: true,
            next_reservable_at: SystemTime::UNIX_EPOCH,
            next_dial_at: SystemTime::UNIX_EPOCH,
        }
    }

    /// Create a new record with a bootstrapper address.
    pub fn bootstrapper(ingress: impl Into<Ingress>) -> Self {
        Self {
            address: Address::Bootstrapper(ingress.into()),
            status: Status::Inert,
            primary_sets: 0,
            secondary_sets: 0,
            persistent: true,
            next_reservable_at: SystemTime::UNIX_EPOCH,
            next_dial_at: SystemTime::UNIX_EPOCH,
        }
    }

    // ---------- Setters ----------

    /// Attempt to update the [Info] of a discovered peer.
    ///
    /// Returns true if the update was successful.
    pub fn update(&mut self, info: Info<C>) -> bool {
        match &self.address {
            Address::Myself(_) => false,
            Address::Unknown | Address::Bootstrapper(_) => {
                self.address = Address::Discovered(info, 0);
                true
            }
            Address::Discovered(prev, _) => {
                // Ensure the new info is more recent.
                let existing_ts = prev.timestamp;
                let incoming_ts = info.timestamp;
                if existing_ts >= incoming_ts {
                    let peer = info.public_key;
                    trace!(
                        ?peer,
                        ?existing_ts,
                        ?incoming_ts,
                        "peer discovery not updated"
                    );
                    return false;
                }
                self.address = Address::Discovered(info, 0);
                true
            }
        }
    }

    /// Increase the count of primary peer sets this peer is part of.
    pub const fn increment_primary(&mut self) {
        self.primary_sets = self.primary_sets.checked_add(1).unwrap();
    }

    /// Decrease the count of primary peer sets this peer is part of.
    pub const fn decrement_primary(&mut self) {
        self.primary_sets = self.primary_sets.checked_sub(1).unwrap();
    }

    /// Increase the count of secondary peer sets this peer is part of.
    pub const fn increment_secondary(&mut self) {
        self.secondary_sets = self.secondary_sets.checked_add(1).unwrap();
    }

    /// Decrease the count of secondary peer sets this peer is part of.
    pub const fn decrement_secondary(&mut self) {
        self.secondary_sets = self.secondary_sets.checked_sub(1).unwrap();
    }

    /// Whether this peer should be dialed outbound (primary or persistent peers).
    pub const fn is_outbound_target(&self) -> bool {
        self.primary_sets > 0 || self.persistent
    }

    /// Attempt to reserve the peer for connection.
    ///
    /// Checks that the peer is not ourselves, is currently inert, and that
    /// `next_reservable_at` has passed. On success, computes a jittered
    /// `next_dial_at` and sets `next_reservable_at` to `now + interval`.
    pub fn reserve(
        &mut self,
        context: &mut (impl Rng + Clock),
        interval: Duration,
    ) -> ReserveResult {
        if matches!(self.address, Address::Myself(_)) || !matches!(self.status, Status::Inert) {
            return ReserveResult::Unavailable;
        }
        let now = context.current();
        if now < self.next_reservable_at {
            return ReserveResult::RateLimited;
        }
        self.status = Status::Reserved;
        self.next_reservable_at = now.saturating_add_ext(interval);
        self.next_dial_at = self.next_reservable_at.add_jittered(context, interval / 2);
        ReserveResult::Reserved
    }

    /// Marks the peer as connected.
    ///
    /// The peer must have the status [Status::Reserved].
    pub fn connect(&mut self) {
        assert!(matches!(self.status, Status::Reserved));
        self.status = Status::Active;
    }

    /// Releases any reservation on the peer.
    pub fn release(&mut self) {
        assert!(self.status != Status::Inert, "Cannot release an Inert peer");
        self.status = Status::Inert;
    }

    /// Indicate that there was a dial failure for this peer using the given `ingress`, which is
    /// checked against the existing record to ensure that we correctly attribute the failure.
    pub fn dial_failure(&mut self, ingress: &Ingress) {
        if let Address::Discovered(info, fails) = &mut self.address {
            if &info.ingress == ingress {
                *fails += 1;
            }
        }
    }

    /// Indicate that a dial succeeded for this peer.
    ///
    /// Due to race conditions, it's possible that we connected using a socket that is now ejected
    /// from the record. However, in this case, the record would already have the `fails` set to 0,
    /// so we can avoid checking against the socket.
    pub const fn dial_success(&mut self) {
        if let Address::Discovered(_, fails) = &mut self.address {
            *fails = 0;
        }
    }

    // ---------- Getters ----------

    /// Returns `true` if this peer can be blocked.
    ///
    /// Only `Myself` cannot be blocked. Actual blocked status is tracked
    /// by the Directory via PrioritySet.
    pub const fn is_blockable(&self) -> bool {
        !matches!(self.address, Address::Myself(_))
    }

    /// Returns the number of secondary peer sets this peer is part of.
    pub const fn secondary_sets(&self) -> usize {
        self.secondary_sets
    }

    /// Returns the number of primary peer sets this peer is part of.
    pub const fn primary_sets(&self) -> usize {
        self.primary_sets
    }

    /// Check whether this record is dialable at the given time.
    ///
    /// Returns [DialStatus::Now] if the peer can be dialed immediately,
    /// [DialStatus::After] if it will become dialable at a future time,
    /// or [DialStatus::Unavailable] if it is not dialable at all.
    pub fn dialable(
        &self,
        now: SystemTime,
        allow_private_ips: bool,
        allow_dns: bool,
    ) -> DialStatus {
        if self.status != Status::Inert || !self.is_outbound_target() {
            return DialStatus::Unavailable;
        }
        let ingress = match &self.address {
            Address::Bootstrapper(ingress) => ingress,
            Address::Discovered(info, _) => &info.ingress,
            _ => return DialStatus::Unavailable,
        };
        if !ingress.is_valid(allow_private_ips, allow_dns) {
            return DialStatus::Unavailable;
        }
        if self.next_dial_at > now {
            DialStatus::After(self.next_dial_at)
        } else {
            DialStatus::Now
        }
    }

    /// Returns `true` if this peer is acceptable (can accept an incoming connection from them).
    ///
    /// A peer is acceptable if:
    /// - The peer is eligible (in a peer set, not ourselves)
    /// - We are not already connected or reserved
    pub fn acceptable(&self) -> bool {
        self.eligible() && self.status == Status::Inert
    }

    /// Return the ingress address of the peer, if known.
    pub const fn ingress(&self) -> Option<&Ingress> {
        match &self.address {
            Address::Unknown => None,
            Address::Myself(info) => Some(&info.ingress),
            Address::Bootstrapper(ingress) => Some(ingress),
            Address::Discovered(info, _) => Some(&info.ingress),
        }
    }

    /// Get the peer information if it is sharable. The information is considered sharable if it is
    /// known and we are connected to the peer.
    pub fn sharable(&self) -> Option<Info<C>> {
        match &self.address {
            Address::Unknown => None,
            Address::Myself(info) => Some(info),
            Address::Bootstrapper(_) => None,
            Address::Discovered(info, _) => (self.status == Status::Active).then_some(info),
        }
        .cloned()
    }

    /// Returns `true` if we want to ask for updated peer information for this peer.
    ///
    /// - Returns `false` for `Myself` addresses.
    /// - Returns `true` for addresses for which we don't have peer info.
    /// - Returns `true` for addresses for which we do have peer info if-and-only-if we have failed to
    ///   dial at least `min_fails` times.
    pub fn want(&self, min_fails: usize) -> bool {
        match self.address {
            Address::Myself(_) => false,
            Address::Unknown | Address::Bootstrapper(_) => true,
            Address::Discovered(_, fails) => self.status != Status::Active && fails >= min_fails,
        }
    }

    /// Returns `true` if the record can safely be deleted.
    pub const fn deletable(&self) -> bool {
        self.primary_sets == 0
            && self.secondary_sets == 0
            && !self.persistent
            && matches!(self.status, Status::Inert)
    }

    /// Returns `true` if this peer is eligible for connection.
    ///
    /// A peer is eligible if:
    /// - It is not ourselves
    /// - It is part of at least one primary peer set, at least one secondary peer set, or is
    ///   persistent
    pub const fn eligible(&self) -> bool {
        match self.address {
            Address::Myself(_) => false,
            Address::Bootstrapper(_) | Address::Unknown | Address::Discovered(_, _) => {
                self.primary_sets > 0 || self.secondary_sets > 0 || self.persistent
            }
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::authenticated::discovery::types;
    use commonware_cryptography::secp256r1::standard::{PrivateKey, PublicKey};
    use commonware_runtime::{deterministic, Runner};
    use std::net::SocketAddr;

    const NAMESPACE: &[u8] = b"test";

    // Helper function to create signed peer info for testing
    fn create_peer_info<S>(
        signer_seed: u64,
        socket: SocketAddr,
        timestamp: u64,
    ) -> Info<S::PublicKey>
    where
        S: commonware_cryptography::PrivateKey,
    {
        let signer = S::from_seed(signer_seed);
        types::Info::sign(&signer, NAMESPACE, socket, timestamp)
    }

    // Common test sockets
    fn test_socket() -> SocketAddr {
        SocketAddr::from(([127, 0, 0, 1], 8080))
    }
    fn test_socket2() -> SocketAddr {
        SocketAddr::from(([127, 0, 0, 1], 8081))
    }

    // Helper function to compare the contents of two Info instances
    fn peer_info_contents_are_equal<S: commonware_cryptography::PublicKey>(
        actual: &Info<S>,
        expected: &Info<S>,
    ) -> bool {
        actual.ingress == expected.ingress
            && actual.timestamp == expected.timestamp
            && actual.public_key == expected.public_key
            && actual.signature == expected.signature
    }

    // Helper function to compare an Option<&Info<S>> with a &Info<S>
    fn compare_optional_peer_info<S: commonware_cryptography::PublicKey>(
        actual_opt: Option<&Info<S>>,
        expected: &Info<S>,
    ) -> bool {
        actual_opt.is_some_and(|actual| peer_info_contents_are_equal(actual, expected))
    }

    #[test]
    fn test_unknown_initial_state() {
        let record = Record::<PublicKey>::unknown();
        assert!(matches!(record.address, Address::Unknown));
        assert_eq!(record.status, Status::Inert);
        assert_eq!(record.primary_sets, 0);
        assert!(!record.persistent);
        assert!(record.ingress().is_none());
        assert!(record.sharable().is_none());
        assert_eq!(record.status, Status::Inert);
        assert!(record.want(0), "Should want info for unknown peer");
        assert!(record.deletable());
        assert!(!record.eligible());
    }

    #[test]
    fn test_myself_initial_state() {
        let my_info = create_peer_info::<PrivateKey>(0, test_socket(), 100);
        let record = Record::<PublicKey>::myself(my_info.clone());
        assert!(
            matches!(&record.address, Address::Myself(info) if peer_info_contents_are_equal(info, &my_info))
        );
        assert_eq!(record.status, Status::Inert);
        assert_eq!(record.primary_sets, 0);
        assert!(record.persistent);
        assert_eq!(record.ingress(), Some(&my_info.ingress));
        assert!(compare_optional_peer_info(
            record.sharable().as_ref(),
            &my_info
        ));
        assert_eq!(record.status, Status::Inert);
        assert!(!record.want(0), "Should not want info for myself");
        assert!(!record.deletable());
        assert!(!record.eligible());
    }

    #[test]
    fn test_bootstrapper_initial_state() {
        let socket = test_socket();
        let ingress = Ingress::Socket(socket);
        let record = Record::<PublicKey>::bootstrapper(socket);
        assert!(matches!(&record.address, Address::Bootstrapper(i) if *i == ingress));
        assert_eq!(record.status, Status::Inert);
        assert_eq!(record.primary_sets, 0);
        assert!(record.persistent);
        assert_eq!(record.ingress(), Some(&ingress));
        assert!(record.sharable().is_none());
        assert_eq!(record.status, Status::Inert);
        assert!(record.want(0), "Should want info for bootstrapper");
        assert!(!record.deletable());
        assert!(record.eligible());
    }

    #[test]
    fn test_unknown_to_discovered() {
        let socket = test_socket();
        let mut record = Record::<PublicKey>::unknown();
        let peer_info = create_peer_info::<PrivateKey>(1, socket, 1000);

        assert!(record.update(peer_info.clone()));
        assert_eq!(record.ingress(), Some(&peer_info.ingress));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info)),
            "Address should be Discovered with 0 failures"
        );
        assert!(record.sharable().is_none(), "Info not sharable yet");
        assert!(!record.persistent);
    }

    #[test]
    fn test_bootstrapper_to_discovered() {
        let socket = test_socket();
        let mut record = Record::<PublicKey>::bootstrapper(socket);
        let peer_info = create_peer_info::<PrivateKey>(2, socket, 1000);

        assert!(record.persistent, "Should start as persistent");
        assert!(record.update(peer_info.clone()));
        assert_eq!(record.ingress(), Some(&peer_info.ingress));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info)),
            "Address should be Discovered with 0 failures"
        );
        assert!(record.sharable().is_none());
        assert!(record.persistent, "Should remain persistent after update");
    }

    #[test]
    fn test_discovered_update_newer_timestamp() {
        let socket = test_socket();
        let mut record = Record::<PublicKey>::unknown();
        let peer_info_old = create_peer_info::<PrivateKey>(3, socket, 1000);
        let peer_info_new = create_peer_info::<PrivateKey>(3, socket, 2000);

        assert!(record.update(peer_info_old));
        assert!(record.update(peer_info_new.clone()));

        assert_eq!(record.ingress(), Some(&peer_info_new.ingress));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info_new)),
            "Address should contain newer info"
        );
    }

    #[test]
    fn test_discovered_no_update_older_or_equal_timestamp() {
        let socket = test_socket();
        let mut record = Record::<PublicKey>::unknown();
        let peer_info_current = create_peer_info::<PrivateKey>(5, socket, 1000);
        let peer_info_older = create_peer_info::<PrivateKey>(5, socket, 500);
        let peer_info_equal = create_peer_info::<PrivateKey>(5, socket, 1000);

        assert!(record.update(peer_info_current.clone()));

        assert!(!record.update(peer_info_older));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info_current)),
            "Address should not update with older info"
        );

        assert!(!record.update(peer_info_equal));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info_current)),
            "Address should not update with equal timestamp info"
        );
    }

    #[test]
    fn test_update_myself() {
        let my_info = create_peer_info::<PrivateKey>(0, test_socket(), 100);
        let mut record_myself = Record::myself(my_info.clone());
        let other_info = create_peer_info::<PrivateKey>(1, test_socket2(), 200);
        let newer_my_info = create_peer_info::<PrivateKey>(0, test_socket(), 300);

        // Cannot update Myself record with other info or newer self info
        assert!(!record_myself.update(other_info));
        assert!(!record_myself.update(newer_my_info));
        assert!(
            matches!(&record_myself.address, Address::Myself(info) if peer_info_contents_are_equal(info, &my_info)),
            "Myself record should remain unchanged"
        );
    }

    #[test]
    fn test_update_with_different_public_key() {
        // While unlikely in normal operation (update uses Info tied to a specific record),
        // the `update` method itself doesn't check the public key matches.
        let socket = test_socket();
        let mut record = Record::<PublicKey>::unknown();

        let peer_info_pk1_ts1000 = create_peer_info::<PrivateKey>(10, socket, 1000);
        let peer_info_pk2_ts2000 = create_peer_info::<PrivateKey>(11, socket, 2000);

        assert!(record.update(peer_info_pk1_ts1000.clone()));
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info_pk1_ts1000))
        );

        // Update should succeed based on newer timestamp, even if PK differs (though context matters)
        assert!(
            record.update(peer_info_pk2_ts2000.clone()),
            "Update should succeed based on newer timestamp"
        );
        assert!(
            matches!(&record.address, Address::Discovered(info, 0) if peer_info_contents_are_equal(info, &peer_info_pk2_ts2000))
        );
    }

    #[test]
    fn test_increment_decrement_and_deletable() {
        // Test Unknown (not persistent)
        let mut record_unknown = Record::<PublicKey>::unknown();
        assert!(record_unknown.deletable());
        record_unknown.increment_primary(); // primary_sets = 1
        assert!(!record_unknown.deletable());
        record_unknown.decrement_primary(); // primary_sets = 0
        assert!(record_unknown.deletable());

        // Test Discovered (not persistent)
        let peer_info = create_peer_info::<PrivateKey>(7, test_socket(), 1000);
        let mut record_disc = Record::<PublicKey>::unknown();
        assert!(record_disc.update(peer_info));
        assert!(record_disc.deletable());
        record_disc.increment_primary(); // primary_sets = 1
        assert!(!record_disc.deletable());
        record_disc.decrement_primary(); // primary_sets = 0
        assert!(record_disc.deletable());

        // Test Bootstrapper (persistent)
        let mut record_boot = Record::<PublicKey>::bootstrapper(test_socket());
        assert!(!record_boot.deletable()); // Persistent
        record_boot.increment_primary(); // primary_sets = 1
        assert!(!record_boot.deletable());
        record_boot.decrement_primary(); // primary_sets = 0
        assert!(!record_boot.deletable()); // Still persistent

        // Test Myself (persistent)
        let my_info = create_peer_info::<PrivateKey>(0, test_socket(), 100);
        let mut record_myself = Record::myself(my_info);
        assert!(!record_myself.deletable()); // Persistent
        record_myself.increment_primary(); // primary_sets = 1
        assert!(!record_myself.deletable());
        record_myself.decrement_primary(); // primary_sets = 0
        assert!(!record_myself.deletable()); // Still persistent
    }

    #[test]
    #[should_panic]
    fn test_decrement_panics_at_zero() {
        let mut record = Record::<PublicKey>::unknown();
        assert_eq!(record.primary_sets, 0);
        record.decrement_primary(); // Panics
    }

    #[test]
    fn test_is_blockable() {
        let my_info = create_peer_info::<PrivateKey>(0, test_socket(), 100);

        // Myself is not blockable
        let record_myself = Record::myself(my_info);
        assert!(!record_myself.is_blockable());

        // Bootstrapper is blockable
        let record_boot = Record::<PublicKey>::bootstrapper(test_socket());
        assert!(record_boot.is_blockable());

        // Unknown is blockable
        let record_unknown = Record::<PublicKey>::unknown();
        assert!(record_unknown.is_blockable());

        // Discovered is blockable
        let peer_info = create_peer_info::<PrivateKey>(1, test_socket(), 1000);
        let mut record_disc = Record::<PublicKey>::unknown();
        assert!(record_disc.update(peer_info));
        assert!(record_disc.is_blockable());
    }

    #[test]
    fn test_status_transitions_reserve_connect_release() {
        deterministic::Runner::default().start(|mut context| async move {
            let mut record = Record::<PublicKey>::unknown();

            assert_eq!(record.status, Status::Inert);
            assert_eq!(
                record.reserve(&mut context, Duration::ZERO),
                ReserveResult::Reserved
            );
            assert_eq!(record.status, Status::Reserved);

            assert_eq!(
                record.reserve(&mut context, Duration::ZERO),
                ReserveResult::Unavailable,
                "Cannot re-reserve when Reserved"
            );
            assert_eq!(record.status, Status::Reserved);

            record.connect();
            assert_eq!(record.status, Status::Active);

            assert_eq!(
                record.reserve(&mut context, Duration::ZERO),
                ReserveResult::Unavailable,
                "Cannot reserve when Active"
            );
            assert_eq!(record.status, Status::Active);

            record.release();
            assert_eq!(record.status, Status::Inert);

            assert_eq!(
                record.reserve(&mut context, Duration::ZERO),
                ReserveResult::Reserved
            );
            assert_eq!(record.status, Status::Reserved);
            record.release();
            assert_eq!(record.status, Status::Inert);
        });
    }

    #[test]
    #[should_panic]
    fn test_connect_when_not_reserved_panics_from_inert() {
        let mut record = Record::<PublicKey>::unknown();
        record.connect(); // Should panic
    }

    #[test]
    #[should_panic]
    fn test_connect_when_active_panics() {
        deterministic::Runner::default().start(|mut context| async move {
            let mut record = Record::<PublicKey>::unknown();
            record.reserve(&mut context, Duration::ZERO);
            record.connect();
            record.connect(); // Should panic
        });
    }

    #[test]
    #[should_panic]
    fn test_release_when_inert_panics() {
        let mut record = Record::<PublicKey>::unknown();
        record.release(); // Should panic
    }

    #[test]
    fn test_sharable_logic() {
        deterministic::Runner::default().start(|mut context| async move {
            let socket = test_socket();
            let peer_info_data = create_peer_info::<PrivateKey>(12, socket, 100);

            // Unknown: Not sharable
            let record_unknown = Record::<PublicKey>::unknown();
            assert!(record_unknown.sharable().is_none());

            // Myself: Sharable
            let record_myself = Record::myself(peer_info_data.clone());
            assert!(compare_optional_peer_info(
                record_myself.sharable().as_ref(),
                &peer_info_data
            ));

            // Bootstrapper (no Info yet): Not sharable
            let record_boot = Record::<PublicKey>::bootstrapper(socket);
            assert!(record_boot.sharable().is_none());

            // Discovered but not Active: Not sharable
            let mut record_disc = Record::<PublicKey>::unknown();
            assert!(record_disc.update(peer_info_data.clone()));
            assert!(record_disc.sharable().is_none()); // Status Inert
            record_disc.reserve(&mut context, Duration::ZERO);
            assert!(record_disc.sharable().is_none()); // Status Reserved

            // Discovered and Active: Sharable
            record_disc.connect();
            assert!(compare_optional_peer_info(
                record_disc.sharable().as_ref(),
                &peer_info_data
            ));

            // Released after Active: Not sharable
            record_disc.release();
            assert!(record_disc.sharable().is_none());
        });
    }

    #[test]
    fn test_reserved_status_check() {
        deterministic::Runner::default().start(|mut context| async move {
            let mut record = Record::<PublicKey>::unknown();
            assert_eq!(record.status, Status::Inert);
            assert_eq!(
                record.reserve(&mut context, Duration::ZERO),
                ReserveResult::Reserved
            );
            assert_eq!(record.status, Status::Reserved);
            record.connect();
            assert_eq!(record.status, Status::Active);
            record.release();
            assert_eq!(record.status, Status::Inert);
        });
    }

    #[test]
    fn test_dial_failure_and_dial_success() {
        let socket = test_socket();
        let ingress = Ingress::Socket(socket);
        let peer_info = create_peer_info::<PrivateKey>(18, socket, 1000);
        let mut record = Record::<PublicKey>::unknown();

        // Cannot fail dial before discovered
        record.dial_failure(&ingress);
        assert!(matches!(record.address, Address::Unknown));

        // Discover
        assert!(record.update(peer_info));
        assert!(matches!(&record.address, Address::Discovered(_, 0)));

        // Fail dial 1
        record.dial_failure(&ingress);
        assert!(matches!(&record.address, Address::Discovered(_, 1)));

        // Fail dial 2
        record.dial_failure(&ingress);
        assert!(matches!(&record.address, Address::Discovered(_, 2)));

        // Fail dial for wrong ingress
        let wrong_ingress = Ingress::Socket(test_socket2());
        record.dial_failure(&wrong_ingress);
        assert!(
            matches!(&record.address, Address::Discovered(_, 2)),
            "Failure count should not change for wrong ingress"
        );

        // Success resets failures
        record.dial_success();
        assert!(
            matches!(&record.address, Address::Discovered(_, 0)),
            "Failures should reset"
        );

        // Fail dial again
        record.dial_failure(&ingress);
        assert!(matches!(&record.address, Address::Discovered(_, 1)));
    }

    #[test]
    fn test_want_logic_with_min_fails() {
        deterministic::Runner::default().start(|mut context| async move {
            let socket = test_socket();
            let ingress = Ingress::Socket(socket);
            let peer_info = create_peer_info::<PrivateKey>(13, socket, 100);
            let min_fails = 2;

            // Unknown and Bootstrapper always want info
            assert!(Record::<PublicKey>::unknown().want(min_fails));
            assert!(Record::<PublicKey>::bootstrapper(socket).want(min_fails));

            // Myself never wants info
            assert!(!Record::myself(peer_info.clone()).want(min_fails));

            let mut record_disc = Record::<PublicKey>::unknown();
            assert!(record_disc.update(peer_info));

            // Status Inert
            assert!(
                !record_disc.want(min_fails),
                "Should not want when fails=0 < min_fails"
            );
            record_disc.dial_failure(&ingress); // fails = 1
            assert!(
                !record_disc.want(min_fails),
                "Should not want when fails=1 < min_fails"
            );
            record_disc.dial_failure(&ingress); // fails = 2
            assert!(
                record_disc.want(min_fails),
                "Should want when fails=2 >= min_fails"
            );

            // Status Reserved
            record_disc.reserve(&mut context, Duration::ZERO);
            assert!(
                record_disc.want(min_fails),
                "Should still want when Reserved and fails >= min_fails"
            );

            // Status Active
            record_disc.connect();
            assert!(!record_disc.want(min_fails), "Should not want when Active");

            // Status Inert again (after release)
            record_disc.release();
            assert!(record_disc.want(min_fails));

            // Reset failures
            record_disc.dial_success(); // Reset failures
            assert!(
                !record_disc.want(min_fails),
                "Should not want when Inert and fails=0"
            );
            record_disc.dial_failure(&ingress); // fails = 1
            assert!(!record_disc.want(min_fails));
            record_disc.dial_failure(&ingress); // fails = 2
            assert!(record_disc.want(min_fails));
        });
    }

    #[test]
    fn test_deletable_logic_detailed() {
        deterministic::Runner::default().start(|mut context| async move {
            let peer_info = create_peer_info::<PrivateKey>(14, test_socket(), 100);

            // Persistent records are never deletable regardless of sets count
            assert!(!Record::myself(peer_info.clone()).deletable());
            assert!(!Record::<PublicKey>::bootstrapper(test_socket()).deletable());
            let mut record_pers = Record::<PublicKey>::bootstrapper(test_socket());
            assert!(record_pers.update(peer_info));
            assert!(!record_pers.deletable());

            // Non-persistent records depend on sets count and status
            let mut record = Record::<PublicKey>::unknown(); // Not persistent
            assert_eq!(record.primary_sets, 0);
            assert_eq!(record.status, Status::Inert);
            assert!(record.deletable()); // primary_sets = 0, !persistent, Inert

            record.increment_primary(); // primary_sets = 1
            assert!(!record.deletable()); // primary_sets != 0

            record.reserve(&mut context, Duration::ZERO); // status = Reserved
            assert!(!record.deletable()); // status != Inert

            record.connect(); // status = Active
            assert!(!record.deletable()); // status != Inert

            record.release(); // status = Inert
            assert!(!record.deletable()); // primary_sets != 0

            record.decrement_primary(); // primary_sets = 0
            assert!(record.deletable()); // primary_sets = 0, !persistent, Inert
        });
    }

    #[test]
    fn test_eligible_logic() {
        let peer_info = create_peer_info::<PrivateKey>(16, test_socket(), 100);

        // Myself is never eligible
        assert!(!Record::myself(peer_info.clone()).eligible());

        // Persistent records (Bootstrapper) are allowed even with sets=0
        assert!(Record::<PublicKey>::bootstrapper(test_socket()).eligible());
        let mut record_pers = Record::<PublicKey>::bootstrapper(test_socket());
        assert!(record_pers.update(peer_info.clone()));
        assert!(record_pers.eligible());

        // Non-persistent records (Unknown, Discovered) require sets > 0
        let mut record_unknown = Record::<PublicKey>::unknown();
        assert!(!record_unknown.eligible()); // primary_sets = 0, !persistent
        record_unknown.increment_primary(); // primary_sets = 1
        assert!(record_unknown.eligible()); // primary_sets > 0
        record_unknown.decrement_primary(); // primary_sets = 0
        assert!(!record_unknown.eligible());

        let mut record_disc = Record::<PublicKey>::unknown();
        assert!(record_disc.update(peer_info));
        assert!(!record_disc.eligible()); // primary_sets = 0, !persistent
        record_disc.increment_primary(); // primary_sets = 1
        assert!(record_disc.eligible()); // primary_sets > 0
    }
}