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
/// PeerBook with connection limits based on https://github.com/libp2p/rust-libp2p/pull/3386
use core::task::{Context, Poll};
use futures::channel::oneshot;
use futures::StreamExt;
use libp2p::core::{ConnectedPoint, Endpoint, Multiaddr};
use libp2p::identify::Info;
use libp2p::swarm::derive_prelude::ConnectionEstablished;
use libp2p::swarm::dial_opts::DialOpts;
use libp2p::swarm::ListenFailure;
use libp2p::swarm::{
    self, dummy::ConnectionHandler as DummyConnectionHandler, CloseConnection, NetworkBehaviour,
};
#[allow(deprecated)]
use libp2p::swarm::{
    ConnectionClosed, ConnectionDenied, ConnectionId, DialFailure, FromSwarm, THandler,
    THandlerInEvent, ToSwarm,
};
use libp2p::PeerId;
use std::collections::hash_map::Entry;
use std::time::Duration;
use tracing::log;
use wasm_timer::Interval;

use std::collections::{HashMap, HashSet, VecDeque};

#[derive(Debug, Clone, Copy, Default)]
pub struct ConnectionLimits {
    max_pending_incoming: Option<u32>,
    max_pending_outgoing: Option<u32>,
    max_established_incoming: Option<u32>,
    max_established_outgoing: Option<u32>,
    max_established_per_peer: Option<u32>,
    max_established_total: Option<u32>,
}

impl ConnectionLimits {
    pub fn max_pending_incoming(&self) -> Option<u32> {
        self.max_pending_incoming
    }

    pub fn max_pending_outgoing(&self) -> Option<u32> {
        self.max_pending_outgoing
    }

    pub fn max_established_incoming(&self) -> Option<u32> {
        self.max_established_incoming
    }

    pub fn max_established_outgoing(&self) -> Option<u32> {
        self.max_established_outgoing
    }

    pub fn max_established(&self) -> Option<u32> {
        self.max_established_total
    }

    pub fn max_established_per_peer(&self) -> Option<u32> {
        self.max_established_per_peer
    }
}

impl ConnectionLimits {
    pub fn set_max_pending_incoming(&mut self, limit: Option<u32>) {
        self.max_pending_incoming = limit;
    }

    pub fn set_max_pending_outgoing(&mut self, limit: Option<u32>) {
        self.max_pending_outgoing = limit;
    }

    pub fn set_max_established_incoming(&mut self, limit: Option<u32>) {
        self.max_established_incoming = limit;
    }

    pub fn set_max_established_outgoing(&mut self, limit: Option<u32>) {
        self.max_established_outgoing = limit;
    }

    pub fn set_max_established(&mut self, limit: Option<u32>) {
        self.max_established_total = limit;
    }

    pub fn set_max_established_per_peer(&mut self, limit: Option<u32>) {
        self.max_established_per_peer = limit;
    }
}

impl ConnectionLimits {
    pub fn with_max_pending_incoming(mut self, limit: Option<u32>) -> Self {
        self.max_pending_incoming = limit;
        self
    }

    pub fn with_max_pending_outgoing(mut self, limit: Option<u32>) -> Self {
        self.max_pending_outgoing = limit;
        self
    }

    pub fn with_max_established_incoming(mut self, limit: Option<u32>) -> Self {
        self.max_established_incoming = limit;
        self
    }

    pub fn with_max_established_outgoing(mut self, limit: Option<u32>) -> Self {
        self.max_established_outgoing = limit;
        self
    }

    pub fn with_max_established(mut self, limit: Option<u32>) -> Self {
        self.max_established_total = limit;
        self
    }

    pub fn with_max_established_per_peer(mut self, limit: Option<u32>) -> Self {
        self.max_established_per_peer = limit;
        self
    }
}

#[derive(Debug, thiserror::Error)]
#[error("Limit: {limit}, Current: {current}")]
pub struct ConnectionLimitError {
    limit: u32,
    current: u32,
}

#[derive(Debug)]
#[allow(clippy::type_complexity)]
pub struct Behaviour {
    limits: ConnectionLimits,

    events: VecDeque<ToSwarm<<Self as NetworkBehaviour>::ToSwarm, THandlerInEvent<Self>>>,
    cleanup_interval: Interval,

