Skip to main content

qudag_network/
peer.rs

1//! P2P network peer management implementation.
2
3use serde::{Deserialize, Serialize};
4use std::net::SocketAddr;
5use thiserror::Error;
6
7/// Errors that can occur during peer operations.
8#[derive(Debug, Error)]
9pub enum PeerError {
10    /// Connection failed
11    #[error("Connection failed")]
12    ConnectionFailed,
13
14    /// Peer not found
15    #[error("Peer not found")]
16    PeerNotFound,
17
18    /// Invalid peer address
19    #[error("Invalid peer address")]
20    InvalidAddress,
21
22    /// Handshake failed
23    #[error("Handshake failed")]
24    HandshakeFailed,
25}
26
27/// Unique peer identifier.
28#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
29pub struct PeerId(Vec<u8>);
30
31impl PeerId {
32    /// Create a new random peer ID
33    pub fn new() -> Self {
34        use std::time::{SystemTime, UNIX_EPOCH};
35        let timestamp = SystemTime::now()
36            .duration_since(UNIX_EPOCH)
37            .unwrap()
38            .as_nanos() as u64;
39
40        // For now, use timestamp as ID. In production, this should be more secure
41        Self(timestamp.to_be_bytes().to_vec())
42    }
43
44    /// Create a peer ID from bytes
45    pub fn from_bytes(bytes: Vec<u8>) -> Self {
46        Self(bytes)
47    }
48
49    /// Get the raw bytes of the peer ID
50    pub fn as_bytes(&self) -> &[u8] {
51        &self.0
52    }
53}
54
55/// Peer connection status.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum PeerStatus {
58    /// Initial connection attempt
59    Connecting,
60
61    /// Connected and handshake complete
62    Connected,
63
64    /// Connection lost
65    Disconnected,
66
67    /// Banned or blacklisted
68    Banned,
69}
70
71/// Network peer information.
72#[derive(Debug, Clone)]
73pub struct Peer {
74    /// Unique peer identifier
75    pub id: PeerId,
76
77    /// Network address
78    pub address: SocketAddr,
79
80    /// Connection status
81    pub status: PeerStatus,
82
83    /// Protocol version
84    pub version: u32,
85}
86
87/// Peer management trait defining the interface for peer operations.
88pub trait PeerManager {
89    /// Add a new peer to the network.
90    fn add_peer(&mut self, address: SocketAddr) -> Result<PeerId, PeerError>;
91
92    /// Remove a peer from the network.
93    fn remove_peer(&mut self, peer_id: &PeerId) -> Result<(), PeerError>;
94
95    /// Get information about a specific peer.
96    fn get_peer(&self, peer_id: &PeerId) -> Result<Peer, PeerError>;
97
98    /// Get list of all connected peers.
99    fn get_peers(&self) -> Vec<Peer>;
100
101    /// Ban a peer from the network.
102    fn ban_peer(&mut self, peer_id: &PeerId) -> Result<(), PeerError>;
103
104    /// Check if a peer is banned.
105    fn is_banned(&self, peer_id: &PeerId) -> bool;
106}