ckb_network/
peer.rs

1use crate::network_group::Group;
2use crate::{
3    multiaddr::Multiaddr, protocols::identify::Flags, ProtocolId, ProtocolVersion, SessionType,
4};
5use ckb_systemtime::{Duration, Instant};
6use p2p::SessionId;
7use std::collections::HashMap;
8
9/// Peer info from identify protocol message
10#[derive(Clone, Debug)]
11pub struct PeerIdentifyInfo {
12    /// Node version
13    pub client_version: String,
14    /// Node flags
15    pub flags: Flags,
16}
17
18/// Peer info
19#[derive(Clone, Debug)]
20pub struct Peer {
21    /// Peer address
22    pub connected_addr: Multiaddr,
23    /// Peer listen addresses
24    pub listened_addrs: Vec<Multiaddr>,
25    /// Peer info from identify protocol message
26    pub identify_info: Option<PeerIdentifyInfo>,
27    /// Ping/Pong message last received time
28    pub last_ping_protocol_message_received_at: Option<Instant>,
29    /// ping pong rtt
30    pub ping_rtt: Option<Duration>,
31    /// Indicates whether it is a probe connection of the fleer protocol
32    pub is_feeler: bool,
33    /// Peer connected time
34    pub connected_time: Instant,
35    /// Session id
36    pub session_id: SessionId,
37    /// Session type, Inbound or Outbound
38    pub session_type: SessionType,
39    /// Opened protocols on this session
40    pub protocols: HashMap<ProtocolId, ProtocolVersion>,
41    /// Whether a whitelist
42    pub is_whitelist: bool,
43    /// Whether the remote peer is a light client, and it subscribes the chain state.
44    pub if_lightclient_subscribed: bool,
45}
46
47impl Peer {
48    /// Init session info
49    pub fn new(
50        session_id: SessionId,
51        session_type: SessionType,
52        connected_addr: Multiaddr,
53        is_whitelist: bool,
54    ) -> Self {
55        Peer {
56            connected_addr,
57            listened_addrs: Vec::new(),
58            identify_info: None,
59            ping_rtt: None,
60            last_ping_protocol_message_received_at: None,
61            connected_time: Instant::now(),
62            is_feeler: false,
63            session_id,
64            session_type,
65            protocols: HashMap::with_capacity_and_hasher(1, Default::default()),
66            is_whitelist,
67            if_lightclient_subscribed: false,
68        }
69    }
70
71    /// Whether outbound session
72    pub fn is_outbound(&self) -> bool {
73        self.session_type.is_outbound()
74    }
75
76    /// Whether inbound session
77    pub fn is_inbound(&self) -> bool {
78        self.session_type.is_inbound()
79    }
80
81    /// Get net group
82    pub fn network_group(&self) -> Group {
83        (&self.connected_addr).into()
84    }
85
86    /// Opened protocol version
87    pub fn protocol_version(&self, protocol_id: ProtocolId) -> Option<ProtocolVersion> {
88        self.protocols.get(&protocol_id).cloned()
89    }
90}