    pending_connections: HashMap<ConnectionId, oneshot::Sender<anyhow::Result<()>>>,
    pending_disconnection: HashMap<PeerId, oneshot::Sender<anyhow::Result<()>>>,

    pending_identify_timer: HashMap<PeerId, Interval>,

    pending_identify: HashMap<PeerId, oneshot::Sender<anyhow::Result<()>>>,

    peer_info: HashMap<PeerId, Info>,
    peer_rtt: HashMap<PeerId, [Duration; 3]>,
    peer_connections: HashMap<PeerId, Vec<(ConnectionId, Multiaddr)>>,

    whitelist: HashSet<PeerId>,

    // For connection limits (took from libp2p pr)
    pending_inbound_connections: HashSet<ConnectionId>,
    pending_outbound_connections: HashSet<ConnectionId>,
    established_inbound_connections: HashSet<ConnectionId>,
    established_outbound_connections: HashSet<ConnectionId>,
    established_per_peer: HashMap<PeerId, HashSet<ConnectionId>>,

    config: Config,
}

impl Default for Behaviour {
    fn default() -> Self {
        Self {
            limits: Default::default(),
            events: Default::default(),
            cleanup_interval: Interval::new_at(
                std::time::Instant::now() + Duration::from_secs(60),
                Duration::from_secs(60),
            ),
            pending_connections: Default::default(),
            pending_disconnection: Default::default(),
            pending_identify_timer: Default::default(),
            pending_identify: Default::default(),
            peer_info: Default::default(),
            peer_rtt: Default::default(),
            peer_connections: Default::default(),
            whitelist: Default::default(),
            pending_inbound_connections: Default::default(),
            pending_outbound_connections: Default::default(),
            established_inbound_connections: Default::default(),
            established_outbound_connections: Default::default(),
            established_per_peer: Default::default(),
            config: Config::default(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    pub wait_on_identify: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            wait_on_identify: true,
        }
    }
}

impl Behaviour {
    pub fn new(config: Config) -> Self {
        Self {
            config,
            ..Default::default()
        }
    }

    pub fn connect(&mut self, opt: impl Into<DialOpts>) -> oneshot::Receiver<anyhow::Result<()>> {
        let opts: DialOpts = opt.into();
        let (tx, rx) = oneshot::channel();
        let id = opts.connection_id();
        self.events.push_back(ToSwarm::Dial { opts });
        self.pending_connections.insert(id, tx);
        rx
    }

    pub fn disconnect(&mut self, peer_id: PeerId) -> oneshot::Receiver<anyhow::Result<()>> {
        let (tx, rx) = oneshot::channel();

        if !self.peer_connections.contains_key(&peer_id) {
            let _ = tx.send(Err(anyhow::anyhow!("Peer is not connected")));
            return rx;
        }

        if self.pending_disconnection.contains_key(&peer_id) {
            let _ = tx.send(Err(anyhow::anyhow!("Disconnection is pending")));
            return rx;
        }
        self.events.push_back(ToSwarm::CloseConnection {
            peer_id,
            connection: CloseConnection::All,
        });

        self.pending_disconnection.insert(peer_id, tx);

        rx
    }

    pub fn set_connection_limit(&mut self, limit: ConnectionLimits) {
        self.limits = limit;
    }

    pub fn add(&mut self, peer_id: PeerId) {
        self.whitelist.insert(peer_id);
    }

    pub fn remove(&mut self, peer_id: PeerId) {
        self.whitelist.remove(&peer_id);
    }

    pub fn inject_peer_info(&mut self, info: Info) {
        let peer_id = info.public_key.to_peer_id();
        self.peer_info.insert(peer_id, info);
        self.pending_identify_timer.remove(&peer_id);
        if self.config.wait_on_identify {
            if let Some(ch) = self.pending_identify.remove(&peer_id) {
                let _ = ch.send(Ok(()));
            }
        }
    }

    pub fn peers(&self) -> impl Iterator<Item = &PeerId> {
        self.peer_connections.keys()
    }

