NAC_Blockchain/sdk/nac-cli/src/commands/node.rs

95 lines
3.0 KiB
Rust

use crate::cli::*;
use crate::client::nac_lens::NacLensClient;
use crate::config::Config;
use crate::error::{CliError, Result};
use crate::utils::*;
use colored::Colorize;
pub async fn execute(cmd: &NodeCommands, _cli: &Cli) -> Result<()> {
match cmd {
NodeCommands::Info => show_node_info().await,
NodeCommands::Status => show_node_status().await,
NodeCommands::Peers => list_peers().await,
NodeCommands::Sync => show_sync_status().await,
}
}
async fn show_node_info() -> Result<()> {
let config = Config::load()
.map_err(|_| CliError::Config("未找到配置文件,请先运行 'nac config init'".to_string()))?;
let client = NacLensClient::new(config.get_current_rpc_url());
print_info("查询节点信息...");
let info = client.get_node_info().await?;
println!();
println!("{}", "节点信息".bold());
println!("{}", "=".repeat(80));
println!();
println!("{}", serde_json::to_string_pretty(&info).unwrap_or_default());
println!();
Ok(())
}
async fn show_node_status() -> Result<()> {
let config = Config::load()
.map_err(|_| CliError::Config("未找到配置文件,请先运行 'nac config init'".to_string()))?;
let client = NacLensClient::new(config.get_current_rpc_url());
print_info("查询节点状态...");
let health = client.get_node_health().await?;
println!();
println!("{}", "节点状态".bold());
println!("{}", "=".repeat(80));
println!();
println!("{}", serde_json::to_string_pretty(&health).unwrap_or_default());
println!();
Ok(())
}
async fn list_peers() -> Result<()> {
let config = Config::load()
.map_err(|_| CliError::Config("未找到配置文件,请先运行 'nac config init'".to_string()))?;
let client = NacLensClient::new(config.get_current_rpc_url());
print_info("查询对等节点...");
let peers = client.get_peers().await?;
println!();
println!("{}", format!("对等节点列表 (共{}个)", peers.len()).bold());
println!("{}", "=".repeat(80));
println!();
for (i, peer) in peers.iter().enumerate() {
println!("{}. {}", i + 1, serde_json::to_string_pretty(peer).unwrap_or_default());
}
println!();
Ok(())
}
async fn show_sync_status() -> Result<()> {
let config = Config::load()
.map_err(|_| CliError::Config("未找到配置文件,请先运行 'nac config init'".to_string()))?;
let client = NacLensClient::new(config.get_current_rpc_url());
print_info("查询同步状态...");
// 获取当前区块高度
let height = client.get_block_height().await?;
let peer_count = client.get_peer_count().await?;
println!();
println!("{}", "同步状态".bold());
println!("{}", "=".repeat(80));
println!();
println!(" {:18} {}", "当前区块高度:", height.to_string().cyan());
println!(" {:18} {}", "对等节点数:", peer_count.to_string().cyan());
println!();
Ok(())
}