Skip to main content

kaspa_sdk/
monitor.rs

1use crate::KaspaClient;
2use crate::types::{KaspaError, Result};
3use std::collections::{HashMap, VecDeque};
4use std::time::{Duration, Instant};
5
6/// Network monitoring for Kaspa node
7///
8/// # Examples
9/// ```
10/// #[tokio::main]
11/// async fn main() {
12///     let client = KaspaClient::new("");
13///     let mut monitor_arc = Arc::new(NetworkMonitor::new(client));
14///     tokio::spawn(async move {
15///         monitor_arc.clone().start_monitoring().await.unwrap();
16///     });
17///     loop {
18///         let report = monitor.generate_health_report();
19///         println!("Network healthy: {}", report.is_healthy);
20///         tokio::time::sleep(Duration::from_secs(60)).await;
21///     }
22/// }
23/// ```
24pub struct NetworkMonitor {
25    client: KaspaClient,
26    metrics: NetworkMetrics,
27    history: VecDeque<NetworkSnapshot>,
28    max_history_size: usize,
29}
30
31#[derive(Debug, Clone)]
32pub struct NetworkMetrics {
33    pub block_rate: f64,       // block/s
34    pub transaction_rate: f64, // trade/s
35    pub peer_count: usize,
36    pub network_hashrate: f64, // network hashrate(computing power)
37    pub difficulty: f64,
38}
39
40pub struct NetworkSnapshot {
41    pub timestamp: Instant,
42    pub block_count: u64,
43    pub mempool_size: usize,
44    pub peer_count: usize,
45}
46
47impl NetworkMonitor {
48    /// create new network monitor
49    ///
50    /// # Examples
51    /// ```
52    /// let client = KaspaClient::new("http://localhost:16110");
53    /// let monitor = NetworkMonitor::new(client);
54    /// ```
55    pub fn new(client: KaspaClient) -> Self {
56        Self {
57            client,
58            metrics: NetworkMetrics::default(),
59            history: VecDeque::new(),
60            max_history_size: 1000,
61        }
62    }
63
64    /// start monitoring
65    ///
66    /// # Examples
67    /// ```rust
68    /// let mut monitor = NetworkMonitor::new(client);
69    /// tokio::spawn(async move {
70    ///     monitor.start_monitoring().await.unwrap();
71    /// });
72    /// ```
73    pub async fn start_monitoring(&mut self) -> Result<()> {
74        loop {
75            if let Err(e) = self.update_metrics().await {
76                println!("Monitoring error: {}", e);
77            }
78            tokio::time::sleep(Duration::from_secs(10)).await;
79        }
80    }
81
82    async fn update_metrics(&mut self) -> Result<()> {
83        let snapshot = self.create_snapshot().await?;
84        self.history.push_back(snapshot);
85        if self.history.len() > self.max_history_size {
86            self.history.pop_front();
87        }
88        self.calculate_metrics().await?;
89        Ok(())
90    }
91
92    /// create snapshot
93    async fn create_snapshot(&self) -> Result<NetworkSnapshot> {
94        let info = self.client.get_info().await?;
95        let mempool_entries = self.client.get_mempool_entries(None).await?;
96        Ok(NetworkSnapshot {
97            timestamp: Instant::now(),
98            block_count: info.block_count,
99            mempool_size: mempool_entries.len(),
100            peer_count: self.client.get_connected_peer_info().await.unwrap().len(),
101        })
102    }
103
104    async fn calculate_metrics(&mut self) -> Result<()> {
105        if self.history.len() < 2 {
106            return Ok(());
107        }
108        let latest = self.history.back().unwrap();
109        let previous = self.history.front().unwrap();
110        let time_diff = latest
111            .timestamp
112            .duration_since(previous.timestamp)
113            .as_secs_f64();
114        let block_diff = latest.block_count - previous.block_count;
115        self.metrics.block_rate = block_diff as f64 / time_diff.max(1.0);
116        self.metrics.peer_count = latest.peer_count;
117        self.metrics.network_hashrate = self.estimate_network_hashrate().await?;
118        Ok(())
119    }
120
121    async fn estimate_network_hashrate(&self) -> Result<f64> {
122        // Estimating network computing power based on difficulty and block time
123        let hashrate_response = self
124            .client
125            .estimate_network_hashes_per_second(Some(100))
126            .await?;
127        hashrate_response
128            .network_hashes_per_second
129            .parse::<f64>()
130            .map_err(|e| KaspaError::Custom(format!("Failed to parse hashrate: {}", e)))
131    }
132
133    /// Generate health health report
134    ///
135    /// # Examples
136    /// ```
137    /// let monitor = NetworkMonitor::new(client);
138    /// let report = monitor.generate_health_report();
139    /// if !report.is_healthy {
140    ///     println!("ALERT: {}", report.recommendation);
141    ///     // Send alert notification...
142    /// }
143    /// println!("Block rate: {:.2} B/s", report.metrics.block_rate);
144    /// println!("Peers: {}", report.metrics.peer_count);
145    /// ```
146    pub fn generate_health_report(&self) -> NetworkHealthReport {
147        NetworkHealthReport {
148            metrics: self.metrics.clone(),
149            is_healthy: self.metrics.block_rate > 0.1,
150            recommendation: if self.metrics.peer_count < 5 {
151                "Low peer count, consider adding more connections".to_string()
152            } else {
153                "Network healthy".to_string()
154            },
155        }
156    }
157}
158
159impl Default for NetworkMetrics {
160    fn default() -> Self {
161        Self {
162            block_rate: 0.0,
163            transaction_rate: 0.0,
164            peer_count: 0,
165            network_hashrate: 0.0,
166            difficulty: 0.0,
167        }
168    }
169}
170
171pub struct DetailedNetworkMetrics {
172    pub inbound_peers: usize,
173    pub outbound_peers: usize,
174    pub average_ping: f64,
175    pub user_agents: HashMap<String, usize>, // User agent statistics
176    pub protocol_versions: HashMap<u32, usize>, // Protocol version statistics
177}
178
179pub struct NetworkHealthReport {
180    pub metrics: NetworkMetrics,
181    pub is_healthy: bool,
182    pub recommendation: String,
183}
184pub struct DetailedNetworkReport {
185    pub basic_metrics: NetworkMetrics,
186    pub peer_metrics: DetailedNetworkMetrics,
187    pub health_status: bool,
188    pub recommendations: Vec<String>,
189    pub timestamp: Instant,
190}
191
192impl DetailedNetworkReport {
193    pub fn display(&self) {
194        println!("=== Kaspa Network Report ===");
195        println!(
196            "Health Status: {}",
197            if self.health_status {
198                "✅ Healthy"
199            } else {
200                "❌ Unhealthy"
201            }
202        );
203        println!(
204            "Block Rate: {:.2} blocks/sec",
205            self.basic_metrics.block_rate
206        );
207        println!(
208            "Transaction Rate: {:.2} tx/sec",
209            self.basic_metrics.transaction_rate
210        );
211        println!(
212            "Network Hashrate: {:.2} H/s",
213            self.basic_metrics.network_hashrate
214        );
215        println!(
216            "Connected Peers: {} (In: {}, Out: {})",
217            self.basic_metrics.peer_count,
218            self.peer_metrics.inbound_peers,
219            self.peer_metrics.outbound_peers
220        );
221        println!("Average Ping: {:.2} ms", self.peer_metrics.average_ping);
222
223        if !self.recommendations.is_empty() {
224            println!("Recommendations:");
225            for rec in &self.recommendations {
226                println!("  - {}", rec);
227            }
228        }
229    }
230}