    pub fn connected_peers_addrs(&self) -> impl Iterator<Item = (PeerId, Vec<Multiaddr>)> + '_ {
        self.peer_connections.iter().map(|(peer_id, list)| {
            let list = list
                .iter()
                .map(|(_, addr)| addr)
                .cloned()
                .collect::<Vec<_>>();
            (*peer_id, list)
        })
    }

    pub fn set_peer_rtt(&mut self, peer_id: PeerId, rtt: Duration) {
        self.peer_rtt
            .entry(peer_id)
            .and_modify(|r| {
                r.rotate_left(1);
                r[2] = rtt;
            })
            .or_insert([Duration::from_millis(0), Duration::from_millis(0), rtt]);
    }

    pub fn get_peer_rtt(&self, peer_id: PeerId) -> Option<[Duration; 3]> {
        self.peer_rtt.get(&peer_id).copied()
    }

    pub fn get_peer_latest_rtt(&self, peer_id: PeerId) -> Option<Duration> {
        self.get_peer_rtt(peer_id).map(|rtt| rtt[2])
    }

    pub fn get_peer_info(&self, peer_id: PeerId) -> Option<&Info> {
        self.peer_info.get(&peer_id)
    }

    pub fn remove_peer_info(&mut self, peer_id: PeerId) {
        self.peer_info.remove(&peer_id);
    }

    pub fn peer_connections(&self, peer_id: PeerId) -> Option<Vec<Multiaddr>> {
        self.peer_connections
            .get(&peer_id)
            .map(|list| list.iter().map(|(_, addr)| addr).cloned().collect())
    }

    fn check_limit(&mut self, limit: Option<u32>, current: usize) -> Result<(), ConnectionDenied> {
        let limit = limit.unwrap_or(u32::MAX);
        let current = current as u32;

        if current >= limit {
            return Err(ConnectionDenied::new(ConnectionLimitError {
                limit,
                current,
            }));
        }

        Ok(())
    }
}

impl NetworkBehaviour for Behaviour {
    type ConnectionHandler = DummyConnectionHandler;
    type ToSwarm = void::Void;

    fn handle_pending_inbound_connection(
        &mut self,
        connection_id: ConnectionId,
        _: &Multiaddr,
        _: &Multiaddr,
    ) -> Result<(), ConnectionDenied> {
        self.check_limit(
            self.limits.max_pending_incoming,
            self.pending_inbound_connections.len(),
        )?;

        self.pending_inbound_connections.insert(connection_id);

        Ok(())
    }

    fn handle_pending_outbound_connection(
        &mut self,
        connection_id: ConnectionId,
        peer_id: Option<PeerId>,
        _: &[Multiaddr],
        _: Endpoint,
    ) -> Result<Vec<Multiaddr>, ConnectionDenied> {
        let mut is_whitelisted = false;

        if let Some(peer_id) = peer_id {
            is_whitelisted = self.whitelist.contains(&peer_id);
        }

        if !is_whitelisted {
            self.check_limit(
                self.limits.max_pending_outgoing,
                self.pending_outbound_connections.len(),
            )?;
        }

        self.pending_outbound_connections.insert(connection_id);

        Ok(vec![])
    }

    fn handle_established_inbound_connection(
        &mut self,
        connection_id: ConnectionId,
        peer_id: PeerId,
        _: &Multiaddr,
        _: &Multiaddr,
    ) -> Result<THandler<Self>, ConnectionDenied> {
        self.pending_inbound_connections.remove(&connection_id);

        if !self.whitelist.contains(&peer_id) {
            self.check_limit(
                self.limits.max_established_incoming,
                self.established_inbound_connections.len(),
            )?;
            self.check_limit(
                self.limits.max_established_per_peer,
                self.established_per_peer
                    .get(&peer_id)
                    .map(|connections| connections.len())
                    .unwrap_or(0),
            )?;
            self.check_limit(
                self.limits.max_established_total,
                self.established_inbound_connections.len()
                    + self.established_outbound_connections.len(),
            )?;
        }

        Ok(DummyConnectionHandler)
    }

