qudag_network/
types.rs

1use serde::{Deserialize, Serialize};
2use std::net::{IpAddr, Ipv4Addr};
3use std::time::Duration;
4use thiserror::Error;
5
6/// Network address combining IP and port
7///
8/// # Examples
9///
10/// ```rust
11/// use qudag_network::types::NetworkAddress;
12/// use std::net::{IpAddr, Ipv4Addr};
13///
14/// // Create address from IP parts
15/// let addr1 = NetworkAddress::new([127, 0, 0, 1], 8080);
16///
17/// // Create address from IP and port
18/// let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
19/// let addr2 = NetworkAddress::from_ip_port(ip, 3000);
20///
21/// // Get socket address string
22/// let socket_str = addr1.to_socket_addr();
23/// assert_eq!(socket_str, "127.0.0.1:8080");
24/// ```
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct NetworkAddress {
27    /// IP address
28    pub ip: IpAddr,
29    /// Port number
30    pub port: u16,
31}
32
33impl NetworkAddress {
34    /// Create a new network address from IPv4 address parts and port
35    pub fn new(ip_parts: [u8; 4], port: u16) -> Self {
36        Self {
37            ip: IpAddr::V4(Ipv4Addr::new(
38                ip_parts[0],
39                ip_parts[1],
40                ip_parts[2],
41                ip_parts[3],
42            )),
43            port,
44        }
45    }
46
47    /// Create a new network address from IP and port
48    pub fn from_ip_port(ip: IpAddr, port: u16) -> Self {
49        Self { ip, port }
50    }
51
52    /// Get the socket address as a string
53    pub fn to_socket_addr(&self) -> String {
54        format!("{}:{}", self.ip, self.port)
55    }
56}
57
58/// Network errors
59#[derive(Debug, Error)]
60pub enum NetworkError {
61    #[error("Connection failed: {0}")]
62    ConnectionError(String),
63
64    #[error("Message handling failed: {0}")]
65    MessageError(String),
66
67    #[error("Routing failed: {0}")]
68    RoutingError(String),
69
70    #[error("Encryption failed: {0}")]
71    EncryptionError(String),
72
73    #[error("Bootstrap failed")]
74    BootstrapFailed,
75
76    #[error("Content too large")]
77    ContentTooLarge,
78
79    #[error("Internal error: {0}")]
80    Internal(String),
81}
82
83/// Message priority levels
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
85pub enum MessagePriority {
86    /// High priority messages
87    High,
88    /// Normal priority messages
89    Normal,
90    /// Low priority messages
91    Low,
92}
93
94/// Message routing strategy
95#[derive(Debug, Clone)]
96pub enum RoutingStrategy {
97    /// Direct to peer
98    Direct(Vec<u8>),
99    /// Flood to all peers
100    Flood,
101    /// Random subset of peers
102    RandomSubset(usize),
103    /// Anonymous routing
104    Anonymous {
105        /// Number of hops
106        hops: usize,
107    },
108}
109
110/// Routing layer for onion routing
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct RoutingLayer {
113    /// Next hop
114    pub next_hop: Vec<u8>,
115    /// Encrypted payload
116    pub payload: Vec<u8>,
117    /// Layer metadata
118    pub metadata: LayerMetadata,
119}
120
121/// Routing layer metadata
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct LayerMetadata {
124    /// Time-to-live
125    pub ttl: Duration,
126    /// Flags
127    pub flags: u32,
128    /// Layer ID
129    pub id: String,
130}
131
132/// Network metrics
133#[derive(Debug, Clone, Default)]
134pub struct NetworkMetrics {
135    /// Messages per second
136    pub messages_per_second: f64,
137    /// Current connections
138    pub connections: usize,
139    /// Active connections
140    pub active_connections: usize,
141    /// Average message latency
142    pub avg_latency: Duration,
143    /// Memory usage in bytes
144    pub memory_usage: usize,
145}
146
147/// Message type
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub enum MessageType {
150    /// Handshake message
151    Handshake {
152        /// Protocol version
153        version: u32,
154        /// Node ID
155        node_id: Vec<u8>,
156    },
157    /// Data message
158    Data {
159        /// Message ID
160        id: String,
161        /// Payload
162        payload: Vec<u8>,
163        /// Priority
164        priority: MessagePriority,
165    },
166    /// Control message
167    Control {
168        /// Command
169        command: String,
170        /// Parameters
171        params: Vec<String>,
172    },
173}
174
175/// Network message structure
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct NetworkMessage {
178    /// Message identifier
179    pub id: String,
180    /// Source node identifier
181    pub source: Vec<u8>,
182    /// Destination node identifier
183    pub destination: Vec<u8>,
184    /// Message payload
185    pub payload: Vec<u8>,
186    /// Message priority
187    pub priority: MessagePriority,
188    /// Time to live
189    pub ttl: Duration,
190}
191
192/// Peer identification
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
194pub struct PeerId([u8; 32]);
195
196impl PeerId {
197    /// Generate a random peer ID
198    pub fn random() -> Self {
199        use rand::RngCore;
200        let mut id = [0u8; 32];
201        rand::thread_rng().fill_bytes(&mut id);
202        Self(id)
203    }
204
205    /// Create a peer ID from bytes
206    pub fn from_bytes(bytes: [u8; 32]) -> Self {
207        Self(bytes)
208    }
209
210    /// Get the peer ID as bytes
211    pub fn to_bytes(&self) -> [u8; 32] {
212        self.0
213    }
214
215    /// Get the peer ID as a slice
216    pub fn as_bytes(&self) -> &[u8] {
217        &self.0
218    }
219}
220
221impl std::fmt::Display for PeerId {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        // Format as truncated hex string for readability (first 8 bytes)
224        for byte in &self.0[..8] {
225            write!(f, "{:02x}", byte)?;
226        }
227        Ok(())
228    }
229}
230
231/// Connection status
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub enum ConnectionStatus {
234    /// Connection is being established
235    Connecting,
236    /// Connection is active
237    Connected,
238    /// Connection is being closed
239    Disconnecting,
240    /// Connection is closed
241    Disconnected,
242    /// Connection failed
243    Failed(String),
244}
245
246/// Queue performance metrics
247#[derive(Debug, Clone, Default)]
248pub struct QueueMetrics {
249    /// Current queue size
250    pub current_size: usize,
251    /// Maximum queue size
252    pub max_size: usize,
253    /// Queue utilization (0.0 to 1.0)
254    pub utilization: f64,
255    /// High water mark
256    pub high_water_mark: usize,
257    /// Messages processed per second
258    pub messages_per_second: f64,
259}
260
261/// Latency performance metrics
262#[derive(Debug, Clone, Default)]
263pub struct LatencyMetrics {
264    /// Average message latency
265    pub avg_latency: Duration,
266    /// Peak message latency
267    pub peak_latency: Duration,
268    /// 95th percentile latency
269    pub p95_latency: Duration,
270    /// 99th percentile latency
271    pub p99_latency: Duration,
272}
273
274/// Throughput performance metrics
275#[derive(Debug, Clone, Default)]
276pub struct ThroughputMetrics {
277    /// Messages per second
278    pub messages_per_second: f64,
279    /// Bytes per second
280    pub bytes_per_second: f64,
281    /// Peak throughput
282    pub peak_throughput: f64,
283    /// Average throughput
284    pub avg_throughput: f64,
285    /// Total messages processed
286    pub total_messages: u64,
287}