watcher/node/src/cli.rs

80 lines
2.9 KiB
Rust

use crate::args::*;
use crate::network::NodeId;
use shared::blockchain_core::ChainData;
use vlogger::*;
use crate::watcher::WatcherCommand;
use crate::node::*;
use crate::log;
use cli_renderer::RenderCommand;
use clap::Parser;
pub fn handle_peer_command(cmd: CliPeerCommand) -> NodeCommand {
match cmd {
CliPeerCommand::List => NodeCommand::ListPeers,
CliPeerCommand::Remove { id } => NodeCommand::RemovePeer {
peer_id: NodeId(*id.parse::<uuid::Uuid>().unwrap().as_bytes()),
},
CliPeerCommand::Connect { addr } => NodeCommand::ConnectTcpPeer(addr),
}
}
pub fn handle_block_command(cmd: CliBlockCommand) -> NodeCommand {
match cmd {
CliBlockCommand::List => NodeCommand::ListBlocks,
CliBlockCommand::Create => NodeCommand::CreateBlock,
CliBlockCommand::Display { key, height } => match (key, height) {
(Some(k), _) => return NodeCommand::DisplayBlockByKey(k),
(_, Some(h)) => return NodeCommand::DisplayBlockByHeight(h),
(None, None) => return NodeCommand::DisplayBlockInteractive,
},
}
}
fn handle_seed_command(cmd: CliSeedCommand) -> NodeCommand {
match cmd {
CliSeedCommand::Connect => NodeCommand::ConnectToSeeds,
}
}
fn handle_ping(cmd: CliPingCommand) -> NodeCommand {
match cmd {
CliPingCommand::Id { id } => {
let id = NodeId(*id.parse::<uuid::Uuid>().unwrap().as_bytes());
NodeCommand::PingId(id)
},
CliPingCommand::Addr { addr } => NodeCommand::PingAddr(addr),
}
}
pub fn cli(input: &str) -> WatcherCommand {
let argv: Vec<&str> = std::iter::once(" ")
.chain(input.split_whitespace())
.collect();
match Cli::try_parse_from(argv) {
Ok(cmd) => match cmd.command {
CliCommand::Layout { mode } => WatcherCommand::Render(RenderCommand::ChangeLayout(mode)),
CliCommand::Clear => WatcherCommand::Render(RenderCommand::ClearPane),
CliCommand::Peer { peer_cmd } => WatcherCommand::Node(handle_peer_command(peer_cmd)),
CliCommand::Block { block_cmd } => WatcherCommand::Node(handle_block_command(block_cmd)),
CliCommand::Transaction(tx) => {
WatcherCommand::Node(NodeCommand::ProcessChainData(ChainData::NodeTransaction(tx)))
}
CliCommand::Award { address, amount } => {
log(msg!(DEBUG, "Received address: {:?}", address));
if address.len() != 20 {
log(msg!(ERROR, "Invalid address length"))
}
WatcherCommand::Node(NodeCommand::AwardCurrency{ address, amount }
)}
CliCommand::DebugShowId => WatcherCommand::Node(NodeCommand::ShowId),
CliCommand::StartListner { addr } => {
WatcherCommand::Node(NodeCommand::StartListner(addr.parse().unwrap()))
}
CliCommand::Seeds { seed_cmd } => WatcherCommand::Node(handle_seed_command(seed_cmd)),
CliCommand::Ping { ping_cmd } => WatcherCommand::Node(handle_ping(ping_cmd)),
},
Err(e) => WatcherCommand::InvalidCommand(format!("{e}")),
}
}