    fn handle_established_outbound_connection(
        &mut self,
        connection_id: ConnectionId,
        peer_id: PeerId,
        _: &Multiaddr,
        _: Endpoint,
    ) -> Result<THandler<Self>, ConnectionDenied> {
        self.pending_outbound_connections.remove(&connection_id);

        if !self.whitelist.contains(&peer_id) {
            self.check_limit(
                self.limits.max_established_outgoing,
                self.established_outbound_connections.len(),
            )?;
            self.check_limit(
                self.limits.max_established_per_peer,
                self.established_per_peer
                    .get(&peer_id)
                    .map(|connections| connections.len())
                    .unwrap_or(0),
            )?;
            self.check_limit(
                self.limits.max_established_total,
                self.established_inbound_connections.len()
                    + self.established_outbound_connections.len(),
            )?;
        }

        Ok(DummyConnectionHandler)
    }

    fn on_connection_handler_event(
        &mut self,
        _: libp2p::PeerId,
        _: swarm::ConnectionId,
        _: swarm::THandlerOutEvent<Self>,
    ) {
    }

    #[allow(clippy::single_match)]
    fn on_swarm_event(&mut self, event: FromSwarm) {
        match event {
            FromSwarm::ConnectionEstablished(ConnectionEstablished {
                peer_id,
                connection_id,
                endpoint,
                ..
            }) => {
                if let Some(ch) = self.pending_connections.remove(&connection_id) {
                    match (
                        self.get_peer_info(peer_id).is_none(),
                        self.config.wait_on_identify,
                    ) {
                        (true, true) => {
                            self.pending_identify.insert(peer_id, ch);
                            self.pending_identify_timer.insert(
                                peer_id,
                                Interval::new_at(
                                    std::time::Instant::now() + Duration::from_secs(5),
                                    Duration::from_secs(5),
                                ),
                            );
                        }
                        _ => {
                            let _ = ch.send(Ok(()));
                        }
                    }
                }
                let multiaddr = match endpoint {
                    ConnectedPoint::Dialer { address, .. } => {
                        self.established_outbound_connections.insert(connection_id);
                        address.clone()
                    }
                    ConnectedPoint::Listener { send_back_addr, .. } => {
                        self.established_inbound_connections.insert(connection_id);
                        send_back_addr.clone()
                    }
                };

                self.peer_connections
                    .entry(peer_id)
                    .or_default()
                    .push((connection_id, multiaddr));

                self.established_per_peer
                    .entry(peer_id)
                    .or_default()
                    .insert(connection_id);
            }
            FromSwarm::DialFailure(DialFailure {
                error,
                connection_id,
                ..
            }) => {
                self.pending_outbound_connections.remove(&connection_id);
                if let Some(ch) = self.pending_connections.remove(&connection_id) {
                    let _ = ch.send(Err(anyhow::anyhow!("{error}")));
                }
            }
            FromSwarm::ConnectionClosed(ConnectionClosed {
                peer_id,
                connection_id,
                ..
            }) => {
                self.established_inbound_connections.remove(&connection_id);
                self.established_outbound_connections.remove(&connection_id);
                self.established_per_peer
                    .entry(peer_id)
                    .or_default()
                    .remove(&connection_id);

                self.peer_rtt.remove(&peer_id);

                if let Entry::Occupied(mut entry) = self.peer_connections.entry(peer_id) {
                    let list = entry.get_mut();
                    if let Some(index) = list.iter().position(|(id, _)| connection_id.eq(id)) {
                        list.swap_remove(index);
                    }
                    if list.is_empty() {
                        entry.remove();
                    }
                }
                if let Entry::Occupied(mut entry) = self.established_per_peer.entry(peer_id) {
                    entry.get_mut().remove(&connection_id);
                    if entry.get().is_empty() {
                        entry.remove();
                    }
                }
                //Note: This is in case we receive a connection close before it was ever established
                if let Some(ch) = self.pending_connections.remove(&connection_id) {
                    let _ = ch.send(Ok(()));
                }
                if let Some(ch) = self.pending_disconnection.remove(&peer_id) {
                    let _ = ch.send(Ok(()));
                }
            }
            FromSwarm::ListenFailure(ListenFailure { connection_id, .. }) => {
                self.pending_inbound_connections.remove(&connection_id);
            }
            _ => {}
        }
    }

    fn poll(&mut self, cx: &mut Context) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
        if let Some(event) = self.events.pop_front() {
            return Poll::Ready(event);
        }

