gateway: added --output to commands that strictly require it

This commit is contained in:
Jędrzej Stuczyński
2023-03-30 15:36:38 +01:00
parent 4feb168cf7
commit 479327849a
29 changed files with 105 additions and 110 deletions
Generated
+1
View File
@@ -3156,6 +3156,7 @@ dependencies = [
"pretty_env_logger",
"semver 0.11.0",
"serde",
"serde_json",
"vergen",
]
+1 -1
View File
@@ -10,7 +10,7 @@ bip39 = { workspace = true }
clap = { version = "4.0", features = ["cargo", "derive"] }
log = "0.4"
rand = "0.7.3"
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
thiserror = "1.0"
url = "2.2"
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal", "macros"] } # async runtime
+3 -3
View File
@@ -26,8 +26,8 @@ lazy_static = "1.4.0"
log = { workspace = true } # self explanatory
pretty_env_logger = "0.4" # for formatting log messages
rand = { version = "0.7.3", features = ["wasm-bindgen"] } # rng-related traits + some rng implementation to use
serde = { version = "1.0.104", features = ["derive"] } # for config serialization/deserialization
serde_json = "1.0"
serde = { workspace = true, features = ["derive"] } # for config serialization/deserialization
serde_json = { workspace = true }
thiserror = "1.0.34"
tap = "1.0.1"
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } # async runtime
@@ -52,4 +52,4 @@ validator-client = { path = "../../common/client-libs/validator-client", feature
websocket-requests = { path = "websocket-requests" }
[dev-dependencies]
serde_json = "1.0" # for the "textsend" example
serde_json = { workspace = true } # for the "textsend" example
+2 -2
View File
@@ -7,7 +7,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
nym-sphinx = { path = "../../../common/nymsphinx" }
+1
View File
@@ -15,6 +15,7 @@ log = { workspace = true }
pretty_env_logger = "0.4.0"
semver = "0.11"
serde = { workspace = true, features = ["derive"], optional = true }
serde_json = { workspace = true, optional = true }
[build-dependencies]
vergen = { version = "=7.4.3", default-features = false, features = ["build", "git", "rustc", "cargo"] }
+1
View File
@@ -4,4 +4,5 @@
pub mod build_information;
pub mod completions;
pub mod logging;
pub mod output_format;
pub mod version_checker;
@@ -0,0 +1,36 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::ValueEnum;
use serde::Serialize;
use std::fmt::{Display, Formatter};
#[derive(Default, Copy, Debug, Clone, ValueEnum)]
pub enum OutputFormat {
#[default]
Text,
Json,
}
impl Display for OutputFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
OutputFormat::Text => write!(f, "text"),
OutputFormat::Json => write!(f, "json"),
}
}
}
impl OutputFormat {
pub fn is_text(&self) -> bool {
matches!(self, OutputFormat::Text)
}
#[cfg(feature = "serde_json")]
pub fn format<T: Serialize + ToString>(&self, data: &T) -> String {
match self {
OutputFormat::Text => data.to_string(),
OutputFormat::Json => serde_json::to_string(data).unwrap(),
}
}
}
+2 -2
View File
@@ -15,8 +15,8 @@ futures = "0.3"
humantime-serde = "1.0"
log = { workspace = true }
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.89"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tap = "1.0.1"
thiserror = "1.0.34"
url = { version ="2.2", features = ["serde"] }
+1 -1
View File
@@ -27,7 +27,7 @@ nym-sphinx = { path = "../../nymsphinx" }
nym-pemstore = { path = "../../pemstore" }
validator-client = { path = "../validator-client" }
nym-task = { path = "../../task" }
serde = { version = "1.0", features = ["derive"]}
serde = { workspace = true, features = ["derive"] }
mobile-storage = { path = "../../mobile-storage" }
@@ -19,8 +19,8 @@ nym-coconut-bandwidth-contract-common = { path = "../../cosmwasm-smart-contracts
nym-multisig-contract-common = { path = "../../cosmwasm-smart-contracts/multisig-contract" }
nym-group-contract-common = { path = "../../cosmwasm-smart-contracts/group-contract" }
nym-vesting-contract = { path = "../../../contracts/vesting" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
reqwest = { version = "0.11", features = ["json"] }
thiserror = "1"
log = { workspace = true }
+1 -1
View File
@@ -7,7 +7,7 @@ description = "Crutch library until there is proper SerDe support for coconut st
[dependencies]
bs58 = "0.4.0"
getset = "0.1.1"
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
thiserror = "1"
nymcoconut = {path = "../nymcoconut" }
+1 -1
View File
@@ -18,7 +18,7 @@ k256 = { version = "0.10", features = ["ecdsa", "sha256"] }
log = { workspace = true }
rand = {version = "0.6", features = ["std"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
serde_json = { workspace = true }
thiserror = "1"
time = { version = "0.3.6", features = ["parsing", "formatting"] }
toml = "0.5.6"
+1 -1
View File
@@ -10,7 +10,7 @@ edition = "2021"
cfg-if = "1.0.0"
handlebars = "3.0.1"
log = { workspace = true }
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
toml = "0.5.6"
url = "2.2"
+1 -1
View File
@@ -13,7 +13,7 @@ itertools = "0.10"
reqwest = "0.11.9"
schemars = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json = { workspace = true }
strum = { version = "0.23", features = ["derive"] }
thiserror = "1.0"
url = "2.2"
+1
View File
@@ -18,6 +18,7 @@ impl ConsoleSigningOutput {
}
}
#[deprecated]
pub fn to_json_string(&self) -> String {
serde_json::to_string(self).expect("json serialization of 'ConsoleSigningOutput' failed")
}
+3 -3
View File
@@ -31,7 +31,7 @@ log = { workspace = true }
once_cell = "1.7.2"
pretty_env_logger = "0.4"
rand = "0.7"
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
sqlx = { version = "0.5", features = [
"runtime-tokio-rustls",
"sqlite",
@@ -56,7 +56,7 @@ nym-coconut-interface = { path = "../common/coconut-interface" }
nym-credentials = { path = "../common/credentials" }
nym-config = { path = "../common/config" }
nym-crypto = { path = "../common/crypto" }
nym-bin-common = { path = "../common/bin-common" }
nym-bin-common = { path = "../common/bin-common", features = ["serde_json"] }
gateway-requests = { path = "gateway-requests" }
mixnet-client = { path = "../common/client-libs/mixnet-client" }
mixnode-common = { path = "../common/mixnode-common" }
@@ -70,7 +70,7 @@ validator-client = { path = "../common/client-libs/validator-client", features =
"nyxd-client",
] }
nym-types = { path = "../common/types" }
serde_json = "1"
serde_json = { workspace = true }
atty = "0.2"
+2 -2
View File
@@ -15,8 +15,8 @@ futures = "0.3.15"
log = { workspace = true }
nym-sphinx = { path = "../../common/nymsphinx" }
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = "1.0"
nym-crypto = { path = "../../common/crypto" }
+6 -2
View File
@@ -77,6 +77,9 @@ pub struct Init {
/// URL where a statistics aggregator is running. The default value is a Nym aggregator server
#[clap(long)]
statistics_service_url: Option<url::Url>,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
impl From<Init> for OverrideConfig {
@@ -100,7 +103,7 @@ impl From<Init> for OverrideConfig {
}
}
pub async fn execute(args: Init, output: OutputFormat) -> Result<(), Box<dyn Error + Send + Sync>> {
pub async fn execute(args: Init) -> Result<(), Box<dyn Error + Send + Sync>> {
eprintln!("Initialising gateway {}...", args.id);
let already_init = if Config::default_config_file_path(&args.id).exists() {
@@ -156,7 +159,7 @@ pub async fn execute(args: Init, output: OutputFormat) -> Result<(), Box<dyn Err
Ok(crate::node::create_gateway(config)
.await
.print_node_details(output)?)
.print_node_details(args.output))
}
#[cfg(test)]
@@ -183,6 +186,7 @@ mod tests {
enabled_statistics: None,
nyxd_urls: None,
only_coconut_credentials: None,
output: Default::default(),
};
std::env::set_var(BECH32_PREFIX, "n");
+4 -6
View File
@@ -65,13 +65,11 @@ pub(crate) struct OverrideConfig {
pub(crate) async fn execute(args: Cli) -> Result<(), Box<dyn Error + Send + Sync>> {
let bin_name = "nym-gateway";
let output = args.output();
match args.command {
Commands::Init(m) => init::execute(m, output).await?,
Commands::NodeDetails(m) => node_details::execute(m, output).await?,
Commands::Run(m) => run::execute(m, output).await?,
Commands::Sign(m) => sign::execute(m, output)?,
Commands::Init(m) => init::execute(m).await?,
Commands::NodeDetails(m) => node_details::execute(m).await?,
Commands::Run(m) => run::execute(m).await?,
Commands::Sign(m) => sign::execute(m)?,
Commands::Upgrade(m) => upgrade::execute(&m).await,
Commands::Completions(s) => s.generate(&mut crate::Cli::command(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut crate::Cli::command(), bin_name),
+6 -6
View File
@@ -3,8 +3,8 @@
use crate::commands::OverrideConfig;
use crate::support::config::build_config;
use crate::OutputFormat;
use clap::Args;
use nym_bin_common::output_format::OutputFormat;
use std::error::Error;
#[derive(Args, Clone)]
@@ -12,15 +12,15 @@ pub struct NodeDetails {
/// The id of the gateway you want to show details for
#[clap(long)]
id: String,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
pub async fn execute(
args: NodeDetails,
output: OutputFormat,
) -> Result<(), Box<dyn Error + Send + Sync>> {
pub async fn execute(args: NodeDetails) -> Result<(), Box<dyn Error + Send + Sync>> {
let config = build_config(args.id.clone(), OverrideConfig::default())?;
Ok(crate::node::create_gateway(config)
.await
.print_node_details(output)?)
.print_node_details(args.output))
}
+9 -7
View File
@@ -1,12 +1,10 @@
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::commands::{ensure_config_version_compatibility, OverrideConfig};
use crate::support::config::build_config;
use crate::{
commands::{ensure_config_version_compatibility, OverrideConfig},
OutputFormat,
};
use clap::Args;
use nym_bin_common::output_format::OutputFormat;
use std::error::Error;
use std::net::IpAddr;
use std::path::PathBuf;
@@ -75,6 +73,9 @@ pub struct Run {
/// URL where a statistics aggregator is running. The default value is a Nym aggregator server
#[clap(long)]
statistics_service_url: Option<url::Url>,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
impl From<Run> for OverrideConfig {
@@ -112,10 +113,11 @@ fn special_addresses() -> Vec<&'static str> {
vec!["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"]
}
pub async fn execute(args: Run, output: OutputFormat) -> Result<(), Box<dyn Error + Send + Sync>> {
pub async fn execute(args: Run) -> Result<(), Box<dyn Error + Send + Sync>> {
let id = args.id.clone();
println!("Starting gateway {id}...");
eprintln!("Starting gateway {id}...");
let output = args.output;
let config = build_config(id, args)?;
ensure_config_version_compatibility(&config)?;
@@ -127,7 +129,7 @@ pub async fn execute(args: Run, output: OutputFormat) -> Result<(), Box<dyn Erro
eprintln!(
"\nTo bond your gateway you will need to install the Nym wallet, go to https://nymtech.net/get-involved and select the Download button.\n\
Select the correct version and install it to your machine. You will need to provide the following: \n ");
gateway.print_node_details(output)?;
gateway.print_node_details(output);
gateway.run().await
}
+9 -14
View File
@@ -6,10 +6,11 @@ use crate::error::GatewayError;
use crate::support::config::build_config;
use crate::{
commands::ensure_config_version_compatibility,
config::persistence::pathfinder::GatewayPathfinder, OutputFormat,
config::persistence::pathfinder::GatewayPathfinder,
};
use anyhow::{bail, Result};
use clap::{ArgGroup, Args};
use nym_bin_common::output_format::OutputFormat;
use nym_crypto::asymmetric::identity;
use nym_types::helpers::ConsoleSigningOutput;
use std::error::Error;
@@ -34,6 +35,9 @@ pub struct Sign {
/// Signs a transaction-specific payload, that is going to be sent to the smart contract, with your identity key
#[clap(long)]
contract_msg: Option<String>,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
enum SignedTarget {
@@ -94,12 +98,7 @@ fn print_signed_text(
let signature = private_key.sign_text(text);
let sign_output = ConsoleSigningOutput::new(text, signature);
let msg = match output {
OutputFormat::Json => sign_output.to_json_string(),
OutputFormat::Text => sign_output.to_string(),
};
println!("{msg}");
println!("{}", output.format(&sign_output));
Ok(())
}
@@ -131,18 +130,14 @@ fn print_signed_contract_msg(
let signature = private_key.sign(&decoded).to_base58_string();
let sign_output = ConsoleSigningOutput::new(decoded_string, signature);
let msg = match output {
OutputFormat::Json => sign_output.to_json_string(),
OutputFormat::Text => sign_output.to_string(),
};
println!("{msg}")
println!("{}", output.format(&sign_output));
}
pub fn execute(args: Sign, output: OutputFormat) -> Result<(), Box<dyn Error + Send + Sync>> {
pub fn execute(args: Sign) -> Result<(), Box<dyn Error + Send + Sync>> {
let config = build_config(args.id.clone(), OverrideConfig::default())?;
ensure_config_version_compatibility(&config)?;
let output = args.output;
let signed_target = SignedTarget::try_from(args)?;
let pathfinder = GatewayPathfinder::new_from_config(&config);
let identity_keypair = load_identity_keys(&pathfinder);
+3 -27
View File
@@ -1,11 +1,12 @@
// Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::{crate_name, crate_version, Parser, ValueEnum};
use clap::{crate_name, crate_version, Parser};
use colored::Colorize;
use lazy_static::lazy_static;
use log::error;
use nym_bin_common::logging::setup_logging;
use nym_bin_common::output_format::OutputFormat;
use nym_bin_common::{build_information::BinaryBuildInformation, logging::banner};
use nym_network_defaults::setup_env;
use std::error::Error;
@@ -26,18 +27,6 @@ fn pretty_build_info_static() -> &'static str {
&PRETTY_BUILD_INFORMATION
}
#[derive(Clone, ValueEnum)]
pub enum OutputFormat {
Json,
Text,
}
impl Default for OutputFormat {
fn default() -> Self {
OutputFormat::Text
}
}
#[derive(Parser)]
#[clap(author = "Nymtech", version, about, long_version = pretty_build_info_static())]
struct Cli {
@@ -45,23 +34,10 @@ struct Cli {
#[clap(short, long)]
pub(crate) config_env_file: Option<std::path::PathBuf>,
#[clap(short, long)]
pub(crate) output: Option<OutputFormat>,
#[clap(subcommand)]
command: commands::Commands,
}
impl Cli {
fn output(&self) -> OutputFormat {
if let Some(ref output) = self.output {
output.clone()
} else {
OutputFormat::default()
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
setup_logging();
+3 -11
View File
@@ -11,9 +11,9 @@ use crate::node::client_handling::websocket::connection_handler::coconut::Coconu
use crate::node::mixnet_handling::receiver::connection_handler::ConnectionHandler;
use crate::node::statistics::collector::GatewayStatisticsCollector;
use crate::node::storage::Storage;
use crate::OutputFormat;
use log::*;
use mixnet_client::forwarder::{MixForwardingSender, PacketForwarder};
use nym_bin_common::output_format::OutputFormat;
use nym_crypto::asymmetric::{encryption, identity};
use nym_network_defaults::NymNetworkDetails;
use nym_statistics_common::collector::StatisticsSender;
@@ -106,7 +106,7 @@ where
sphinx_keypair
}
pub(crate) fn print_node_details(&self, output: OutputFormat) -> Result<(), GatewayError> {
pub(crate) fn print_node_details(&self, output: OutputFormat) {
let node_details = nym_types::gateway::GatewayNodeDetailsResponse {
identity_key: self.identity_keypair.public_key().to_base58_string(),
sphinx_key: self.sphinx_keypair.public_key().to_base58_string(),
@@ -123,15 +123,7 @@ where
.to_string(),
};
match output {
OutputFormat::Json => println!(
"{}",
serde_json::to_string(&node_details)
.unwrap_or_else(|_| "Could not serialize node details".to_string())
),
OutputFormat::Text => println!("{}", node_details),
}
Ok(())
println!("{}", output.format(&node_details));
}
fn start_mix_socket_listener(
+2 -2
View File
@@ -29,8 +29,8 @@ log = { workspace = true }
pretty_env_logger = "0.4.0"
rand = "0.7.3"
rocket = { version = "0.5.0-rc.2", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sysinfo = "0.27.7"
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
tokio-util = { version = "0.7.3", features = ["codec"] }
-12
View File
@@ -24,18 +24,6 @@ fn pretty_build_info_static() -> &'static str {
&PRETTY_BUILD_INFORMATION
}
#[derive(Clone, ValueEnum)]
enum OutputFormat {
Json,
Text,
}
impl Default for OutputFormat {
fn default() -> Self {
OutputFormat::Text
}
}
#[derive(Parser)]
#[clap(author = "Nymtech", version, about, long_version = pretty_build_info_static())]
struct Cli {
+1 -1
View File
@@ -34,7 +34,7 @@ reqwest = { version = "0.11.11", features = ["json"] }
rocket = { version = "0.5.0-rc.2", features = ["json"] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", rev = "dfd3662c49e2f6fc37df35091cb94d82f7fb5915" }
serde = "1.0"
serde_json = "1.0"
serde_json = { workspace = true }
tap = "1.0"
thiserror = "1.0"
time = { version = "0.3.14", features = ["serde-human-readable", "parsing"] }
@@ -22,7 +22,7 @@ pretty_env_logger = "0.4.0"
publicsuffix = "1.5" # Can't update this until bip updates to support newer idna version
rand = "0.7.3"
reqwest = { version = "0.11.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
sqlx = { version = "0.6.1", features = ["runtime-tokio-rustls", "chrono"]}
tap = { workspace = true }
thiserror = "1.0"
@@ -10,7 +10,7 @@ dirs = "4.0"
log = { workspace = true }
pretty_env_logger = "0.4"
rocket = { version = "0.5.0-rc.2", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde = { workspace = true, features = ["derive"] }
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate", "chrono"]}
thiserror = "1"
tokio = { version = "1.4", features = [ "net", "rt-multi-thread", "macros", "time" ] }