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
// Copyright 2023 Protocol Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! A libp2p module for managing allow and blocks lists to peers.
//!
//! # Allow list example
//!
//! ```rust
//! # use libp2p_swarm::Swarm;
//! # use libp2p_swarm_derive::NetworkBehaviour;
//! # use libp2p_allow_block_list as allow_block_list;
//! # use libp2p_allow_block_list::AllowedPeers;
//! #
//! #[derive(NetworkBehaviour)]
//! # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
//! struct MyBehaviour {
//!    allowed_peers: allow_block_list::Behaviour<AllowedPeers>,
//! }
//!
//! # fn main() {
//! let behaviour = MyBehaviour {
//!     allowed_peers: allow_block_list::Behaviour::default()
//! };
//! # }
//! ```
//! # Block list example
//!
//! ```rust
//! # use libp2p_swarm::Swarm;
//! # use libp2p_swarm_derive::NetworkBehaviour;
//! # use libp2p_allow_block_list as allow_block_list;
//! # use libp2p_allow_block_list::BlockedPeers;
//! #
//! #[derive(NetworkBehaviour)]
//! # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
//! struct MyBehaviour {
//!    blocked_peers: allow_block_list::Behaviour<BlockedPeers>,
//! }
//!
//! # fn main() {
//! let behaviour = MyBehaviour {
//!     blocked_peers: allow_block_list::Behaviour::default()
//! };
//! # }
//! ```

use libp2p_core::transport::PortUse;
use libp2p_core::{Endpoint, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_swarm::{
    dummy, CloseConnection, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler,
    THandlerInEvent, THandlerOutEvent, ToSwarm,
};
use std::collections::{HashSet, VecDeque};
use std::fmt;
use std::task::{Context, Poll, Waker};
use void::Void;

/// A [`NetworkBehaviour`] that can act as an allow or block list.
#[derive(Default, Debug)]
pub struct Behaviour<S> {
    state: S,
    close_connections: VecDeque<PeerId>,
    waker: Option<Waker>,
}

/// The list of explicitly allowed peers.
#[derive(Default)]
pub struct AllowedPeers {
    peers: HashSet<PeerId>,
}

/// The list of explicitly blocked peers.
#[derive(Default)]
pub struct BlockedPeers {
    peers: HashSet<PeerId>,
}

impl Behaviour<AllowedPeers> {
    /// Allow connections to the given peer.
    pub fn allow_peer(&mut self, peer: PeerId) {
        self.state.peers.insert(peer);
        if let Some(waker) = self.waker.take() {
            waker.wake()
        }
    }

    /// Disallow connections to the given peer.
    ///
    /// All active connections to this peer will be closed immediately.
    pub fn disallow_peer(&mut self, peer: PeerId) {
        self.state.peers.remove(&peer);
        self.close_connections.push_back(peer);
        if let Some(waker) = self.waker.take() {
            waker.wake()
        }
    }
}

impl Behaviour<BlockedPeers> {
    /// Block connections to a given peer.
    ///
    /// All active connections to this peer will be closed immediately.
    pub fn block_peer(&mut self, peer: PeerId) {
        self.state.peers.insert(peer);
        self.close_connections.push_back(peer);
        if let Some(waker) = self.waker.take() {
            waker.wake()
        }
    }

    /// Unblock connections to a given peer.
    pub fn unblock_peer(&mut self, peer: PeerId) {
        self.state.peers.remove(&peer);
        if let Some(waker) = self.waker.take() {
            waker.wake()
        }
    }
}

/// A connection to this peer is not explicitly allowed and was thus [`denied`](ConnectionDenied).
#[derive(Debug)]
pub struct NotAllowed {
    peer: PeerId,
}

impl fmt::Display for NotAllowed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "peer {} is not in the allow list", self.peer)
    }
}

impl std::error::Error for NotAllowed {}

/// A connection to this peer was explicitly blocked and was thus [`denied`](ConnectionDenied).
#[derive(Debug)]
pub struct Blocked {
    peer: PeerId,
}