        self.pending_identify_timer
            .retain(|peer_id, timer| match timer.poll_next_unpin(cx) {
                Poll::Ready(Some(_)) => {
                    if let Some(ch) = self.pending_identify.remove(peer_id) {
                        let _ = ch.send(Ok(()));
                    }
                    false
                }
                Poll::Ready(None) => {
                    log::error!("timer for {} was not available", peer_id);
                    false
                }
                Poll::Pending => true,
            });

        // Used to cleanup any info that may be left behind after a peer is no longer connected while giving time to all
        // Note: If a peer is whitelisted, this will retain the info as a cache, although this may change in the future
        while let Poll::Ready(Some(_)) = self.cleanup_interval.poll_next_unpin(cx) {
            self.peer_info.retain(|peer_id, _| {
                !self.established_per_peer.contains_key(peer_id)
                    && !self.whitelist.contains(peer_id)
            });
        }

        Poll::Pending
    }
}

#[cfg(test)]
mod test {
    use std::time::Duration;

    use super::Behaviour as PeerBook;
    use crate::p2p::peerbook::ConnectionLimits;
    use futures::StreamExt;
    use libp2p::{
        identify::{self, Config},
        swarm::{behaviour::toggle::Toggle, NetworkBehaviour, SwarmEvent},
        Multiaddr, PeerId, Swarm, SwarmBuilder,
    };

    #[derive(NetworkBehaviour)]
    struct Behaviour {
        peerbook: PeerBook,
        identify: Toggle<identify::Behaviour>,
    }

    //TODO: Expand test out
    #[tokio::test]
    async fn connection_limits() {
        let (_, addr1, mut swarm1) = build_swarm(false).await;
        let (peer2, _, mut swarm2) = build_swarm(false).await;
        let (peer3, _, mut swarm3) = build_swarm(false).await;
        let (peer4, _, mut swarm4) = build_swarm(false).await;

        swarm1
            .behaviour_mut()
            .peerbook
            .set_connection_limit(ConnectionLimits {
                max_established_incoming: Some(1),
                ..Default::default()
            });

        let mut oneshot = swarm2.behaviour_mut().peerbook.connect(addr1.clone());

        loop {
            tokio::select! {
                biased;
                _ = swarm1.next() => {},
                _ = swarm2.next() => {},
                conn_res = (&mut oneshot) => {
                    conn_res.unwrap().unwrap();
                    break;
                }
            }
        }
        swarm1.behaviour_mut().peerbook.add(peer3);
        let mut oneshot = swarm3.behaviour_mut().peerbook.connect(addr1.clone());

        loop {
            tokio::select! {
                biased;
                _ = swarm1.next() => {},
                _ = swarm3.next() => {},
                conn_res = (&mut oneshot) => {
                    conn_res.unwrap().unwrap();
                    break;
                }
            }
        }

        let mut oneshot = swarm4.behaviour_mut().peerbook.connect(addr1.clone());

        loop {
            tokio::select! {
                biased;
                e = swarm1.select_next_some() => {
                    if matches!(e, SwarmEvent::IncomingConnectionError { .. }) {
                        break;
                    }
                },
                _ = swarm4.next() => {},
                conn_res = (&mut oneshot) => {
                    assert!(conn_res.unwrap().is_err());
                    break;
                }
            }
        }

        let list = swarm1.connected_peers().copied().collect::<Vec<_>>();

        assert!(list.contains(&peer2));
        assert!(list.contains(&peer3));
        assert!(!list.contains(&peer4));
    }

    #[tokio::test]
    async fn connect_without_identify() {
        let (_, addr1, mut swarm1) = build_swarm(false).await;
        let (peer2, _, mut swarm2) = build_swarm(false).await;

        let mut oneshot = swarm2.behaviour_mut().peerbook.connect(addr1.clone());

        loop {
            tokio::select! {
                biased;
                _ = swarm1.next() => {},
                _ = swarm2.next() => {},
                conn_res = (&mut oneshot) => {
                    conn_res.unwrap().unwrap();
                    break;
                }
            }
        }

        let list = swarm1.connected_peers().copied().collect::<Vec<_>>();

        assert!(list.contains(&peer2));
    }

