1use crate::KaspaClient;
2use crate::types::{KaspaError, Result};
3use std::collections::{HashMap, VecDeque};
4use std::time::{Duration, Instant};
5
6pub 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, pub transaction_rate: f64, pub peer_count: usize,
36 pub network_hashrate: f64, 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 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 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 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 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 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>, pub protocol_versions: HashMap<u32, usize>, }
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}