Merge pull request #3260 from nymtech/feature/standarise-output-json

Feature/standarise output json
This commit is contained in:
Tommy Verrall
2023-04-04 10:29:50 +01:00
committed by GitHub
49 changed files with 260 additions and 257 deletions
Generated
+3 -1
View File
@@ -3149,6 +3149,7 @@ dependencies = [
name = "nym-bin-common"
version = "0.3.0"
dependencies = [
"atty",
"clap 4.1.11",
"clap_complete",
"clap_complete_fig",
@@ -3156,6 +3157,7 @@ dependencies = [
"pretty_env_logger",
"semver 0.11.0",
"serde",
"serde_json",
"vergen",
]
@@ -3215,6 +3217,7 @@ dependencies = [
"humantime-serde",
"k256",
"log",
"nym-bin-common",
"nym-coconut-bandwidth-contract-common",
"nym-coconut-dkg-common",
"nym-contracts-common",
@@ -3500,7 +3503,6 @@ name = "nym-mixnode"
version = "1.1.14"
dependencies = [
"anyhow",
"atty",
"bs58",
"clap 4.1.11",
"colored",
+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 -4
View File
@@ -26,15 +26,15 @@ 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
tokio-tungstenite = "0.14" # websocket
## internal
nym-bin-common = { path = "../../common/bin-common" }
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" }
@@ -52,4 +52,3 @@ validator-client = { path = "../../common/client-libs/validator-client", feature
websocket-requests = { path = "websocket-requests" }
[dev-dependencies]
serde_json = "1.0" # for the "textsend" example
+14 -17
View File
@@ -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<bool>,
/// 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<Init> for OverrideConfig {
@@ -97,6 +97,7 @@ pub struct InitResults {
#[serde(flatten)]
client_core: client_core::init::InitResults,
client_listening_port: String,
client_address: String,
}
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.to_string(),
}
}
}
@@ -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");
}
+2 -2
View File
@@ -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<dyn Error + Send + Sync>> {
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());
+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 -1
View File
@@ -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 = ["output_format"] }
client-core = { path = "../../common/client-core", features = ["fs-surb-storage"] }
nym-coconut-interface = { path = "../../common/coconut-interface" }
nym-config = { path = "../../common/config" }
+16 -18
View File
@@ -1,4 +1,4 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// 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<bool>,
/// 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<Init> for OverrideConfig {
@@ -99,6 +99,7 @@ pub struct InitResults {
#[serde(flatten)]
client_core: client_core::init::InitResults,
socks5_listening_port: String,
client_address: String,
}
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.to_string(),
}
}
}
@@ -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");
}
+2 -2
View File
@@ -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<dyn Error + Send + Sync>> {
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());
+3
View File
@@ -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"
@@ -15,9 +16,11 @@ 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"] }
[features]
default = []
output_format = ["serde", "serde_json"]
+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;
+6
View File
@@ -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))
}
}
@@ -0,0 +1,35 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::ValueEnum;
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 = "output_format")]
pub fn format<T: serde::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"] }
+3 -3
View File
@@ -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::<C>(&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);
+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" }
+2 -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"
@@ -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" }
+22 -1
View File
@@ -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<T> {
data: T,
}
impl<T> Display for DataWrapper<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data)
}
}
impl<T> DataWrapper<T> {
pub(crate) fn new(data: T) -> Self {
DataWrapper { data }
}
}
@@ -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))
}
@@ -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))
}
@@ -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))
}
+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"
-4
View File
@@ -17,10 +17,6 @@ impl ConsoleSigningOutput {
encoded_signature: encoded_signature.into(),
}
}
pub fn to_json_string(&self) -> String {
serde_json::to_string(self).expect("json serialization of 'ConsoleSigningOutput' failed")
}
}
impl Display for ConsoleSigningOutput {
+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 = ["output_format"] }
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" }
+8 -3
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() {
@@ -154,9 +157,10 @@ pub async fn execute(args: Init, output: OutputFormat) -> Result<(), Box<dyn Err
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(output)?)
.print_node_details(args.output);
Ok(())
}
#[cfg(test)]
@@ -183,6 +187,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),
+8 -7
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,16 @@ 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)
crate::node::create_gateway(config)
.await
.print_node_details(output)?)
.print_node_details(args.output);
Ok(())
}
+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);
+6 -32
View File
@@ -1,12 +1,13 @@
// 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::{build_information::BinaryBuildInformation, logging::banner};
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_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,29 +34,14 @@ 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();
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());
+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(
+3 -4
View File
@@ -29,14 +29,13 @@ 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"] }
toml = "0.5.8"
url = { version = "2.2", features = ["serde"] }
atty = "0.2"
## internal
nym-config = { path = "../common/config" }
@@ -51,7 +50,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 = ["output_format"] }
cpu-cycles = { path = "../cpu-cycles", optional = true }
[dev-dependencies]
+6 -3
View File
@@ -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<Vec<url::Url>>,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
impl From<Init> for OverrideConfig {
@@ -63,7 +66,7 @@ impl From<Init> 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)
}
+4 -6
View File
@@ -63,15 +63,13 @@ 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),
}
+6 -3
View File
@@ -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)
}
+9 -6
View File
@@ -5,8 +5,8 @@ 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_bin_common::output_format::OutputFormat;
use nym_config::NymConfig;
use std::net::IpAddr;
use validator_client::nyxd;
@@ -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<Vec<url::Url>>,
#[clap(short, long, default_value_t = OutputFormat::default())]
output: OutputFormat,
}
impl From<Run> for OverrideConfig {
@@ -63,20 +66,20 @@ impl From<Run> 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
}
+10 -17
View File
@@ -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<String>,
#[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)
}
}
}
+4 -31
View File
@@ -5,10 +5,10 @@
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};
use nym_bin_common::build_information::BinaryBuildInformation;
use nym_bin_common::logging::{maybe_print_banner, setup_logging};
mod commands;
mod config;
@@ -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 {
@@ -43,23 +31,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()
}
}
}
#[cfg(feature = "cpu-cycles")]
pub fn cpu_cycles() {
info!("{}", cpu_cycles::cpucycles())
@@ -68,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());
+2 -9
View File
@@ -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(
+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"] }
+1
View File
@@ -2783,6 +2783,7 @@ dependencies = [
name = "nym-bin-common"
version = "0.3.0"
dependencies = [
"atty",
"clap",
"clap_complete",
"clap_complete_fig",
@@ -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"
@@ -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 = ["output_format"] }
nym-network-defaults = { path = "../../common/network-defaults" }
nym-sdk = { path = "../../sdk/rust/nym-sdk" }
nym-sphinx = { path = "../../common/nymsphinx" }
@@ -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<bool>,
/// 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<Init> for OverrideConfig {
@@ -71,12 +71,14 @@ impl From<Init> for OverrideConfig {
pub struct InitResults {
#[serde(flatten)]
client_core: client_core::init::InitResults,
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.to_string(),
}
}
}
@@ -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");
}
@@ -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());
@@ -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" ] }