    #[tokio::test]
    async fn disconnect() {
        let (peer1, addr1, mut swarm1) = build_swarm(false).await;
        let (_, _, mut swarm2) = build_swarm(false).await;

        let mut oneshot = swarm2.behaviour_mut().peerbook.connect(addr1.clone());

        loop {
            tokio::select! {
                biased;
                _ = swarm1.next() => {},
                _ = swarm2.next() => {},
                conn_res = (&mut oneshot) => {
                    conn_res.unwrap().unwrap();
                    break;
                }
            }
        }

        let list = swarm2.connected_peers().copied().collect::<Vec<_>>();
        assert!(list.contains(&peer1));

        let oneshot = swarm2.behaviour_mut().peerbook.disconnect(peer1);

        let mut p1_disconnect = false;
        let mut p2_disconnect = false;

        loop {
            tokio::select! {
                biased;
                e1 = swarm1.select_next_some() => {
                    if matches!(e1, SwarmEvent::ConnectionClosed { .. }) {
                        p2_disconnect = true;
                    }
                },
                e2 = swarm2.select_next_some() => {
                    if matches!(e2, SwarmEvent::ConnectionClosed { .. }) {
                        p1_disconnect = true;
                    }
                },
            }
            if p1_disconnect && p2_disconnect {
                break;
            }
        }

        oneshot.await.unwrap().unwrap();

        let list = swarm2.connected_peers().copied().collect::<Vec<_>>();
        assert!(list.is_empty());
    }

    #[tokio::test]
    async fn cannot_disconnect() {
        let (peer1, _, mut swarm1) = build_swarm(false).await;
        let (_, _, mut swarm2) = build_swarm(false).await;

        let mut oneshot = swarm2.behaviour_mut().peerbook.disconnect(peer1);

        loop {
            tokio::select! {
                biased;
                e1 = swarm1.select_next_some() => {
                    if matches!(e1, SwarmEvent::ConnectionClosed { .. }) {
                        panic!("Cannot disconnect if not connected")
                    }
                },
                e2 = swarm2.select_next_some() => {
                    if matches!(e2, SwarmEvent::ConnectionClosed { .. }) {
                        panic!("Cannot disconnect if not connected")
                    }
                },
                res = &mut oneshot => {
                    let result = res.unwrap();
                    assert!(result.is_err());
                    break;
                }
            }
        }
    }

    #[tokio::test]
    async fn connect_with_identify() {
        let (_, addr1, mut swarm1) = build_swarm(true).await;
        let (peer2, _, mut swarm2) = build_swarm(true).await;

        let mut oneshot = swarm2.behaviour_mut().peerbook.connect(addr1.clone());
        let mut peer_1_identify = false;
        let mut peer_2_identify = false;
        loop {
            tokio::select! {
                biased;
                Some(e) = swarm1.next() => {
                    if let SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Received { .. })) = e {
                        peer_2_identify = true;
                    }
                },
                Some(e) = swarm2.next() => {
                    if let SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Received { .. })) = e {
                        peer_1_identify = true;
                    }
                },
                conn_res = (&mut oneshot) => {
                    conn_res.unwrap().unwrap();
                }
            }

            if peer_1_identify && peer_2_identify {
                break;
            }
        }

        let list = swarm1.connected_peers().copied().collect::<Vec<_>>();

        assert!(list.contains(&peer2));
    }

    async fn build_swarm(identify: bool) -> (PeerId, Multiaddr, Swarm<Behaviour>) {
        let mut swarm = SwarmBuilder::with_new_identity()
            .with_tokio()
            .with_tcp(
                libp2p::tcp::Config::default(),
                libp2p::noise::Config::new,
                libp2p::yamux::Config::default,
            )
            .expect("")
            .with_behaviour(|kp| Behaviour {
                peerbook: PeerBook::default(),
                identify: Toggle::from(identify.then_some(identify::Behaviour::new(Config::new(
                    "/peerbook/0.1".into(),
                    kp.public(),
                )))),
            })
            .expect("")
            .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(30)))
            .build();

        Swarm::listen_on(&mut swarm, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap();

        if let Some(SwarmEvent::NewListenAddr { address, .. }) = swarm.next().await {
            let peer_id = swarm.local_peer_id();
            return (*peer_id, address, swarm);
        }

        panic!("no new addrs")
    }
}