hopr_transport_p2p/behavior/
mod.rs

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