impl fmt::Display for Blocked {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "peer {} is in the block list", self.peer)
    }
}

impl std::error::Error for Blocked {}

trait Enforce: 'static {
    fn enforce(&self, peer: &PeerId) -> Result<(), ConnectionDenied>;
}

impl Enforce for AllowedPeers {
    fn enforce(&self, peer: &PeerId) -> Result<(), ConnectionDenied> {
        if !self.peers.contains(peer) {
            return Err(ConnectionDenied::new(NotAllowed { peer: *peer }));
        }

        Ok(())
    }
}

impl Enforce for BlockedPeers {
    fn enforce(&self, peer: &PeerId) -> Result<(), ConnectionDenied> {
        if self.peers.contains(peer) {
            return Err(ConnectionDenied::new(Blocked { peer: *peer }));
        }

        Ok(())
    }
}

impl<S> NetworkBehaviour for Behaviour<S>
where
    S: Enforce,
{
    type ConnectionHandler = dummy::ConnectionHandler;
    type ToSwarm = Void;

    fn handle_established_inbound_connection(
        &mut self,
        _: ConnectionId,
        peer: PeerId,
        _: &Multiaddr,
        _: &Multiaddr,
    ) -> Result<THandler<Self>, ConnectionDenied> {
        self.state.enforce(&peer)?;

        Ok(dummy::ConnectionHandler)
    }

    fn handle_pending_outbound_connection(
        &mut self,
        _: ConnectionId,
        peer: Option<PeerId>,
        _: &[Multiaddr],
        _: Endpoint,
    ) -> Result<Vec<Multiaddr>, ConnectionDenied> {
        if let Some(peer) = peer {
            self.state.enforce(&peer)?;
        }

        Ok(vec![])
    }

    fn handle_established_outbound_connection(
        &mut self,
        _: ConnectionId,
        peer: PeerId,
        _: &Multiaddr,
        _: Endpoint,
        _: PortUse,
    ) -> Result<THandler<Self>, ConnectionDenied> {
        self.state.enforce(&peer)?;

        Ok(dummy::ConnectionHandler)
    }

    fn on_swarm_event(&mut self, _event: FromSwarm) {}

    fn on_connection_handler_event(
        &mut self,
        _id: PeerId,
        _: ConnectionId,
        event: THandlerOutEvent<Self>,
    ) {
        void::unreachable(event)
    }

    fn poll(
        &mut self,
        cx: &mut Context<'_>,
    ) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
        if let Some(peer) = self.close_connections.pop_front() {
            return Poll::Ready(ToSwarm::CloseConnection {
                peer_id: peer,
                connection: CloseConnection::All,
            });
        }

        self.waker = Some(cx.waker().clone());
        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use libp2p_swarm::{dial_opts::DialOpts, DialError, ListenError, Swarm, SwarmEvent};
    use libp2p_swarm_test::SwarmExt;

    #[async_std::test]
    async fn cannot_dial_blocked_peer() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        dialer.behaviour_mut().block_peer(*listener.local_peer_id());

        let DialError::Denied { cause } = dial(&mut dialer, &listener).unwrap_err() else {
            panic!("unexpected dial error")
        };
        assert!(cause.downcast::<Blocked>().is_ok());
    }

    #[async_std::test]
    async fn can_dial_unblocked_peer() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        dialer.behaviour_mut().block_peer(*listener.local_peer_id());
        dialer
            .behaviour_mut()
            .unblock_peer(*listener.local_peer_id());

        dial(&mut dialer, &listener).unwrap();
    }

    #[async_std::test]
    async fn blocked_peer_cannot_dial_us() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        listener.behaviour_mut().block_peer(*dialer.local_peer_id());
        dial(&mut dialer, &listener).unwrap();
        async_std::task::spawn(dialer.loop_on_next());

        let cause = listener
            .wait(|e| match e {
                SwarmEvent::IncomingConnectionError {
                    error: ListenError::Denied { cause },
                    ..
                } => Some(cause),
                _ => None,
            })
            .await;
        assert!(cause.downcast::<Blocked>().is_ok());
    }

    #[async_std::test]
    async fn connections_get_closed_upon_blocked() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<BlockedPeers>::default());
        listener.listen().with_memory_addr_external().await;
        dialer.connect(&mut listener).await;

        dialer.behaviour_mut().block_peer(*listener.local_peer_id());

        let (
            [SwarmEvent::ConnectionClosed {
                peer_id: closed_dialer_peer,
                ..
            }],
            [SwarmEvent::ConnectionClosed {
                peer_id: closed_listener_peer,
                ..
            }],
        ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await
        else {
            panic!("unexpected events")
        };
        assert_eq!(closed_dialer_peer, *listener.local_peer_id());
        assert_eq!(closed_listener_peer, *dialer.local_peer_id());
    }

    #[async_std::test]
    async fn cannot_dial_peer_unless_allowed() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        let DialError::Denied { cause } = dial(&mut dialer, &listener).unwrap_err() else {
            panic!("unexpected dial error")
        };
        assert!(cause.downcast::<NotAllowed>().is_ok());

        dialer.behaviour_mut().allow_peer(*listener.local_peer_id());
        assert!(dial(&mut dialer, &listener).is_ok());
    }

    #[async_std::test]
    async fn cannot_dial_disallowed_peer() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        dialer.behaviour_mut().allow_peer(*listener.local_peer_id());
        dialer
            .behaviour_mut()
            .disallow_peer(*listener.local_peer_id());

        let DialError::Denied { cause } = dial(&mut dialer, &listener).unwrap_err() else {
            panic!("unexpected dial error")
        };
        assert!(cause.downcast::<NotAllowed>().is_ok());
    }

    #[async_std::test]
    async fn not_allowed_peer_cannot_dial_us() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        listener.listen().with_memory_addr_external().await;

        dialer
            .dial(
                DialOpts::unknown_peer_id()
                    .address(listener.external_addresses().next().cloned().unwrap())
                    .build(),
            )
            .unwrap();

        let (
            [SwarmEvent::OutgoingConnectionError {
                error:
                    DialError::Denied {
                        cause: outgoing_cause,
                    },
                ..
            }],
            [_, SwarmEvent::IncomingConnectionError {
                error:
                    ListenError::Denied {
                        cause: incoming_cause,
                    },
                ..
            }],
        ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await
        else {
            panic!("unexpected events")
        };
        assert!(outgoing_cause.downcast::<NotAllowed>().is_ok());
        assert!(incoming_cause.downcast::<NotAllowed>().is_ok());
    }

    #[async_std::test]
    async fn connections_get_closed_upon_disallow() {
        let mut dialer = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        let mut listener = Swarm::new_ephemeral(|_| Behaviour::<AllowedPeers>::default());
        listener.listen().with_memory_addr_external().await;
        dialer.behaviour_mut().allow_peer(*listener.local_peer_id());
        listener.behaviour_mut().allow_peer(*dialer.local_peer_id());

        dialer.connect(&mut listener).await;

        dialer
            .behaviour_mut()
            .disallow_peer(*listener.local_peer_id());
        let (
            [SwarmEvent::ConnectionClosed {
                peer_id: closed_dialer_peer,
                ..
            }],
            [SwarmEvent::ConnectionClosed {
                peer_id: closed_listener_peer,
                ..
            }],
        ) = libp2p_swarm_test::drive(&mut dialer, &mut listener).await
        else {
            panic!("unexpected events")
        };
        assert_eq!(closed_dialer_peer, *listener.local_peer_id());
        assert_eq!(closed_listener_peer, *dialer.local_peer_id());
    }

    fn dial<S>(
        dialer: &mut Swarm<Behaviour<S>>,
        listener: &Swarm<Behaviour<S>>,
    ) -> Result<(), DialError>
    where
        S: Enforce,
    {
        dialer.dial(
            DialOpts::peer_id(*listener.local_peer_id())
                .addresses(listener.external_addresses().cloned().collect())
                .build(),
        )
    }
}