From 479327849a3e2a882a8fbfbb77b307c3389fffbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 15:36:38 +0100 Subject: [PATCH 1/9] gateway: added --output to commands that strictly require it --- Cargo.lock | 1 + clients/credential/Cargo.toml | 2 +- clients/native/Cargo.toml | 6 ++-- clients/native/websocket-requests/Cargo.toml | 4 +-- common/bin-common/Cargo.toml | 1 + common/bin-common/src/lib.rs | 1 + common/bin-common/src/output_format/mod.rs | 36 +++++++++++++++++++ common/client-core/Cargo.toml | 4 +-- common/client-libs/gateway-client/Cargo.toml | 2 +- .../client-libs/validator-client/Cargo.toml | 4 +-- common/coconut-interface/Cargo.toml | 2 +- common/commands/Cargo.toml | 2 +- common/config/Cargo.toml | 2 +- common/types/Cargo.toml | 2 +- common/types/src/helpers.rs | 1 + gateway/Cargo.toml | 6 ++-- gateway/gateway-requests/Cargo.toml | 4 +-- gateway/src/commands/init.rs | 8 +++-- gateway/src/commands/mod.rs | 10 +++--- gateway/src/commands/node_details.rs | 12 +++---- gateway/src/commands/run.rs | 16 +++++---- gateway/src/commands/sign.rs | 23 +++++------- gateway/src/main.rs | 30 ++-------------- gateway/src/node/mod.rs | 14 ++------ mixnode/Cargo.toml | 4 +-- mixnode/src/main.rs | 12 ------- nym-api/Cargo.toml | 2 +- .../network-requester/Cargo.toml | 2 +- .../network-statistics/Cargo.toml | 2 +- 29 files changed, 105 insertions(+), 110 deletions(-) create mode 100644 common/bin-common/src/output_format/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 1cc99e3071..0b95bb44ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3156,6 +3156,7 @@ dependencies = [ "pretty_env_logger", "semver 0.11.0", "serde", + "serde_json", "vergen", ] diff --git a/clients/credential/Cargo.toml b/clients/credential/Cargo.toml index b82767a434..98d9fbbd67 100644 --- a/clients/credential/Cargo.toml +++ b/clients/credential/Cargo.toml @@ -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 diff --git a/clients/native/Cargo.toml b/clients/native/Cargo.toml index b8bd48d01e..9a92353283 100644 --- a/clients/native/Cargo.toml +++ b/clients/native/Cargo.toml @@ -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 diff --git a/clients/native/websocket-requests/Cargo.toml b/clients/native/websocket-requests/Cargo.toml index 0f0921f636..cd1f5b589f 100644 --- a/clients/native/websocket-requests/Cargo.toml +++ b/clients/native/websocket-requests/Cargo.toml @@ -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" } diff --git a/common/bin-common/Cargo.toml b/common/bin-common/Cargo.toml index 21f90d27f9..6c0750e3c6 100644 --- a/common/bin-common/Cargo.toml +++ b/common/bin-common/Cargo.toml @@ -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"] } diff --git a/common/bin-common/src/lib.rs b/common/bin-common/src/lib.rs index eed7b4f998..8659264149 100644 --- a/common/bin-common/src/lib.rs +++ b/common/bin-common/src/lib.rs @@ -4,4 +4,5 @@ pub mod build_information; pub mod completions; pub mod logging; +pub mod output_format; pub mod version_checker; diff --git a/common/bin-common/src/output_format/mod.rs b/common/bin-common/src/output_format/mod.rs new file mode 100644 index 0000000000..dfde754237 --- /dev/null +++ b/common/bin-common/src/output_format/mod.rs @@ -0,0 +1,36 @@ +// Copyright 2023 - Nym Technologies SA +// 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(&self, data: &T) -> String { + match self { + OutputFormat::Text => data.to_string(), + OutputFormat::Json => serde_json::to_string(data).unwrap(), + } + } +} diff --git a/common/client-core/Cargo.toml b/common/client-core/Cargo.toml index 856cd17e57..6ca0d7ba6b 100644 --- a/common/client-core/Cargo.toml +++ b/common/client-core/Cargo.toml @@ -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"] } diff --git a/common/client-libs/gateway-client/Cargo.toml b/common/client-libs/gateway-client/Cargo.toml index f630a24154..7d3bd02ba1 100644 --- a/common/client-libs/gateway-client/Cargo.toml +++ b/common/client-libs/gateway-client/Cargo.toml @@ -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" } diff --git a/common/client-libs/validator-client/Cargo.toml b/common/client-libs/validator-client/Cargo.toml index 3df2637ebb..4c0917b5d4 100644 --- a/common/client-libs/validator-client/Cargo.toml +++ b/common/client-libs/validator-client/Cargo.toml @@ -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 } diff --git a/common/coconut-interface/Cargo.toml b/common/coconut-interface/Cargo.toml index 18f9115052..30093aa243 100644 --- a/common/coconut-interface/Cargo.toml +++ b/common/coconut-interface/Cargo.toml @@ -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" } diff --git a/common/commands/Cargo.toml b/common/commands/Cargo.toml index 86f8fcc54a..d4cdfbe91d 100644 --- a/common/commands/Cargo.toml +++ b/common/commands/Cargo.toml @@ -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" diff --git a/common/config/Cargo.toml b/common/config/Cargo.toml index 496d483d75..3add3dc1b4 100644 --- a/common/config/Cargo.toml +++ b/common/config/Cargo.toml @@ -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" diff --git a/common/types/Cargo.toml b/common/types/Cargo.toml index 5f822c4987..d1c1cfd67a 100644 --- a/common/types/Cargo.toml +++ b/common/types/Cargo.toml @@ -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" diff --git a/common/types/src/helpers.rs b/common/types/src/helpers.rs index 87ef78c90c..7c8f69de8d 100644 --- a/common/types/src/helpers.rs +++ b/common/types/src/helpers.rs @@ -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") } diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index cc6a1d6a3d..317a5e1f81 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -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" diff --git a/gateway/gateway-requests/Cargo.toml b/gateway/gateway-requests/Cargo.toml index 3fce04a8ae..ab663c6e27 100644 --- a/gateway/gateway-requests/Cargo.toml +++ b/gateway/gateway-requests/Cargo.toml @@ -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" } diff --git a/gateway/src/commands/init.rs b/gateway/src/commands/init.rs index 02eefb6f69..1a51e912e0 100644 --- a/gateway/src/commands/init.rs +++ b/gateway/src/commands/init.rs @@ -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, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -100,7 +103,7 @@ impl From for OverrideConfig { } } -pub async fn execute(args: Init, output: OutputFormat) -> Result<(), Box> { +pub async fn execute(args: Init) -> Result<(), Box> { 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 Result<(), Box> { 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), diff --git a/gateway/src/commands/node_details.rs b/gateway/src/commands/node_details.rs index 694bdb15b8..36f682bd10 100644 --- a/gateway/src/commands/node_details.rs +++ b/gateway/src/commands/node_details.rs @@ -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> { +pub async fn execute(args: NodeDetails) -> Result<(), Box> { 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)) } diff --git a/gateway/src/commands/run.rs b/gateway/src/commands/run.rs index 4000fd8a7f..8c9635a557 100644 --- a/gateway/src/commands/run.rs +++ b/gateway/src/commands/run.rs @@ -1,12 +1,10 @@ // Copyright 2020-2023 - Nym Technologies SA // 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, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From 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> { +pub async fn execute(args: Run) -> Result<(), Box> { 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, + + #[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> { +pub fn execute(args: Sign) -> Result<(), Box> { 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); diff --git a/gateway/src/main.rs b/gateway/src/main.rs index 11f8e69457..b17906d4f0 100644 --- a/gateway/src/main.rs +++ b/gateway/src/main.rs @@ -1,11 +1,12 @@ -// Copyright 2020 - Nym Technologies SA +// Copyright 2020-2023 - Nym Technologies SA // 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, - #[clap(short, long)] - pub(crate) output: Option, - #[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> { setup_logging(); diff --git a/gateway/src/node/mod.rs b/gateway/src/node/mod.rs index 343802fea1..5d135fef0f 100644 --- a/gateway/src/node/mod.rs +++ b/gateway/src/node/mod.rs @@ -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( diff --git a/mixnode/Cargo.toml b/mixnode/Cargo.toml index 3a1a21b9af..53d3857a55 100644 --- a/mixnode/Cargo.toml +++ b/mixnode/Cargo.toml @@ -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"] } diff --git a/mixnode/src/main.rs b/mixnode/src/main.rs index 609e63a0ad..277f4b8f66 100644 --- a/mixnode/src/main.rs +++ b/mixnode/src/main.rs @@ -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 { diff --git a/nym-api/Cargo.toml b/nym-api/Cargo.toml index d6e3be4373..fad3925f93 100644 --- a/nym-api/Cargo.toml +++ b/nym-api/Cargo.toml @@ -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"] } diff --git a/service-providers/network-requester/Cargo.toml b/service-providers/network-requester/Cargo.toml index bf49bab7c1..fe39370b8e 100644 --- a/service-providers/network-requester/Cargo.toml +++ b/service-providers/network-requester/Cargo.toml @@ -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" diff --git a/service-providers/network-statistics/Cargo.toml b/service-providers/network-statistics/Cargo.toml index 14c4cc317e..9ee8add427 100644 --- a/service-providers/network-statistics/Cargo.toml +++ b/service-providers/network-statistics/Cargo.toml @@ -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" ] } From 1347535e8fcc8e423c9b4b772c3da91bbe7628ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 15:41:47 +0100 Subject: [PATCH 2/9] mixnode: ibid --- common/types/src/helpers.rs | 5 ----- mixnode/Cargo.toml | 2 +- mixnode/src/commands/init.rs | 9 ++++++--- mixnode/src/commands/mod.rs | 12 +++++------- mixnode/src/commands/node_details.rs | 9 ++++++--- mixnode/src/commands/run.rs | 15 +++++++++------ mixnode/src/commands/sign.rs | 27 ++++++++++----------------- mixnode/src/main.rs | 15 +-------------- mixnode/src/node/mod.rs | 11 ++--------- 9 files changed, 40 insertions(+), 65 deletions(-) diff --git a/common/types/src/helpers.rs b/common/types/src/helpers.rs index 7c8f69de8d..29bceb8ff7 100644 --- a/common/types/src/helpers.rs +++ b/common/types/src/helpers.rs @@ -17,11 +17,6 @@ impl ConsoleSigningOutput { encoded_signature: encoded_signature.into(), } } - - #[deprecated] - pub fn to_json_string(&self) -> String { - serde_json::to_string(self).expect("json serialization of 'ConsoleSigningOutput' failed") - } } impl Display for ConsoleSigningOutput { diff --git a/mixnode/Cargo.toml b/mixnode/Cargo.toml index 53d3857a55..fce6af86e9 100644 --- a/mixnode/Cargo.toml +++ b/mixnode/Cargo.toml @@ -51,7 +51,7 @@ nym-task = { path = "../common/task" } nym-types = { path = "../common/types" } nym-topology = { path = "../common/topology" } validator-client = { path = "../common/client-libs/validator-client" } -nym-bin-common = { path = "../common/bin-common" } +nym-bin-common = { path = "../common/bin-common", features = ["serde_json"] } cpu-cycles = { path = "../cpu-cycles", optional = true } [dev-dependencies] diff --git a/mixnode/src/commands/init.rs b/mixnode/src/commands/init.rs index 9dc60f2369..db3474c088 100644 --- a/mixnode/src/commands/init.rs +++ b/mixnode/src/commands/init.rs @@ -4,9 +4,9 @@ use super::OverrideConfig; use crate::config::Config; use crate::node::MixNode; -use crate::OutputFormat; use crate::{commands::override_config, config::persistence::pathfinder::MixNodePathfinder}; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use nym_crypto::asymmetric::{encryption, identity}; use std::net::IpAddr; @@ -46,6 +46,9 @@ pub(crate) struct Init { // the alias here is included for backwards compatibility (1.1.4 and before) #[clap(long, alias = "validators", value_delimiter = ',')] nym_apis: Option>, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -63,7 +66,7 @@ impl From for OverrideConfig { } } -pub(crate) fn execute(args: &Init, output: OutputFormat) { +pub(crate) fn execute(args: &Init) { let override_config_fields = OverrideConfig::from(args.clone()); let id = &override_config_fields.id; eprintln!("Initialising mixnode {id}..."); @@ -112,5 +115,5 @@ pub(crate) fn execute(args: &Init, output: OutputFormat) { eprintln!("Saved configuration file to {config_save_location:?}"); eprintln!("Mixnode configuration completed.\n\n\n"); - MixNode::new(config).print_node_details(output) + MixNode::new(config).print_node_details(args.output) } diff --git a/mixnode/src/commands/mod.rs b/mixnode/src/commands/mod.rs index 09b3e6e8bc..26c663bab0 100644 --- a/mixnode/src/commands/mod.rs +++ b/mixnode/src/commands/mod.rs @@ -62,16 +62,14 @@ struct OverrideConfig { pub(crate) async fn execute(args: Cli) { let bin_name = "nym-mixnode"; - - let output = args.output(); - + match args.command { Commands::Describe(m) => describe::execute(m), - Commands::Init(m) => init::execute(&m, output), - Commands::Run(m) => run::execute(&m, output).await, - Commands::Sign(m) => sign::execute(&m, output), + Commands::Init(m) => init::execute(&m), + Commands::Run(m) => run::execute(&m).await, + Commands::Sign(m) => sign::execute(&m), Commands::Upgrade(m) => upgrade::execute(&m), - Commands::NodeDetails(m) => node_details::execute(&m, output), + Commands::NodeDetails(m) => node_details::execute(&m), Commands::Completions(s) => s.generate(&mut crate::Cli::command(), bin_name), Commands::GenerateFigSpec => fig_generate(&mut crate::Cli::command(), bin_name), } diff --git a/mixnode/src/commands/node_details.rs b/mixnode/src/commands/node_details.rs index 9f1d0745a7..a4b185206c 100644 --- a/mixnode/src/commands/node_details.rs +++ b/mixnode/src/commands/node_details.rs @@ -3,8 +3,8 @@ use crate::config::Config; use crate::node::MixNode; -use crate::OutputFormat; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; #[derive(Args)] @@ -12,9 +12,12 @@ pub(crate) struct NodeDetails { /// The id of the mixnode you want to show details for #[clap(long)] id: String, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } -pub(crate) fn execute(args: &NodeDetails, output: OutputFormat) { +pub(crate) fn execute(args: &NodeDetails) { let config = match Config::load_from_file(&args.id) { Ok(cfg) => cfg, Err(err) => { @@ -27,5 +30,5 @@ pub(crate) fn execute(args: &NodeDetails, output: OutputFormat) { } }; - MixNode::new(config).print_node_details(output) + MixNode::new(config).print_node_details(args.output) } diff --git a/mixnode/src/commands/run.rs b/mixnode/src/commands/run.rs index 6c2509d6a7..b0595d38d8 100644 --- a/mixnode/src/commands/run.rs +++ b/mixnode/src/commands/run.rs @@ -5,10 +5,10 @@ use super::OverrideConfig; use crate::commands::{override_config, version_check}; use crate::config::Config; use crate::node::MixNode; -use crate::OutputFormat; use clap::Args; use nym_config::NymConfig; use std::net::IpAddr; +use nym_bin_common::output_format::OutputFormat; use validator_client::nyxd; #[derive(Args, Clone)] @@ -45,6 +45,9 @@ pub(crate) struct Run { // the alias here is included for backwards compatibility (1.1.4 and before) #[clap(long, alias = "validators", value_delimiter = ',')] nym_apis: Option>, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -63,20 +66,20 @@ impl From for OverrideConfig { } fn show_binding_warning(address: &str) { - println!("\n##### NOTE #####"); - println!( + eprintln!("\n##### NOTE #####"); + eprintln!( "\nYou are trying to bind to {address} - you might not be accessible to other nodes\n\ You can ignore this note if you're running setup on a local network \n\ or have set a custom 'announce-host'" ); - println!("\n\n"); + eprintln!("\n\n"); } fn special_addresses() -> Vec<&'static str> { vec!["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"] } -pub(crate) async fn execute(args: &Run, output: OutputFormat) { +pub(crate) async fn execute(args: &Run) { eprintln!("Starting mixnode {}...", args.id); let mut config = match Config::load_from_file(&args.id) { @@ -107,7 +110,7 @@ pub(crate) async fn execute(args: &Run, output: OutputFormat) { eprintln!( "\nTo bond your mixnode 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 "); - mixnode.print_node_details(output); + mixnode.print_node_details(args.output); mixnode.run().await } diff --git a/mixnode/src/commands/sign.rs b/mixnode/src/commands/sign.rs index 6abbf8a884..706defb8df 100644 --- a/mixnode/src/commands/sign.rs +++ b/mixnode/src/commands/sign.rs @@ -6,10 +6,10 @@ use std::convert::TryFrom; use crate::commands::validate_bech32_address_or_exit; use crate::config::{persistence::pathfinder::MixNodePathfinder, Config}; use crate::node::MixNode; -use crate::OutputFormat; use anyhow::{bail, Result}; use clap::{ArgGroup, Args}; use log::error; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use nym_crypto::asymmetric::identity; use nym_types::helpers::ConsoleSigningOutput; @@ -36,6 +36,9 @@ pub(crate) 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, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } enum SignedTarget { @@ -79,12 +82,7 @@ fn print_signed_text(private_key: &identity::PrivateKey, text: &str, output: Out 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)); } fn print_signed_contract_msg( @@ -114,15 +112,10 @@ 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(crate) fn execute(args: &Sign, output: OutputFormat) { +pub(crate) fn execute(args: &Sign) { let config = match Config::load_from_file(&args.id) { Ok(cfg) => cfg, Err(err) => { @@ -151,13 +144,13 @@ pub(crate) fn execute(args: &Sign, output: OutputFormat) { match signed_target { SignedTarget::Text(text) => { - print_signed_text(identity_keypair.private_key(), &text, output) + print_signed_text(identity_keypair.private_key(), &text, args.output) } SignedTarget::Address(addr) => { - print_signed_address(identity_keypair.private_key(), addr, output) + print_signed_address(identity_keypair.private_key(), addr, args.output) } SignedTarget::ContractMsg(raw_msg) => { - print_signed_contract_msg(identity_keypair.private_key(), &raw_msg, output) + print_signed_contract_msg(identity_keypair.private_key(), &raw_msg, args.output) } } } diff --git a/mixnode/src/main.rs b/mixnode/src/main.rs index 277f4b8f66..e041c9ad08 100644 --- a/mixnode/src/main.rs +++ b/mixnode/src/main.rs @@ -5,7 +5,7 @@ extern crate rocket; use ::nym_config::defaults::setup_env; -use clap::{crate_name, crate_version, Parser, ValueEnum}; +use clap::{crate_name, crate_version, Parser}; use lazy_static::lazy_static; use nym_bin_common::logging::setup_logging; use nym_bin_common::{build_information::BinaryBuildInformation, logging::banner}; @@ -31,23 +31,10 @@ struct Cli { #[clap(short, long)] pub(crate) config_env_file: Option, - #[clap(short, long)] - pub(crate) output: Option, - #[clap(subcommand)] command: commands::Commands, } -impl Cli { - fn output(&self) -> OutputFormat { - if let Some(ref output) = self.output { - output.clone() - } else { - OutputFormat::default() - } - } -} - #[cfg(feature = "cpu-cycles")] pub fn cpu_cycles() { info!("{}", cpu_cycles::cpucycles()) diff --git a/mixnode/src/node/mod.rs b/mixnode/src/node/mod.rs index b38fe40228..28716f120c 100644 --- a/mixnode/src/node/mod.rs +++ b/mixnode/src/node/mod.rs @@ -16,9 +16,9 @@ use crate::node::listener::Listener; use crate::node::node_description::NodeDescription; use crate::node::node_statistics::SharedNodeStats; use crate::node::packet_delayforwarder::{DelayForwarder, PacketDelayForwardSender}; -use crate::OutputFormat; use log::{error, info, warn}; use mixnode_common::verloc::{self, AtomicVerlocResult, VerlocMeasurer}; +use nym_bin_common::output_format::OutputFormat; use nym_bin_common::version_checker::parse_version; use nym_config::NymConfig; use nym_crypto::asymmetric::{encryption, identity}; @@ -96,14 +96,7 @@ impl MixNode { wallet_address: self.config.get_wallet_address().map(|x| x.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}"), - } + println!("{}", output.format(&node_details)); } fn start_http_api( From b026e9107f875c3b6ae61b1bfa00ca4bd4bdfee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 15:51:49 +0100 Subject: [PATCH 3/9] standarised output-json in client init --- clients/native/Cargo.toml | 3 +- clients/native/src/commands/init.rs | 31 ++++++++--------- clients/socks5/Cargo.toml | 2 +- clients/socks5/src/commands/init.rs | 34 +++++++++---------- .../network-requester/Cargo.toml | 2 +- .../network-requester/src/cli/init.rs | 28 +++++++-------- 6 files changed, 45 insertions(+), 55 deletions(-) diff --git a/clients/native/Cargo.toml b/clients/native/Cargo.toml index 9a92353283..1adefd9679 100644 --- a/clients/native/Cargo.toml +++ b/clients/native/Cargo.toml @@ -34,7 +34,7 @@ tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } tokio-tungstenite = "0.14" # websocket ## internal -nym-bin-common = { path = "../../common/bin-common" } +nym-bin-common = { path = "../../common/bin-common", features = ["serde_json"] } client-core = { path = "../../common/client-core", features = ["fs-surb-storage"] } nym-coconut-interface = { path = "../../common/coconut-interface" } nym-config = { path = "../../common/config" } @@ -52,4 +52,3 @@ validator-client = { path = "../../common/client-libs/validator-client", feature websocket-requests = { path = "websocket-requests" } [dev-dependencies] -serde_json = { workspace = true } # for the "textsend" example diff --git a/clients/native/src/commands/init.rs b/clients/native/src/commands/init.rs index 95ba859f80..606de14c78 100644 --- a/clients/native/src/commands/init.rs +++ b/clients/native/src/commands/init.rs @@ -8,6 +8,7 @@ use crate::{ error::ClientError, }; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use nym_crypto::asymmetric::identity; use nym_sphinx::addressing::clients::Recipient; @@ -71,9 +72,8 @@ pub(crate) struct Init { #[clap(long, hide = true)] enabled_credentials_mode: Option, - /// Save a summary of the initialization to a json file - #[clap(long)] - output_json: bool, + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -97,6 +97,7 @@ pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, client_listening_port: String, + client_address: Recipient, } impl InitResults { @@ -104,6 +105,7 @@ impl InitResults { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), client_listening_port: config.get_listening_port().to_string(), + client_address: *address, } } } @@ -111,12 +113,13 @@ impl InitResults { impl Display for InitResults { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "{}", self.client_core)?; - write!(f, "Client listening port: {}", self.client_listening_port) + writeln!(f, "Client listening port: {}", self.client_listening_port)?; + write!(f, "address of this client: {}", self.client_address) } } pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> { - println!("Initialising client..."); + eprintln!("Initialising client..."); let id = &args.id; @@ -125,14 +128,14 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> { // in case we're using old config, try to upgrade it // (if we're using the current version, it's a no-op) try_upgrade_v1_1_13_config(id)?; - println!("Client \"{id}\" was already initialised before"); + eprintln!("Client \"{id}\" was already initialised before"); } // Usually you only register with the gateway on the first init, however you can force // re-registering if wanted. let user_wants_force_register = args.force_register_gateway; if user_wants_force_register { - println!("Instructed to force registering gateway. This might overwrite keys!"); + eprintln!("Instructed to force registering gateway. This might overwrite keys!"); } // If the client was already initialized, don't generate new keys and don't re-register with @@ -167,26 +170,20 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> { let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?; let init_results = InitResults::new(&config, &address); - println!("{init_results}"); + println!("{}", args.output.format(&init_results)); - // Output summary to a json file, if specified - if args.output_json { - client_core::init::output_to_json(&init_results, "client_init_results.json"); - } - - println!("\nThe address of this client is: {address}\n"); Ok(()) } fn print_saved_config(config: &Config) { let config_save_location = config.get_config_file_save_location(); - println!("Saved configuration file to {config_save_location:?}"); - println!("Using gateway: {}", config.get_base().get_gateway_id()); + eprintln!("Saved configuration file to {config_save_location:?}"); + eprintln!("Using gateway: {}", config.get_base().get_gateway_id()); log::debug!("Gateway id: {}", config.get_base().get_gateway_id()); log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner()); log::debug!( "Gateway listener: {}", config.get_base().get_gateway_listener() ); - println!("Client configuration completed.\n"); + eprintln!("Client configuration completed.\n"); } diff --git a/clients/socks5/Cargo.toml b/clients/socks5/Cargo.toml index 2865a75ac7..b350b5cae9 100644 --- a/clients/socks5/Cargo.toml +++ b/clients/socks5/Cargo.toml @@ -19,7 +19,7 @@ tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } url = "2.2" # internal -nym-bin-common = { path = "../../common/bin-common" } +nym-bin-common = { path = "../../common/bin-common", features = ["serde_json"] } client-core = { path = "../../common/client-core", features = ["fs-surb-storage"] } nym-coconut-interface = { path = "../../common/coconut-interface" } nym-config = { path = "../../common/config" } diff --git a/clients/socks5/src/commands/init.rs b/clients/socks5/src/commands/init.rs index e3e50ec389..4e10b603a9 100644 --- a/clients/socks5/src/commands/init.rs +++ b/clients/socks5/src/commands/init.rs @@ -1,4 +1,4 @@ -// Copyright 2021 - Nym Technologies SA +// Copyright 2021-2023 - Nym Technologies SA // SPDX-License-Identifier: Apache-2.0 use crate::commands::try_upgrade_v1_1_13_config; @@ -7,6 +7,7 @@ use crate::{ error::Socks5ClientError, }; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use nym_crypto::asymmetric::identity; use nym_socks5_client_core::config::Config; @@ -75,9 +76,8 @@ pub(crate) struct Init { #[clap(long, hide = true)] enabled_credentials_mode: Option, - /// Save a summary of the initialization to a json file - #[clap(long)] - output_json: bool, + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -99,6 +99,7 @@ pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, socks5_listening_port: String, + client_address: Recipient, } impl InitResults { @@ -106,6 +107,7 @@ impl InitResults { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), socks5_listening_port: config.get_socks5().get_listening_port().to_string(), + client_address: *address, } } } @@ -113,12 +115,13 @@ impl InitResults { impl Display for InitResults { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "{}", self.client_core)?; - write!(f, "SOCKS5 listening port: {}", self.socks5_listening_port) + write!(f, "SOCKS5 listening port: {}", self.socks5_listening_port)?; + write!(f, "address of this client: {}", self.client_address) } } pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> { - println!("Initialising client..."); + eprintln!("Initialising client..."); let id = &args.id; let provider_address = &args.provider; @@ -128,14 +131,14 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> { // in case we're using old config, try to upgrade it // (if we're using the current version, it's a no-op) try_upgrade_v1_1_13_config(id)?; - println!("SOCKS5 client \"{id}\" was already initialised before"); + eprintln!("SOCKS5 client \"{id}\" was already initialised before"); } // Usually you only register with the gateway on the first init, however you can force // re-registering if wanted. let user_wants_force_register = args.force_register_gateway; if user_wants_force_register { - println!("Instructed to force registering gateway. This might overwrite keys!"); + eprintln!("Instructed to force registering gateway. This might overwrite keys!"); } // If the client was already initialized, don't generate new keys and don't re-register with @@ -175,26 +178,21 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> { let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?; let init_results = InitResults::new(&config, &address); - println!("{}", init_results); + println!("{}", args.output.format(&init_results)); - // Output summary to a json file, if specified - if args.output_json { - client_core::init::output_to_json(&init_results, "socks5_client_init_results.json"); - } - - println!("\nThe address of this client is: {}\n", address); + eprintln!("\nThe address of this client is: {}\n", address); Ok(()) } fn print_saved_config(config: &Config) { let config_save_location = config.get_config_file_save_location(); - println!("Saved configuration file to {:?}", config_save_location); - println!("Using gateway: {}", config.get_base().get_gateway_id()); + eprintln!("Saved configuration file to {:?}", config_save_location); + eprintln!("Using gateway: {}", config.get_base().get_gateway_id()); log::debug!("Gateway id: {}", config.get_base().get_gateway_id()); log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner()); log::debug!( "Gateway listener: {}", config.get_base().get_gateway_listener() ); - println!("Client configuration completed.\n"); + eprintln!("Client configuration completed.\n"); } diff --git a/service-providers/network-requester/Cargo.toml b/service-providers/network-requester/Cargo.toml index fe39370b8e..af2f8cecb9 100644 --- a/service-providers/network-requester/Cargo.toml +++ b/service-providers/network-requester/Cargo.toml @@ -34,7 +34,7 @@ url = { workspace = true } client-core = { path = "../../common/client-core" } 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"] } nym-network-defaults = { path = "../../common/network-defaults" } nym-sdk = { path = "../../sdk/rust/nym-sdk" } nym-sphinx = { path = "../../common/nymsphinx" } diff --git a/service-providers/network-requester/src/cli/init.rs b/service-providers/network-requester/src/cli/init.rs index ef9320b9a2..3861027f7e 100644 --- a/service-providers/network-requester/src/cli/init.rs +++ b/service-providers/network-requester/src/cli/init.rs @@ -8,6 +8,7 @@ use crate::{ error::NetworkRequesterError, }; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use nym_crypto::asymmetric::identity; use nym_sphinx::addressing::clients::Recipient; @@ -49,9 +50,8 @@ pub(crate) struct Init { #[clap(long)] enabled_credentials_mode: Option, - /// Save a summary of the initialization to a json file - #[clap(long)] - output_json: bool, + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } impl From for OverrideConfig { @@ -71,12 +71,14 @@ impl From for OverrideConfig { pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, + client_address: Recipient, } impl InitResults { fn new(config: &Config, address: &Recipient) -> Self { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), + client_address: *address, } } } @@ -88,7 +90,7 @@ impl Display for InitResults { } pub(crate) async fn execute(args: &Init) -> Result<(), NetworkRequesterError> { - println!("Initialising client..."); + eprintln!("Initialising client..."); let id = &args.id; @@ -97,14 +99,14 @@ pub(crate) async fn execute(args: &Init) -> Result<(), NetworkRequesterError> { // in case we're using old config, try to upgrade it // (if we're using the current version, it's a no-op) try_upgrade_v1_1_13_config(id)?; - println!("Client \"{id}\" was already initialised before"); + eprintln!("Client \"{id}\" was already initialised before"); } // Usually you only register with the gateway on the first init, however you can force // re-registering if wanted. let user_wants_force_register = args.force_register_gateway; if user_wants_force_register { - println!("Instructed to force registering gateway. This might overwrite keys!"); + eprintln!("Instructed to force registering gateway. This might overwrite keys!"); } // If the client was already initialized, don't generate new keys and don't re-register with @@ -142,26 +144,20 @@ pub(crate) async fn execute(args: &Init) -> Result<(), NetworkRequesterError> { let address = client_core::init::get_client_address_from_stored_keys(config.get_base())?; let init_results = InitResults::new(&config, &address); - println!("{init_results}"); + println!("{}", args.output.format(&init_results)); - // Output summary to a json file, if specified - if args.output_json { - client_core::init::output_to_json(&init_results, "client_init_results.json"); - } - - println!("\nThe address of this client is: {address}\n"); Ok(()) } fn print_saved_config(config: &Config) { let config_save_location = config.get_config_file_save_location(); - println!("Saved configuration file to {config_save_location:?}"); - println!("Using gateway: {}", config.get_base().get_gateway_id()); + eprintln!("Saved configuration file to {config_save_location:?}"); + eprintln!("Using gateway: {}", config.get_base().get_gateway_id()); log::debug!("Gateway id: {}", config.get_base().get_gateway_id()); log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner()); log::debug!( "Gateway listener: {}", config.get_base().get_gateway_listener() ); - println!("Client configuration completed.\n"); + eprintln!("Client configuration completed.\n"); } From ac9290de2735f2de7257f7a734b43bf4250cff4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 15:56:58 +0100 Subject: [PATCH 4/9] clippy --- gateway/src/commands/init.rs | 5 +++-- gateway/src/commands/node_details.rs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/gateway/src/commands/init.rs b/gateway/src/commands/init.rs index 1a51e912e0..9e55c47b62 100644 --- a/gateway/src/commands/init.rs +++ b/gateway/src/commands/init.rs @@ -157,9 +157,10 @@ pub async fn execute(args: Init) -> Result<(), Box> { eprintln!("Saved configuration file to {:?}", config_save_location); eprintln!("Gateway configuration completed.\n\n\n"); - Ok(crate::node::create_gateway(config) + crate::node::create_gateway(config) .await - .print_node_details(args.output)) + .print_node_details(args.output); + Ok(()) } #[cfg(test)] diff --git a/gateway/src/commands/node_details.rs b/gateway/src/commands/node_details.rs index 36f682bd10..11c855ace5 100644 --- a/gateway/src/commands/node_details.rs +++ b/gateway/src/commands/node_details.rs @@ -20,7 +20,8 @@ pub struct NodeDetails { pub async fn execute(args: NodeDetails) -> Result<(), Box> { let config = build_config(args.id.clone(), OverrideConfig::default())?; - Ok(crate::node::create_gateway(config) + crate::node::create_gateway(config) .await - .print_node_details(args.output)) + .print_node_details(args.output); + Ok(()) } From 696f6c399cb53a2b588d3c0edface6d52421ea3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 16:07:22 +0100 Subject: [PATCH 5/9] feature cleanup + added the capability to few nym-cli commands --- Cargo.lock | 1 + clients/native/Cargo.toml | 2 +- clients/socks5/Cargo.toml | 2 +- common/bin-common/Cargo.toml | 1 + common/bin-common/src/output_format/mod.rs | 5 ++-- common/commands/Cargo.toml | 1 + common/commands/src/utils.rs | 23 ++++++++++++++++++- .../create_family_join_permit_sign_payload.rs | 9 ++++++-- .../mixnode/mixnode_bonding_sign_payload.rs | 9 ++++++-- gateway/Cargo.toml | 2 +- mixnode/Cargo.toml | 2 +- mixnode/src/commands/mod.rs | 2 +- mixnode/src/commands/run.rs | 2 +- .../network-requester/Cargo.toml | 2 +- 14 files changed, 48 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b95bb44ab..8502cbea2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3216,6 +3216,7 @@ dependencies = [ "humantime-serde", "k256", "log", + "nym-bin-common", "nym-coconut-bandwidth-contract-common", "nym-coconut-dkg-common", "nym-contracts-common", diff --git a/clients/native/Cargo.toml b/clients/native/Cargo.toml index 1adefd9679..36061ee954 100644 --- a/clients/native/Cargo.toml +++ b/clients/native/Cargo.toml @@ -34,7 +34,7 @@ tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } tokio-tungstenite = "0.14" # websocket ## internal -nym-bin-common = { path = "../../common/bin-common", features = ["serde_json"] } +nym-bin-common = { path = "../../common/bin-common", features = ["output_format"] } client-core = { path = "../../common/client-core", features = ["fs-surb-storage"] } nym-coconut-interface = { path = "../../common/coconut-interface" } nym-config = { path = "../../common/config" } diff --git a/clients/socks5/Cargo.toml b/clients/socks5/Cargo.toml index b350b5cae9..66d8a99aeb 100644 --- a/clients/socks5/Cargo.toml +++ b/clients/socks5/Cargo.toml @@ -19,7 +19,7 @@ tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } url = "2.2" # internal -nym-bin-common = { path = "../../common/bin-common", features = ["serde_json"] } +nym-bin-common = { path = "../../common/bin-common", features = ["output_format"] } client-core = { path = "../../common/client-core", features = ["fs-surb-storage"] } nym-coconut-interface = { path = "../../common/coconut-interface" } nym-config = { path = "../../common/config" } diff --git a/common/bin-common/Cargo.toml b/common/bin-common/Cargo.toml index 6c0750e3c6..40867d90d6 100644 --- a/common/bin-common/Cargo.toml +++ b/common/bin-common/Cargo.toml @@ -22,3 +22,4 @@ vergen = { version = "=7.4.3", default-features = false, features = ["build", "g [features] default = [] +output_format = ["serde", "serde_json"] diff --git a/common/bin-common/src/output_format/mod.rs b/common/bin-common/src/output_format/mod.rs index dfde754237..386cc267a1 100644 --- a/common/bin-common/src/output_format/mod.rs +++ b/common/bin-common/src/output_format/mod.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 use clap::ValueEnum; -use serde::Serialize; use std::fmt::{Display, Formatter}; #[derive(Default, Copy, Debug, Clone, ValueEnum)] @@ -26,8 +25,8 @@ impl OutputFormat { matches!(self, OutputFormat::Text) } - #[cfg(feature = "serde_json")] - pub fn format(&self, data: &T) -> String { + #[cfg(feature = "output_format")] + pub fn format(&self, data: &T) -> String { match self { OutputFormat::Text => data.to_string(), OutputFormat::Json => serde_json::to_string(data).unwrap(), diff --git a/common/commands/Cargo.toml b/common/commands/Cargo.toml index d4cdfbe91d..9bddc24e50 100644 --- a/common/commands/Cargo.toml +++ b/common/commands/Cargo.toml @@ -29,6 +29,7 @@ cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegr cosmwasm-std = { workspace = true } validator-client = { path = "../client-libs/validator-client", features = ["nyxd-client"] } +nym-bin-common = { path = "../../common/bin-common", features = ["output_format"] } nym-crypto = { path = "../../common/crypto", features = ["asymmetric"] } nym-network-defaults = { path = "../network-defaults" } nym-contracts-common = { path = "../cosmwasm-smart-contracts/contracts-common" } diff --git a/common/commands/src/utils.rs b/common/commands/src/utils.rs index 05c395924d..a3db404198 100644 --- a/common/commands/src/utils.rs +++ b/common/commands/src/utils.rs @@ -4,8 +4,9 @@ use cosmrs::AccountId; use cosmwasm_std::{Addr, Coin as CosmWasmCoin, Decimal}; use log::error; +use serde::Serialize; use std::error::Error; -use std::fmt::Display; +use std::fmt::{Display, Formatter}; use validator_client::nyxd::Coin; // TODO: perhaps it should be moved to some global common crate? @@ -54,3 +55,23 @@ where error!("{}", e); e } + +#[derive(Serialize)] +pub(crate) struct DataWrapper { + data: T, +} + +impl Display for DataWrapper +where + T: Display, +{ + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.data) + } +} + +impl DataWrapper { + pub(crate) fn new(data: T) -> Self { + DataWrapper { data } + } +} diff --git a/common/commands/src/validator/mixnet/operators/mixnode/families/create_family_join_permit_sign_payload.rs b/common/commands/src/validator/mixnet/operators/mixnode/families/create_family_join_permit_sign_payload.rs index 2654a337e4..2e80ded330 100644 --- a/common/commands/src/validator/mixnet/operators/mixnode/families/create_family_join_permit_sign_payload.rs +++ b/common/commands/src/validator/mixnet/operators/mixnode/families/create_family_join_permit_sign_payload.rs @@ -2,10 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 use crate::context::QueryClient; -use crate::utils::account_id_to_cw_addr; +use crate::utils::{account_id_to_cw_addr, DataWrapper}; use clap::Parser; use cosmrs::AccountId; use log::info; +use nym_bin_common::output_format::OutputFormat; use nym_crypto::asymmetric::identity; use nym_mixnet_contract_common::construct_family_join_permit; use nym_mixnet_contract_common::families::FamilyHead; @@ -25,6 +26,9 @@ pub struct Args { /// Identity of the member for whom we're issuing the permit #[arg(long)] pub member: identity::PublicKey, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } pub async fn create_family_join_permit_sign_payload(args: Args, client: QueryClient) { @@ -68,5 +72,6 @@ pub async fn create_family_join_permit_sign_payload(args: Args, client: QueryCli let head = FamilyHead::new(mixnode.bond_information.identity()); let payload = construct_family_join_permit(nonce, head, proxy, args.member.to_base58_string()); - println!("{}", payload.to_base58_string().unwrap()) + let wrapper = DataWrapper::new(payload.to_base58_string().unwrap()); + println!("{}", args.output.format(&wrapper)) } diff --git a/common/commands/src/validator/mixnet/operators/mixnode/mixnode_bonding_sign_payload.rs b/common/commands/src/validator/mixnet/operators/mixnode/mixnode_bonding_sign_payload.rs index a4b41b03f2..c674b942f6 100644 --- a/common/commands/src/validator/mixnet/operators/mixnode/mixnode_bonding_sign_payload.rs +++ b/common/commands/src/validator/mixnet/operators/mixnode/mixnode_bonding_sign_payload.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 use crate::context::SigningClient; -use crate::utils::account_id_to_cw_addr; +use crate::utils::{account_id_to_cw_addr, DataWrapper}; use clap::Parser; use cosmwasm_std::{Coin, Uint128}; +use nym_bin_common::output_format::OutputFormat; use nym_contracts_common::Percent; use nym_mixnet_contract_common::{construct_mixnode_bonding_sign_payload, MixNodeCostParams}; use nym_network_defaults::{ @@ -54,6 +55,9 @@ pub struct Args { /// Indicates whether the mixnode is going to get bonded via a vesting account #[arg(long)] pub with_vesting_account: bool, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } pub async fn create_payload(args: Args, client: SigningClient) { @@ -104,5 +108,6 @@ pub async fn create_payload(args: Args, client: SigningClient) { let payload = construct_mixnode_bonding_sign_payload(nonce, address, proxy, coin, mixnode, cost_params); - println!("{}", payload.to_base58_string().unwrap()) + let wrapper = DataWrapper::new(payload.to_base58_string().unwrap()); + println!("{}", args.output.format(&wrapper)) } diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index 317a5e1f81..6e803e461f 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -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", features = ["serde_json"] } +nym-bin-common = { path = "../common/bin-common", features = ["output_format"] } gateway-requests = { path = "gateway-requests" } mixnet-client = { path = "../common/client-libs/mixnet-client" } mixnode-common = { path = "../common/mixnode-common" } diff --git a/mixnode/Cargo.toml b/mixnode/Cargo.toml index fce6af86e9..5bfce1a43b 100644 --- a/mixnode/Cargo.toml +++ b/mixnode/Cargo.toml @@ -51,7 +51,7 @@ nym-task = { path = "../common/task" } nym-types = { path = "../common/types" } nym-topology = { path = "../common/topology" } validator-client = { path = "../common/client-libs/validator-client" } -nym-bin-common = { path = "../common/bin-common", features = ["serde_json"] } +nym-bin-common = { path = "../common/bin-common", features = ["output_format"] } cpu-cycles = { path = "../cpu-cycles", optional = true } [dev-dependencies] diff --git a/mixnode/src/commands/mod.rs b/mixnode/src/commands/mod.rs index 26c663bab0..6172776c72 100644 --- a/mixnode/src/commands/mod.rs +++ b/mixnode/src/commands/mod.rs @@ -62,7 +62,7 @@ struct OverrideConfig { pub(crate) async fn execute(args: Cli) { let bin_name = "nym-mixnode"; - + match args.command { Commands::Describe(m) => describe::execute(m), Commands::Init(m) => init::execute(&m), diff --git a/mixnode/src/commands/run.rs b/mixnode/src/commands/run.rs index b0595d38d8..c8d40721d9 100644 --- a/mixnode/src/commands/run.rs +++ b/mixnode/src/commands/run.rs @@ -6,9 +6,9 @@ use crate::commands::{override_config, version_check}; use crate::config::Config; use crate::node::MixNode; use clap::Args; +use nym_bin_common::output_format::OutputFormat; use nym_config::NymConfig; use std::net::IpAddr; -use nym_bin_common::output_format::OutputFormat; use validator_client::nyxd; #[derive(Args, Clone)] diff --git a/service-providers/network-requester/Cargo.toml b/service-providers/network-requester/Cargo.toml index af2f8cecb9..9283495517 100644 --- a/service-providers/network-requester/Cargo.toml +++ b/service-providers/network-requester/Cargo.toml @@ -34,7 +34,7 @@ url = { workspace = true } client-core = { path = "../../common/client-core" } nym-config = { path = "../../common/config" } nym-crypto = { path = "../../common/crypto" } -nym-bin-common = { path = "../../common/bin-common", features = ["serde_json"] } +nym-bin-common = { path = "../../common/bin-common", features = ["output_format"] } nym-network-defaults = { path = "../../common/network-defaults" } nym-sdk = { path = "../../sdk/rust/nym-sdk" } nym-sphinx = { path = "../../common/nymsphinx" } From 4a837ce28c1f5ea715335ce2d2cbab9f7714abbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 30 Mar 2023 16:17:13 +0100 Subject: [PATCH 6/9] added output argument for generating gateway sign payload --- .../operators/gateway/gateway_bonding_sign_payload.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/common/commands/src/validator/mixnet/operators/gateway/gateway_bonding_sign_payload.rs b/common/commands/src/validator/mixnet/operators/gateway/gateway_bonding_sign_payload.rs index 470c25bb98..5b1372234b 100644 --- a/common/commands/src/validator/mixnet/operators/gateway/gateway_bonding_sign_payload.rs +++ b/common/commands/src/validator/mixnet/operators/gateway/gateway_bonding_sign_payload.rs @@ -2,9 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 use crate::context::SigningClient; -use crate::utils::account_id_to_cw_addr; +use crate::utils::{account_id_to_cw_addr, DataWrapper}; use clap::Parser; use cosmwasm_std::Coin; +use nym_bin_common::output_format::OutputFormat; use nym_mixnet_contract_common::construct_gateway_bonding_sign_payload; use nym_network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT}; use validator_client::nyxd::traits::MixnetQueryClient; @@ -41,6 +42,9 @@ pub struct Args { /// Indicates whether the gateway is going to get bonded via a vesting account #[arg(long)] pub with_vesting_account: bool, + + #[clap(short, long, default_value_t = OutputFormat::default())] + output: OutputFormat, } pub async fn create_payload(args: Args, client: SigningClient) { @@ -77,5 +81,6 @@ pub async fn create_payload(args: Args, client: SigningClient) { }; let payload = construct_gateway_bonding_sign_payload(nonce, address, proxy, coin, gateway); - println!("{}", payload.to_base58_string().unwrap()) + let wrapper = DataWrapper::new(payload.to_base58_string().unwrap()); + println!("{}", args.output.format(&wrapper)) } From 3b8dd1f4a5ebb780ac48bcfb0bf66ffb61604f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Tue, 4 Apr 2023 09:50:53 +0100 Subject: [PATCH 7/9] using stderr when registering gateway --- common/client-core/src/init/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/common/client-core/src/init/mod.rs b/common/client-core/src/init/mod.rs index facb54bf73..d418ba13b7 100644 --- a/common/client-core/src/init/mod.rs +++ b/common/client-core/src/init/mod.rs @@ -115,7 +115,7 @@ where // If we are not going to register gateway, and an explicitly chosen gateway is not passed in, // load the existing configuration file if !register_gateway && user_chosen_gateway_id.is_none() { - println!("Not registering gateway, will reuse existing config and keys"); + eprintln!("Not registering gateway, will reuse existing config and keys"); return load_existing_gateway_config::(&id); } @@ -131,7 +131,7 @@ where // If we are not registering, just return this and assume the caller has the keys already and // wants to keep the, if !register_gateway && user_chosen_gateway_id.is_some() { - println!("Using gateway provided by user, keeping existing keys"); + eprintln!("Using gateway provided by user, keeping existing keys"); return Ok(gateway.into()); } @@ -140,7 +140,7 @@ where let our_identity = key_manager.identity_keypair(); // Establish connection, authenticate and generate keys for talking with the gateway - println!("Registering with new gateway"); + eprintln!("Registering with new gateway"); let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?; key_manager.insert_gateway_shared_key(shared_keys); From 01aa06e488c254c44e4d1ad681aa8fdca1d1e0f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Tue, 4 Apr 2023 10:00:29 +0100 Subject: [PATCH 8/9] standarise printing of banner based on tty --- Cargo.lock | 2 +- clients/native/src/main.rs | 4 ++-- clients/socks5/src/main.rs | 4 ++-- common/bin-common/Cargo.toml | 1 + common/bin-common/src/logging/mod.rs | 6 ++++++ gateway/src/main.rs | 8 +++----- mixnode/Cargo.toml | 1 - mixnode/src/main.rs | 8 +++----- nym-wallet/Cargo.lock | 1 + service-providers/network-requester/src/main.rs | 4 ++-- 10 files changed, 21 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8502cbea2d..3e464ccddf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3149,6 +3149,7 @@ dependencies = [ name = "nym-bin-common" version = "0.3.0" dependencies = [ + "atty", "clap 4.1.11", "clap_complete", "clap_complete_fig", @@ -3502,7 +3503,6 @@ name = "nym-mixnode" version = "1.1.14" dependencies = [ "anyhow", - "atty", "bs58", "clap 4.1.11", "colored", diff --git a/clients/native/src/main.rs b/clients/native/src/main.rs index 48965e7c1a..cc862b2a88 100644 --- a/clients/native/src/main.rs +++ b/clients/native/src/main.rs @@ -4,7 +4,7 @@ use std::error::Error; use clap::{crate_name, crate_version, Parser}; -use nym_bin_common::logging::{banner, setup_logging}; +use nym_bin_common::logging::{maybe_print_banner, setup_logging}; use nym_network_defaults::setup_env; pub mod client; @@ -15,7 +15,7 @@ pub mod websocket; #[tokio::main] async fn main() -> Result<(), Box> { setup_logging(); - println!("{}", banner(crate_name!(), crate_version!())); + maybe_print_banner(crate_name!(), crate_version!()); let args = commands::Cli::parse(); setup_env(args.config_env_file.as_ref()); diff --git a/clients/socks5/src/main.rs b/clients/socks5/src/main.rs index 1c3d9b83d7..7125c0c042 100644 --- a/clients/socks5/src/main.rs +++ b/clients/socks5/src/main.rs @@ -4,7 +4,7 @@ use std::error::Error; use clap::{crate_name, crate_version, Parser}; -use nym_bin_common::logging::{banner, setup_logging}; +use nym_bin_common::logging::{maybe_print_banner, setup_logging}; use nym_network_defaults::setup_env; mod commands; @@ -13,7 +13,7 @@ pub mod error; #[tokio::main] async fn main() -> Result<(), Box> { setup_logging(); - println!("{}", banner(crate_name!(), crate_version!())); + maybe_print_banner(crate_name!(), crate_version!()); let args = commands::Cli::parse(); setup_env(args.config_env_file.as_ref()); diff --git a/common/bin-common/Cargo.toml b/common/bin-common/Cargo.toml index 40867d90d6..29fd632897 100644 --- a/common/bin-common/Cargo.toml +++ b/common/bin-common/Cargo.toml @@ -8,6 +8,7 @@ license = { workspace = true } repository = { workspace = true } [dependencies] +atty = "0.2" clap = { version = "4.0", features = ["derive"] } clap_complete = "4.0" clap_complete_fig = "4.0" diff --git a/common/bin-common/src/logging/mod.rs b/common/bin-common/src/logging/mod.rs index 27f7711e80..1562c91e8b 100644 --- a/common/bin-common/src/logging/mod.rs +++ b/common/bin-common/src/logging/mod.rs @@ -39,3 +39,9 @@ pub fn banner(crate_name: &str, crate_version: &str) -> String { "# ) } + +pub fn maybe_print_banner(crate_name: &str, crate_version: &str) { + if atty::is(atty::Stream::Stdout) { + println!("{}", banner(crate_name, crate_version)) + } +} diff --git a/gateway/src/main.rs b/gateway/src/main.rs index b17906d4f0..9ea8eb679d 100644 --- a/gateway/src/main.rs +++ b/gateway/src/main.rs @@ -5,9 +5,9 @@ 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::build_information::BinaryBuildInformation; +use nym_bin_common::logging::{maybe_print_banner, 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; @@ -41,9 +41,7 @@ struct Cli { #[tokio::main] async fn main() -> Result<(), Box> { setup_logging(); - if atty::is(atty::Stream::Stdout) { - println!("{}", banner(crate_name!(), crate_version!())); - } + maybe_print_banner(crate_name!(), crate_version!()); let args = Cli::parse(); setup_env(args.config_env_file.as_ref()); diff --git a/mixnode/Cargo.toml b/mixnode/Cargo.toml index 5bfce1a43b..014f862b87 100644 --- a/mixnode/Cargo.toml +++ b/mixnode/Cargo.toml @@ -36,7 +36,6 @@ tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] } tokio-util = { version = "0.7.3", features = ["codec"] } toml = "0.5.8" url = { version = "2.2", features = ["serde"] } -atty = "0.2" ## internal nym-config = { path = "../common/config" } diff --git a/mixnode/src/main.rs b/mixnode/src/main.rs index e041c9ad08..e9f9f9f59c 100644 --- a/mixnode/src/main.rs +++ b/mixnode/src/main.rs @@ -7,8 +7,8 @@ extern crate rocket; use ::nym_config::defaults::setup_env; use clap::{crate_name, crate_version, Parser}; use lazy_static::lazy_static; -use nym_bin_common::logging::setup_logging; -use nym_bin_common::{build_information::BinaryBuildInformation, logging::banner}; +use nym_bin_common::build_information::BinaryBuildInformation; +use nym_bin_common::logging::{maybe_print_banner, setup_logging}; mod commands; mod config; @@ -43,9 +43,7 @@ pub fn cpu_cycles() { #[tokio::main] async fn main() { setup_logging(); - if atty::is(atty::Stream::Stdout) { - println!("{}", banner(crate_name!(), crate_version!())); - } + maybe_print_banner(crate_name!(), crate_version!()); let args = Cli::parse(); setup_env(args.config_env_file.as_ref()); diff --git a/nym-wallet/Cargo.lock b/nym-wallet/Cargo.lock index 5b007fc6ff..bcd757d57a 100644 --- a/nym-wallet/Cargo.lock +++ b/nym-wallet/Cargo.lock @@ -2783,6 +2783,7 @@ dependencies = [ name = "nym-bin-common" version = "0.3.0" dependencies = [ + "atty", "clap", "clap_complete", "clap_complete_fig", diff --git a/service-providers/network-requester/src/main.rs b/service-providers/network-requester/src/main.rs index 0629525185..696cb41c21 100644 --- a/service-providers/network-requester/src/main.rs +++ b/service-providers/network-requester/src/main.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use clap::{crate_name, crate_version, Parser}; -use nym_bin_common::logging::{banner, setup_logging}; +use nym_bin_common::logging::{maybe_print_banner, setup_logging}; use nym_network_defaults::setup_env; use error::NetworkRequesterError; @@ -19,7 +19,7 @@ mod statistics; #[tokio::main] async fn main() -> Result<(), NetworkRequesterError> { setup_logging(); - println!("{}", banner(crate_name!(), crate_version!())); + maybe_print_banner(crate_name!(), crate_version!()); let args = cli::Cli::parse(); setup_env(args.config_env_file.as_ref()); From 0505a4807de963f67e8cf722bcd18546344c28a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Tue, 4 Apr 2023 10:03:08 +0100 Subject: [PATCH 9/9] using string representation of 'Recipient' for 'InitResults' --- clients/native/src/commands/init.rs | 4 ++-- clients/socks5/src/commands/init.rs | 4 ++-- service-providers/network-requester/src/cli/init.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/clients/native/src/commands/init.rs b/clients/native/src/commands/init.rs index 606de14c78..4f064c6bea 100644 --- a/clients/native/src/commands/init.rs +++ b/clients/native/src/commands/init.rs @@ -97,7 +97,7 @@ pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, client_listening_port: String, - client_address: Recipient, + client_address: String, } impl InitResults { @@ -105,7 +105,7 @@ impl InitResults { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), client_listening_port: config.get_listening_port().to_string(), - client_address: *address, + client_address: address.to_string(), } } } diff --git a/clients/socks5/src/commands/init.rs b/clients/socks5/src/commands/init.rs index 4e10b603a9..e2aa1c17ec 100644 --- a/clients/socks5/src/commands/init.rs +++ b/clients/socks5/src/commands/init.rs @@ -99,7 +99,7 @@ pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, socks5_listening_port: String, - client_address: Recipient, + client_address: String, } impl InitResults { @@ -107,7 +107,7 @@ impl InitResults { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), socks5_listening_port: config.get_socks5().get_listening_port().to_string(), - client_address: *address, + client_address: address.to_string(), } } } diff --git a/service-providers/network-requester/src/cli/init.rs b/service-providers/network-requester/src/cli/init.rs index 3861027f7e..13ab40abb7 100644 --- a/service-providers/network-requester/src/cli/init.rs +++ b/service-providers/network-requester/src/cli/init.rs @@ -71,14 +71,14 @@ impl From for OverrideConfig { pub struct InitResults { #[serde(flatten)] client_core: client_core::init::InitResults, - client_address: Recipient, + client_address: String, } impl InitResults { fn new(config: &Config, address: &Recipient) -> Self { Self { client_core: client_core::init::InitResults::new(config.get_base(), address), - client_address: *address, + client_address: address.to_string(), } } }