Skip to main content

hopr_transport_p2p/behavior/
mod.rs

1use std::fmt::Debug;
2
3use futures::Stream;
4use libp2p::{identity::PublicKey, swarm::NetworkBehaviour};
5
6use crate::PeerDiscovery;
7
8/// Definition of the HOPR discovery mechanism for the network.
9pub(crate) mod discovery;
10
11/// Network Behavior definition for aggregated HOPR network functionality.
12///
13/// Individual network behaviors from the libp2p perspectives are aggregated
14/// under this type in order to create an aggregated network behavior capable
15/// of generating events for all component behaviors.
16#[derive(NetworkBehaviour)]
17#[behaviour(to_swarm = "HoprNetworkBehaviorEvent")]
18pub struct HoprNetworkBehavior {
19    discovery: discovery::Behaviour,
20    pub(crate) streams: libp2p_stream::Behaviour,
21    identify: libp2p::identify::Behaviour,
22    autonat: libp2p::autonat::Behaviour,
23}
24
25impl Debug for HoprNetworkBehavior {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.debug_struct("HoprNetworkBehavior").finish()
28    }
29}
30
31impl HoprNetworkBehavior {
32    pub fn new<T>(me: PublicKey, external_discovery_events: T) -> Self
33    where
34        T: Stream<Item = PeerDiscovery> + Send + 'static,
35    {
36        let my_peer_id = libp2p::PeerId::from_public_key(&me);
37
38        Self {
39            streams: libp2p_stream::Behaviour::new(),
40            discovery: discovery::Behaviour::new(my_peer_id, external_discovery_events),
41            identify: libp2p::identify::Behaviour::new(libp2p::identify::Config::new(
42                "/hopr/identify/1.0.0".to_string(),
43                me,
44            )),
45            autonat: libp2p::autonat::Behaviour::new(my_peer_id, Default::default()),
46        }
47    }
48}
49
50/// Aggregated network behavior event inheriting the component behaviors' events.
51///
52/// Necessary to allow the libp2p handler to properly distribute the events for
53/// processing in the business logic loop.
54#[derive(Debug)]
55pub enum HoprNetworkBehaviorEvent {
56    Discovery(()),
57    Identify(Box<libp2p::identify::Event>),
58    Autonat(libp2p::autonat::Event),
59}
60
61impl From<()> for HoprNetworkBehaviorEvent {
62    fn from(event: ()) -> Self {
63        Self::Discovery(event)
64    }
65}
66
67impl From<libp2p::identify::Event> for HoprNetworkBehaviorEvent {
68    fn from(event: libp2p::identify::Event) -> Self {
69        Self::Identify(Box::new(event))
70    }
71}
72impl From<libp2p::autonat::Event> for HoprNetworkBehaviorEvent {
73    fn from(event: libp2p::autonat::Event) -> Self {
74        Self::Autonat(event)
75    }
76}