Skip to content

Commit 71a76dc

Browse files
author
Ifeanyichukwu
committed
fix(cmd): add network validation in coffee cmd inputs
fix(cmd): add network validation in coffee cmd inputs
1 parent db419c6 commit 71a76dc

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

coffee_cmd/src/cmd.rs

+51-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
//! Coffee command line arguments definition.
22
use clap::{Parser, Subcommand};
3+
use coffee_lib::error;
4+
use coffee_lib::errors::CoffeeError;
5+
use std::fmt::Display;
36

47
/// Coffee main command line definition for the command line tools.
58
#[derive(Debug, Parser)]
@@ -133,6 +136,43 @@ impl From<&RemoteAction> for coffee_core::RemoteAction {
133136
}
134137
}
135138

139+
#[derive(Debug)]
140+
enum ClnNetwork {
141+
Mainnet,
142+
Testnet,
143+
Signet,
144+
Regtest,
145+
Liquid,
146+
}
147+
148+
impl Display for ClnNetwork {
149+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150+
let s = match self {
151+
ClnNetwork::Mainnet => "mainnet",
152+
ClnNetwork::Testnet => "testnet",
153+
ClnNetwork::Signet => "signet",
154+
ClnNetwork::Regtest => "regtest",
155+
ClnNetwork::Liquid => "liquid",
156+
};
157+
write!(f, "{}", s)
158+
}
159+
}
160+
161+
impl TryFrom<String> for ClnNetwork {
162+
type Error = String;
163+
164+
fn try_from(network: String) -> Result<Self, Self::Error> {
165+
match network.as_str() {
166+
"mainnet" => Ok(Self::Mainnet),
167+
"testnet" => Ok(Self::Testnet),
168+
"signet" => Ok(Self::Signet),
169+
"regtest" => Ok(Self::Regtest),
170+
"liquid" => Ok(Self::Liquid),
171+
_ => Err(format!("{} is not a valid network name", network)),
172+
}
173+
}
174+
}
175+
136176
impl coffee_core::CoffeeArgs for CoffeeArgs {
137177
fn command(&self) -> coffee_core::CoffeeOperation {
138178
coffee_core::CoffeeOperation::from(&self.command)
@@ -147,7 +187,17 @@ impl coffee_core::CoffeeArgs for CoffeeArgs {
147187
}
148188

149189
fn network(&self) -> Option<String> {
150-
self.network.clone()
190+
let network = self
191+
.network
192+
.clone()
193+
.ok_or_else(|| error!("Network is not set"))
194+
.ok()?;
195+
let validated_network = ClnNetwork::try_from(network.to_lowercase()).ok();
196+
197+
match validated_network {
198+
Some(valid_network) => format!("{}", valid_network).into(),
199+
None => None,
200+
}
151201
}
152202

153203
fn skip_verify(&self) -> bool {

0 commit comments

Comments
 (0)