Renaming validator-api to nym-api (#1863)

* Renaming validator-api to nym-api

* nym-api: simplified crate name

* Added nym-api rename to changelog

* Changed some output messages

* Renamed validator-api-requests to nym-api requests

* Removing more references to validator-api-requests

* Additional lockfile name changes after full build

* Removing mistakenly added merge files

* ibid

* ibid

* Getting rid of ref to validator_api deep inside validator-client

* Fixing file storage paths

* Renaming struct function names referring to validator_api

* Simplifying struct init

* Fixed up all other instances of nym_api.

* Renaming validatorApi to nymApi in TypeScript client for consistency

v

* Found a few more Rust instances

* Changed examples in TypeScript SDK

* Found one more instance of the use of validator instead of nym apis

* Aliasing config key name for deserialization to preserve compatibility with old configs
This commit is contained in:
Dave Hrycyszyn
2022-12-14 15:05:01 +00:00
committed by GitHub
parent 4ece8b7e8f
commit f6a79ce7c3
165 changed files with 600 additions and 640 deletions
Generated
+20 -20
View File
@@ -967,9 +967,9 @@ dependencies = [
"coconut-interface",
"cosmrs",
"crypto",
"nym-api-requests",
"rand 0.7.3",
"thiserror",
"validator-api-requests",
"validator-client",
]
@@ -3091,6 +3091,21 @@ dependencies = [
"libc",
]
[[package]]
name = "nym-api-requests"
version = "0.1.0"
dependencies = [
"bs58",
"coconut-interface",
"cosmrs",
"cosmwasm-std",
"getset",
"mixnet-contract-common",
"schemars",
"serde",
"ts-rs",
]
[[package]]
name = "nym-bity-integration"
version = "0.1.0"
@@ -3225,6 +3240,7 @@ dependencies = [
"mixnet-client",
"mixnode-common",
"network-defaults",
"nym-api-requests",
"nymsphinx",
"once_cell",
"pemstore",
@@ -3240,7 +3256,6 @@ dependencies = [
"tokio-tungstenite 0.14.0",
"tokio-util 0.7.3",
"url",
"validator-api-requests",
"validator-client",
"vergen 5.1.17",
"version-checker",
@@ -3436,6 +3451,7 @@ dependencies = [
"logging",
"mixnet-contract-common",
"multisig-contract-common",
"nym-api-requests",
"nymcoconut",
"nymsphinx",
"okapi",
@@ -3461,7 +3477,6 @@ dependencies = [
"topology",
"ts-rs",
"url",
"validator-api-requests",
"validator-client",
"vergen 7.2.1",
"version-checker",
@@ -6195,10 +6210,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"mixnet-contract-common",
"nym-api-requests",
"nym-types",
"nym-wallet-types",
"ts-rs",
"validator-api-requests",
"validator-client",
"vesting-contract-common",
"walkdir",
@@ -6404,21 +6419,6 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
[[package]]
name = "validator-api-requests"
version = "0.1.0"
dependencies = [
"bs58",
"coconut-interface",
"cosmrs",
"cosmwasm-std",
"getset",
"mixnet-contract-common",
"schemars",
"serde",
"ts-rs",
]
[[package]]
name = "validator-client"
version = "0.1.0"
@@ -6443,6 +6443,7 @@ dependencies = [
"mixnet-contract-common",
"multisig-contract-common",
"network-defaults",
"nym-api-requests",
"prost 0.10.3",
"reqwest",
"serde",
@@ -6452,7 +6453,6 @@ dependencies = [
"tokio",
"ts-rs",
"url",
"validator-api-requests",
"vesting-contract",
"vesting-contract-common",
]
+3 -3
View File
@@ -74,8 +74,8 @@ members = [
"mixnode",
"service-providers/network-requester",
"service-providers/network-statistics",
"validator-api",
"validator-api/validator-api-requests",
"nym-api",
"nym-api/nym-api-requests",
"tools/nym-cli",
"tools/ts-rs-cli"
]
@@ -87,7 +87,7 @@ default-members = [
"service-providers/network-requester",
"service-providers/network-statistics",
"mixnode",
"validator-api",
"nym-api",
"explorer-api",
]
@@ -85,7 +85,7 @@ pub struct BaseClientBuilder<'a, B> {
gateway_config: &'a GatewayEndpointConfig,
debug_config: &'a DebugConfig,
disabled_credentials: bool,
validator_api_endpoints: Vec<Url>,
nym_api_endpoints: Vec<Url>,
reply_storage_backend: B,
bandwidth_controller: Option<BandwidthController>,
@@ -106,7 +106,7 @@ where
gateway_config: base_config.get_gateway_endpoint_config(),
debug_config: base_config.get_debug_config(),
disabled_credentials: base_config.get_disabled_credentials_mode(),
validator_api_endpoints: base_config.get_validator_api_endpoints(),
nym_api_endpoints: base_config.get_nym_api_endpoints(),
bandwidth_controller,
reply_storage_backend,
key_manager,
@@ -120,13 +120,13 @@ where
bandwidth_controller: Option<BandwidthController>,
reply_storage_backend: B,
disabled_credentials: bool,
validator_api_endpoints: Vec<Url>,
nym_api_endpoints: Vec<Url>,
) -> BaseClientBuilder<'a, B> {
BaseClientBuilder {
gateway_config,
debug_config,
disabled_credentials,
validator_api_endpoints,
nym_api_endpoints,
bandwidth_controller,
reply_storage_backend,
key_manager,
@@ -281,13 +281,13 @@ where
// future responsible for periodically polling directory server and updating
// the current global view of topology
async fn start_topology_refresher(
validator_api_urls: Vec<Url>,
nym_api_urls: Vec<Url>,
refresh_rate: Duration,
topology_accessor: TopologyAccessor,
shutdown: ShutdownListener,
) -> Result<(), ClientCoreError<B>> {
let topology_refresher_config = TopologyRefresherConfig::new(
validator_api_urls,
nym_api_urls,
refresh_rate,
env!("CARGO_PKG_VERSION").to_string(),
);
@@ -386,7 +386,7 @@ where
.await?;
Self::start_topology_refresher(
self.validator_api_endpoints.clone(),
self.nym_api_endpoints.clone(),
self.debug_config.topology_refresh_rate,
shared_topology_accessor.clone(),
shutdown.subscribe(),
@@ -136,19 +136,15 @@ impl Default for TopologyAccessor {
}
pub struct TopologyRefresherConfig {
validator_api_urls: Vec<Url>,
nym_api_urls: Vec<Url>,
refresh_rate: Duration,
client_version: String,
}
impl TopologyRefresherConfig {
pub fn new(
validator_api_urls: Vec<Url>,
refresh_rate: Duration,
client_version: String,
) -> Self {
pub fn new(nym_api_urls: Vec<Url>, refresh_rate: Duration, client_version: String) -> Self {
TopologyRefresherConfig {
validator_api_urls,
nym_api_urls,
refresh_rate,
client_version,
}
@@ -159,7 +155,7 @@ pub struct TopologyRefresher {
validator_client: validator_client::client::ApiClient,
client_version: String,
validator_api_urls: Vec<Url>,
nym_api_urls: Vec<Url>,
topology_accessor: TopologyAccessor,
refresh_rate: Duration,
@@ -169,14 +165,12 @@ pub struct TopologyRefresher {
impl TopologyRefresher {
pub fn new(mut cfg: TopologyRefresherConfig, topology_accessor: TopologyAccessor) -> Self {
cfg.validator_api_urls.shuffle(&mut thread_rng());
cfg.nym_api_urls.shuffle(&mut thread_rng());
TopologyRefresher {
validator_client: validator_client::client::ApiClient::new(
cfg.validator_api_urls[0].clone(),
),
validator_client: validator_client::client::ApiClient::new(cfg.nym_api_urls[0].clone()),
client_version: cfg.client_version,
validator_api_urls: cfg.validator_api_urls,
nym_api_urls: cfg.nym_api_urls,
topology_accessor,
refresh_rate: cfg.refresh_rate,
currently_used_api: 0,
@@ -184,15 +178,15 @@ impl TopologyRefresher {
}
}
fn use_next_validator_api(&mut self) {
if self.validator_api_urls.len() == 1 {
warn!("There's only a single validator API available - it won't be possible to use a different one");
fn use_next_nym_api(&mut self) {
if self.nym_api_urls.len() == 1 {
warn!("There's only a single nym API available - it won't be possible to use a different one");
return;
}
self.currently_used_api = (self.currently_used_api + 1) % self.validator_api_urls.len();
self.currently_used_api = (self.currently_used_api + 1) % self.nym_api_urls.len();
self.validator_client
.change_validator_api(self.validator_api_urls[self.currently_used_api].clone())
.change_nym_api(self.nym_api_urls[self.currently_used_api].clone())
}
/// Verifies whether nodes a reasonably distributed among all mix layers.
@@ -288,7 +282,7 @@ impl TopologyRefresher {
let new_topology = self.get_current_compatible_topology().await;
if new_topology.is_none() {
self.use_next_validator_api();
self.use_next_nym_api();
}
if new_topology.is_none() && self.was_latest_valid {
+7 -6
View File
@@ -160,8 +160,8 @@ impl<T> Config<T> {
self.client.validator_urls = validator_urls;
}
pub fn set_custom_validator_apis(&mut self, validator_api_urls: Vec<Url>) {
self.client.validator_api_urls = validator_api_urls;
pub fn set_custom_nym_apis(&mut self, nym_api_urls: Vec<Url>) {
self.client.nym_api_urls = nym_api_urls;
}
pub fn set_high_default_traffic_volume(&mut self) {
@@ -221,8 +221,8 @@ impl<T> Config<T> {
self.client.validator_urls.clone()
}
pub fn get_validator_api_endpoints(&self) -> Vec<Url> {
self.client.validator_api_urls.clone()
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
self.client.nym_api_urls.clone()
}
pub fn get_gateway_id(&self) -> String {
@@ -409,7 +409,8 @@ pub struct Client<T> {
validator_urls: Vec<Url>,
/// Addresses to APIs running on validator from which the client gets the view of the network.
validator_api_urls: Vec<Url>,
#[serde(alias = "validator_api_urls")]
nym_api_urls: Vec<Url>,
/// Path to file containing private identity key.
private_identity_key_file: PathBuf,
@@ -456,7 +457,7 @@ impl<T: NymConfig> Default for Client<T> {
id: "".to_string(),
disabled_credentials_mode: true,
validator_urls: vec![],
validator_api_urls: vec![],
nym_api_urls: vec![],
private_identity_key_file: Default::default(),
public_identity_key_file: Default::default(),
private_encryption_key_file: Default::default(),
+2 -2
View File
@@ -30,8 +30,8 @@ pub enum ClientCoreError<B: ReplyStorageBackend> {
#[error("Failed to setup gateway")]
FailedToSetupGateway,
#[error("List of validator apis is empty")]
ListOfValidatorApisIsEmpty,
#[error("List of nym apis is empty")]
ListOfNymApisIsEmpty,
#[error("Could not load existing gateway configuration: {0}")]
CouldNotLoadExistingGatewayConfiguration(std::io::Error),
+4 -4
View File
@@ -24,12 +24,12 @@ pub(super) async fn query_gateway_details<B>(
where
B: ReplyStorageBackend,
{
let validator_api = validator_servers
let nym_api = validator_servers
.choose(&mut thread_rng())
.ok_or(ClientCoreError::ListOfValidatorApisIsEmpty)?;
let validator_client = validator_client::client::ApiClient::new(validator_api.clone());
.ok_or(ClientCoreError::ListOfNymApisIsEmpty)?;
let validator_client = validator_client::client::ApiClient::new(nym_api.clone());
log::trace!("Fetching list of gateways from: {}", validator_api);
log::trace!("Fetching list of gateways from: {}", nym_api);
let gateways = validator_client.get_cached_gateways().await?;
let valid_gateways = gateways
.into_iter()
+3 -6
View File
@@ -96,7 +96,7 @@ where
{
println!("Configuring gateway");
let gateway =
query_gateway_details(config.get_validator_api_endpoints(), user_chosen_gateway_id).await?;
query_gateway_details(config.get_nym_api_endpoints(), user_chosen_gateway_id).await?;
log::debug!("Querying gateway gives: {}", gateway);
// Registering with gateway by setting up and writing shared keys to disk
@@ -120,11 +120,8 @@ where
T: NymConfig,
{
println!("Using gateway provided by user, keeping existing keys");
let gateway = query_gateway_details(
config.get_validator_api_endpoints(),
Some(user_chosen_gateway_id),
)
.await?;
let gateway =
query_gateway_details(config.get_nym_api_endpoints(), Some(user_chosen_gateway_id)).await?;
log::debug!("Querying gateway gives: {}", gateway);
Ok(gateway.into())
}
+2 -2
View File
@@ -31,8 +31,8 @@ validator_urls = [
]
# Addresses to APIs running on validator from which the client gets the view of the network.
validator_api_urls = [
{{#each client.validator_api_urls }}
nym_api_urls = [
{{#each client.nym_api_urls }}
'{{this}}',
{{/each}}
]
+1 -1
View File
@@ -56,7 +56,7 @@ impl SocketClient {
.expect("No nymd validator endpoint provided");
let api_url = config
.get_base()
.get_validator_api_endpoints()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
+2 -2
View File
@@ -114,13 +114,13 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
if let Some(raw_validators) = args.api_validators {
config
.get_base_mut()
.set_custom_validator_apis(config::parse_validators(&raw_validators));
.set_custom_nym_apis(config::parse_validators(&raw_validators));
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::API_VALIDATOR)
.expect("api validator not set");
config
.get_base_mut()
.set_custom_validator_apis(config::parse_validators(&raw_validators));
.set_custom_nym_apis(config::parse_validators(&raw_validators));
}
if args.disable_socket {
+2 -2
View File
@@ -31,8 +31,8 @@ validator_urls = [
]
# Addresses to APIs running on validator from which the client gets the view of the network.
validator_api_urls = [
{{#each client.validator_api_urls }}
nym_api_urls = [
{{#each client.nym_api_urls }}
'{{this}}',
{{/each}}
]
+1 -1
View File
@@ -67,7 +67,7 @@ impl NymClient {
.expect("No nymd validator endpoint provided");
let api_url = config
.get_base()
.get_validator_api_endpoints()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
+2 -2
View File
@@ -116,11 +116,11 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
if let Some(raw_validators) = args.api_validators {
config
.get_base_mut()
.set_custom_validator_apis(parse_validators(&raw_validators));
.set_custom_nym_apis(parse_validators(&raw_validators));
} else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::API_VALIDATOR) {
config
.get_base_mut()
.set_custom_validator_apis(parse_validators(&raw_validators));
.set_custom_nym_apis(parse_validators(&raw_validators));
}
if args.use_anonymous_sender_tag {
+3 -3
View File
@@ -43,9 +43,9 @@ pub(crate) struct Run {
#[clap(long)]
nymd_validators: Option<String>,
/// Comma separated list of rest endpoints of the API validators
/// Comma separated list of rest endpoints of the Nym APIs
#[clap(long)]
api_validators: Option<String>,
nym_apis: Option<String>,
/// Port for the socket to listen on
#[clap(short, long)]
@@ -71,7 +71,7 @@ impl From<Run> for OverrideConfig {
fn from(run_config: Run) -> Self {
OverrideConfig {
nymd_validators: run_config.nymd_validators,
api_validators: run_config.api_validators,
api_validators: run_config.nym_apis,
port: run_config.port,
use_anonymous_sender_tag: run_config.use_anonymous_sender_tag,
fastmode: run_config.fastmode,
+4 -4
View File
@@ -86,7 +86,7 @@ export default class ValidatorClient implements INymClient {
static async connect(
mnemonic: string,
nymdUrl: string,
validatorApiUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
vestingContract: string,
@@ -94,19 +94,19 @@ export default class ValidatorClient implements INymClient {
): Promise<ValidatorClient> {
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, validatorApiUrl, prefix, denom);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, nymApiUrl, prefix, denom);
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom);
}
static async connectForQuery(
nymdUrl: string,
validatorApiUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
vestingContract: string,
denom: string,
): Promise<ValidatorClient> {
const queryClient = await QueryClient.connectWithNym(nymdUrl, validatorApiUrl);
const queryClient = await QueryClient.connectWithNym(nymdUrl, nymApiUrl);
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom);
}
@@ -6,13 +6,13 @@
import axios from 'axios';
import { GatewayBond, MixNodeBond } from './types';
export const VALIDATOR_API_VERSION = '/v1';
export const VALIDATOR_API_GATEWAYS_PATH = `${VALIDATOR_API_VERSION}/gateways`;
export const VALIDATOR_API_MIXNODES_PATH = `${VALIDATOR_API_VERSION}/mixnodes`;
export const VALIDATOR_API_ACTIVE_MIXNODES_PATH = `${VALIDATOR_API_VERSION}/mixnodes/active`;
export const VALIDATOR_API_REWARDED_MIXNODES_PATH = `${VALIDATOR_API_VERSION}/mixnodes/rewarded`;
export const NYM_API_VERSION = '/v1';
export const NYM_API_GATEWAYS_PATH = `${NYM_API_VERSION}/gateways`;
export const NYM_API_MIXNODES_PATH = `${NYM_API_VERSION}/mixnodes`;
export const NYM_API_ACTIVE_MIXNODES_PATH = `${NYM_API_VERSION}/mixnodes/active`;
export const NYM_API_REWARDED_MIXNODES_PATH = `${NYM_API_VERSION}/mixnodes/rewarded`;
export interface IValidatorApiQuery {
export interface INymApiQuery {
getCachedMixnodes(): Promise<MixNodeBond[]>;
getCachedGateways(): Promise<GatewayBond[]>;
@@ -22,16 +22,16 @@ export interface IValidatorApiQuery {
getRewardedMixnodes(): Promise<MixNodeBond[]>;
}
export default class ValidatorApiQuerier implements IValidatorApiQuery {
validatorApiUrl: string;
export default class NymApiQuerier implements INymApiQuery {
nymApiUrl: string;
constructor(validatorApiUrl: string) {
this.validatorApiUrl = validatorApiUrl;
constructor(nymApiUrl: string) {
this.nymApiUrl = nymApiUrl;
}
async getCachedMixnodes(): Promise<MixNodeBond[]> {
const url = new URL(this.validatorApiUrl);
url.pathname += VALIDATOR_API_MIXNODES_PATH;
const url = new URL(this.nymApiUrl);
url.pathname += NYM_API_MIXNODES_PATH;
const response = await axios.get(url.toString());
if (response.status === 200) {
@@ -41,8 +41,8 @@ export default class ValidatorApiQuerier implements IValidatorApiQuery {
}
async getCachedGateways(): Promise<GatewayBond[]> {
const url = new URL(this.validatorApiUrl);
url.pathname += VALIDATOR_API_GATEWAYS_PATH;
const url = new URL(this.nymApiUrl);
url.pathname += NYM_API_GATEWAYS_PATH;
const response = await axios.get(url.toString());
if (response.status === 200) {
@@ -52,8 +52,8 @@ export default class ValidatorApiQuerier implements IValidatorApiQuery {
}
async getActiveMixnodes(): Promise<MixNodeBond[]> {
const url = new URL(this.validatorApiUrl);
url.pathname += VALIDATOR_API_ACTIVE_MIXNODES_PATH;
const url = new URL(this.nymApiUrl);
url.pathname += NYM_API_ACTIVE_MIXNODES_PATH;
const response = await axios.get(url.toString());
if (response.status === 200) {
@@ -63,8 +63,8 @@ export default class ValidatorApiQuerier implements IValidatorApiQuery {
}
async getRewardedMixnodes(): Promise<MixNodeBond[]> {
const url = new URL(this.validatorApiUrl);
url.pathname += VALIDATOR_API_REWARDED_MIXNODES_PATH;
const url = new URL(this.nymApiUrl);
url.pathname += NYM_API_REWARDED_MIXNODES_PATH;
const response = await axios.get(url.toString());
if (response.status === 200) {
+11 -11
View File
@@ -29,7 +29,7 @@ import {
PagedMixnodeResponse,
RewardingStatus,
} from './types';
import ValidatorApiQuerier, { IValidatorApiQuery } from './validator-api-querier';
import NymApiQuerier, { INymApiQuery as INymApiQuery } from './nym-api-querier';
export interface ICosmWasmQuery {
// methods exposed by `CosmWasmClient`
@@ -93,22 +93,22 @@ export interface INymdQuery {
): Promise<RewardingStatus>;
}
export interface IQueryClient extends ICosmWasmQuery, INymdQuery, IValidatorApiQuery {}
export interface IQueryClient extends ICosmWasmQuery, INymdQuery, INymApiQuery { }
export default class QueryClient extends CosmWasmClient implements IQueryClient {
private nymdQuerier: NymdQuerier;
private validatorApiQuerier: ValidatorApiQuerier;
private nymApiQuerier: NymApiQuerier;
private constructor(tmClient: Tendermint34Client, validatorApiUrl: string) {
private constructor(tmClient: Tendermint34Client, nymApiUrl: string) {
super(tmClient);
this.nymdQuerier = new NymdQuerier(this);
this.validatorApiQuerier = new ValidatorApiQuerier(validatorApiUrl);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNym(nymdUrl: string, validatorApiUrl: string): Promise<QueryClient> {
public static async connectWithNym(nymdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nymdUrl);
return new QueryClient(tmClient, validatorApiUrl);
return new QueryClient(tmClient, nymApiUrl);
}
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
@@ -194,18 +194,18 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
}
getCachedGateways(): Promise<GatewayBond[]> {
return this.validatorApiQuerier.getCachedGateways();
return this.nymApiQuerier.getCachedGateways();
}
getCachedMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getCachedMixnodes();
return this.nymApiQuerier.getCachedMixnodes();
}
getActiveMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getActiveMixnodes();
return this.nymApiQuerier.getActiveMixnodes();
}
getRewardedMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getRewardedMixnodes();
return this.nymApiQuerier.getRewardedMixnodes();
}
}
+10 -10
View File
@@ -33,7 +33,7 @@ import {
PagedMixnodeResponse,
RewardingStatus,
} from './types';
import ValidatorApiQuerier from './validator-api-querier';
import NymApiQuerier from './nym-api-querier';
// methods exposed by `SigningCosmWasmClient`
export interface ICosmWasmSigning {
@@ -199,13 +199,13 @@ export interface ISigningClient extends IQueryClient, ICosmWasmSigning, INymSign
export default class SigningClient extends SigningCosmWasmClient implements ISigningClient {
private nymdQuerier: NymdQuerier;
private validatorApiQuerier: ValidatorApiQuerier;
private nymApiQuerier: NymApiQuerier;
clientAddress: string;
private constructor(
clientAddress: string,
validatorApiUrl: string,
nymApiUrl: string,
tmClient: Tendermint34Client,
wallet: DirectSecp256k1HdWallet,
signerOptions: SigningCosmWasmClientOptions,
@@ -213,13 +213,13 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
super(tmClient, wallet, signerOptions);
this.clientAddress = clientAddress;
this.nymdQuerier = new NymdQuerier(this);
this.validatorApiQuerier = new ValidatorApiQuerier(validatorApiUrl);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNymSigner(
wallet: DirectSecp256k1HdWallet,
nymdUrl: string,
validatorApiUrl: string,
nymApiUrl: string,
prefix: string,
denom: string,
): Promise<SigningClient> {
@@ -229,7 +229,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
gasPrice: nymGasPrice(denom),
};
const tmClient = await Tendermint34Client.connect(nymdUrl);
return new SigningClient(address, validatorApiUrl, tmClient, wallet, signerOptions);
return new SigningClient(address, nymApiUrl, tmClient, wallet, signerOptions);
}
// query related:
@@ -317,19 +317,19 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
}
getCachedGateways(): Promise<GatewayBond[]> {
return this.validatorApiQuerier.getCachedGateways();
return this.nymApiQuerier.getCachedGateways();
}
getCachedMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getCachedMixnodes();
return this.nymApiQuerier.getCachedMixnodes();
}
getActiveMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getActiveMixnodes();
return this.nymApiQuerier.getActiveMixnodes();
}
getRewardedMixnodes(): Promise<MixNodeBond[]> {
return this.validatorApiQuerier.getRewardedMixnodes();
return this.nymApiQuerier.getRewardedMixnodes();
}
// signing related:
@@ -1,4 +1,4 @@
import ValidatorClient from '../../dist';
import ValidatorClient from '../../validator/index';
import expect from 'expect';
describe('Query: balances', () => {
+2 -2
View File
@@ -17,7 +17,7 @@ pub struct Config {
/// ID specifies the human readable ID of this particular client.
pub(crate) id: String,
pub(crate) validator_api_url: Url,
pub(crate) nym_api_url: Url,
pub(crate) disabled_credentials_mode: bool,
@@ -38,7 +38,7 @@ impl Config {
) -> Self {
Config {
id,
validator_api_url: validator_server
nym_api_url: validator_server
.parse()
.expect("provided url was malformed"),
disabled_credentials_mode: true,
+1 -1
View File
@@ -99,7 +99,7 @@ impl NymClientBuilder {
self.bandwidth_controller,
self.reply_surb_storage_backend,
self.disabled_credentials,
vec![self.config.validator_api_url.clone()],
vec![self.config.nym_api_url.clone()],
);
let self_address = base_builder.as_mix_recipient().to_string();
@@ -29,7 +29,7 @@ futures = "0.3"
coconut-interface = { path = "../../coconut-interface" }
network-defaults = { path = "../../network-defaults" }
validator-api-requests = { path = "../../../validator-api/validator-api-requests", features = ["coconut"] }
nym-api-requests = { path = "../../../nym-api/nym-api-requests", features = ["coconut"] }
# required for nymd-client
# at some point it might be possible to make it wasm-compatible
@@ -1,16 +1,16 @@
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{validator_api, ValidatorClientError};
use crate::{nym_api, ValidatorClientError};
use coconut_dkg_common::types::NodeIndex;
use coconut_interface::VerificationKey;
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::MixId;
use mixnet_contract_common::{GatewayBond, IdentityKeyRef};
use validator_api_requests::coconut::{
use nym_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use validator_api_requests::models::{
use nym_api_requests::models::{
GatewayCoreStatusResponse, MixnodeCoreStatusResponse, MixnodeStatusResponse,
RewardEstimationResponse, StakeSaturationResponse,
};
@@ -37,10 +37,10 @@ use mixnet_contract_common::{
#[cfg(feature = "nymd-client")]
use network_defaults::NymNetworkDetails;
#[cfg(feature = "nymd-client")]
use nym_api_requests::models::MixNodeBondAnnotated;
#[cfg(feature = "nymd-client")]
use std::str::FromStr;
use url::Url;
#[cfg(feature = "nymd-client")]
use validator_api_requests::models::MixNodeBondAnnotated;
#[cfg(feature = "nymd-client")]
#[must_use]
@@ -142,7 +142,7 @@ pub struct Client<C> {
proposals_page_limit: Option<u32>,
// ideally they would have been read-only, but unfortunately rust doesn't have such features
pub validator_api: validator_api::Client,
pub nym_api: nym_api::Client,
pub nymd: NymdClient<C>,
}
@@ -152,7 +152,7 @@ impl Client<SigningNymdClient> {
config: Config,
mnemonic: bip39::Mnemonic,
) -> Result<Client<SigningNymdClient>, ValidatorClientError> {
let validator_api_client = validator_api::Client::new(config.api_url.clone());
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client = NymdClient::connect_with_mnemonic(
config.nymd_config.clone(),
config.nymd_url.as_str(),
@@ -169,7 +169,7 @@ impl Client<SigningNymdClient> {
dealers_page_limit: config.dealers_page_limit,
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
validator_api: validator_api_client,
nym_api: nym_api_client,
nymd: nymd_client,
})
}
@@ -192,7 +192,7 @@ impl Client<SigningNymdClient> {
#[cfg(feature = "nymd-client")]
impl Client<QueryNymdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNymdClient>, ValidatorClientError> {
let validator_api_client = validator_api::Client::new(config.api_url.clone());
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client =
NymdClient::connect(config.nymd_config.clone(), config.nymd_url.as_str())?;
@@ -205,7 +205,7 @@ impl Client<QueryNymdClient> {
dealers_page_limit: config.dealers_page_limit,
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
validator_api: validator_api_client,
nym_api: nym_api_client,
nymd: nymd_client,
})
}
@@ -731,53 +731,53 @@ impl<C> Client<C> {
// validator-api wrappers
#[cfg(feature = "nymd-client")]
impl<C> Client<C> {
pub fn change_validator_api(&mut self, new_endpoint: Url) {
self.validator_api.change_url(new_endpoint)
pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api.change_url(new_endpoint)
}
pub async fn get_cached_mixnodes(&self) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_mixnodes().await?)
Ok(self.nym_api.get_mixnodes().await?)
}
pub async fn get_cached_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorClientError> {
Ok(self.validator_api.get_mixnodes_detailed().await?)
Ok(self.nym_api.get_mixnodes_detailed().await?)
}
pub async fn get_cached_rewarded_mixnodes(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_rewarded_mixnodes().await?)
Ok(self.nym_api.get_rewarded_mixnodes().await?)
}
pub async fn get_cached_rewarded_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorClientError> {
Ok(self.validator_api.get_rewarded_mixnodes_detailed().await?)
Ok(self.nym_api.get_rewarded_mixnodes_detailed().await?)
}
pub async fn get_cached_active_mixnodes(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_active_mixnodes().await?)
Ok(self.nym_api.get_active_mixnodes().await?)
}
pub async fn get_cached_active_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorClientError> {
Ok(self.validator_api.get_active_mixnodes_detailed().await?)
Ok(self.nym_api.get_active_mixnodes_detailed().await?)
}
pub async fn get_cached_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError> {
Ok(self.validator_api.get_gateways().await?)
Ok(self.nym_api.get_gateways().await?)
}
pub async fn blind_sign(
&self,
request_body: &BlindSignRequestBody,
) -> Result<BlindedSignatureResponse, ValidatorClientError> {
Ok(self.validator_api.blind_sign(request_body).await?)
Ok(self.nym_api.blind_sign(request_body).await?)
}
}
@@ -827,42 +827,40 @@ impl CoconutApiClient {
#[derive(Clone)]
pub struct ApiClient {
pub validator_api: validator_api::Client,
pub nym_api_client: nym_api::Client,
// TODO: perhaps if we really need it at some (currently I don't see any reasons for it)
// we could re-implement the communication with the REST API on port 1317
}
impl ApiClient {
pub fn new(api_url: Url) -> Self {
let validator_api_client = validator_api::Client::new(api_url);
let nym_api_client = nym_api::Client::new(api_url);
ApiClient {
validator_api: validator_api_client,
}
ApiClient { nym_api_client }
}
pub fn change_validator_api(&mut self, new_endpoint: Url) {
self.validator_api.change_url(new_endpoint);
pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api_client.change_url(new_endpoint);
}
pub async fn get_cached_active_mixnodes(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_active_mixnodes().await?)
Ok(self.nym_api_client.get_active_mixnodes().await?)
}
pub async fn get_cached_rewarded_mixnodes(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_rewarded_mixnodes().await?)
Ok(self.nym_api_client.get_rewarded_mixnodes().await?)
}
pub async fn get_cached_mixnodes(&self) -> Result<Vec<MixNodeDetails>, ValidatorClientError> {
Ok(self.validator_api.get_mixnodes().await?)
Ok(self.nym_api_client.get_mixnodes().await?)
}
pub async fn get_cached_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError> {
Ok(self.validator_api.get_gateways().await?)
Ok(self.nym_api_client.get_gateways().await?)
}
pub async fn get_gateway_core_status_count(
@@ -871,7 +869,7 @@ impl ApiClient {
since: Option<i64>,
) -> Result<GatewayCoreStatusResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.get_gateway_core_status_count(identity, since)
.await?)
}
@@ -882,7 +880,7 @@ impl ApiClient {
since: Option<i64>,
) -> Result<MixnodeCoreStatusResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.get_mixnode_core_status_count(mix_id, since)
.await?)
}
@@ -891,7 +889,7 @@ impl ApiClient {
&self,
mix_id: MixId,
) -> Result<MixnodeStatusResponse, ValidatorClientError> {
Ok(self.validator_api.get_mixnode_status(mix_id).await?)
Ok(self.nym_api_client.get_mixnode_status(mix_id).await?)
}
pub async fn get_mixnode_reward_estimation(
@@ -899,7 +897,7 @@ impl ApiClient {
mix_id: MixId,
) -> Result<RewardEstimationResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.get_mixnode_reward_estimation(mix_id)
.await?)
}
@@ -909,7 +907,7 @@ impl ApiClient {
mix_id: MixId,
) -> Result<StakeSaturationResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.get_mixnode_stake_saturation(mix_id)
.await?)
}
@@ -918,7 +916,7 @@ impl ApiClient {
&self,
request_body: &BlindSignRequestBody,
) -> Result<BlindedSignatureResponse, ValidatorClientError> {
Ok(self.validator_api.blind_sign(request_body).await?)
Ok(self.nym_api_client.blind_sign(request_body).await?)
}
pub async fn partial_bandwidth_credential(
@@ -926,7 +924,7 @@ impl ApiClient {
request_body: &str,
) -> Result<BlindedSignatureResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.partial_bandwidth_credential(request_body)
.await?)
}
@@ -936,7 +934,7 @@ impl ApiClient {
request_body: &VerifyCredentialBody,
) -> Result<VerifyCredentialResponse, ValidatorClientError> {
Ok(self
.validator_api
.nym_api_client
.verify_bandwidth_credential(request_body)
.await?)
}
@@ -1,15 +1,15 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::validator_api;
use crate::nym_api;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ValidatorClientError {
#[error("There was an issue with the validator api request - {source}")]
ValidatorAPIError {
NymAPIError {
#[from]
source: validator_api::error::ValidatorAPIError,
source: nym_api::error::NymAPIError,
},
#[error("One of the provided URLs was malformed - {0}")]
@@ -5,14 +5,14 @@ pub mod client;
#[cfg(feature = "nymd-client")]
pub mod connection_tester;
mod error;
pub mod nym_api;
#[cfg(feature = "nymd-client")]
pub mod nymd;
pub mod validator_api;
#[cfg(feature = "nymd-client")]
pub use crate::client::{ApiClient, CoconutApiClient};
pub use crate::error::ValidatorClientError;
pub use validator_api_requests::*;
pub use nym_api_requests::*;
#[cfg(feature = "nymd-client")]
pub use client::{Client, Config};
@@ -1,8 +1,8 @@
use nym_api_requests::models::RequestError;
use thiserror::Error;
use validator_api_requests::models::RequestError;
#[derive(Error, Debug)]
pub enum ValidatorAPIError {
pub enum NymAPIError {
#[error("There was an issue with the REST request - {source}")]
ReqwestClientError {
#[from]
@@ -12,6 +12,6 @@ pub enum ValidatorAPIError {
#[error("Request failed with error message - {0}")]
GenericRequestFailure(String),
#[error("The validator API has failed to resolve our request. It returned status code {status} and additional error message: {}", error.message())]
#[error("The nym API has failed to resolve our request. It returned status code {status} and additional error message: {}", error.message())]
ApiRequestFailure { status: u16, error: RequestError },
}
@@ -1,22 +1,22 @@
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::validator_api::error::ValidatorAPIError;
use crate::validator_api::routes::{CORE_STATUS_COUNT, SINCE_ARG};
use crate::nym_api::error::NymAPIError;
use crate::nym_api::routes::{CORE_STATUS_COUNT, SINCE_ARG};
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixId};
use reqwest::Response;
use serde::{Deserialize, Serialize};
use url::Url;
use validator_api_requests::coconut::{
use nym_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use validator_api_requests::models::{
use nym_api_requests::models::{
GatewayCoreStatusResponse, GatewayStatusReportResponse, GatewayUptimeHistoryResponse,
InclusionProbabilityResponse, MixNodeBondAnnotated, MixnodeCoreStatusResponse,
MixnodeStatusReportResponse, MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RequestError,
RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
};
use reqwest::Response;
use serde::{Deserialize, Serialize};
use url::Url;
pub mod error;
pub mod routes;
@@ -53,7 +53,7 @@ impl Client {
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<Response, ValidatorAPIError>
) -> Result<Response, NymAPIError>
where
K: AsRef<str>,
V: AsRef<str>,
@@ -62,11 +62,11 @@ impl Client {
Ok(self.reqwest_client.get(url).send().await?)
}
async fn query_validator_api<T, K, V>(
async fn query_nym_api<T, K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, ValidatorAPIError>
) -> Result<T, NymAPIError>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str>,
@@ -76,16 +76,16 @@ impl Client {
if res.status().is_success() {
Ok(res.json().await?)
} else {
Err(ValidatorAPIError::GenericRequestFailure(res.text().await?))
Err(NymAPIError::GenericRequestFailure(res.text().await?))
}
}
// This works for endpoints returning Result<Json<T>, ErrorResponse>
async fn query_validator_api_fallible<T, K, V>(
async fn query_nym_api_fallible<T, K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, ValidatorAPIError>
) -> Result<T, NymAPIError>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str>,
@@ -97,19 +97,19 @@ impl Client {
Ok(res.json().await?)
} else {
let request_error: RequestError = res.json().await?;
Err(ValidatorAPIError::ApiRequestFailure {
Err(NymAPIError::ApiRequestFailure {
status: status.as_u16(),
error: request_error,
})
}
}
async fn post_validator_api<B, T, K, V>(
async fn post_nym_api<B, T, K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
json_body: &B,
) -> Result<T, ValidatorAPIError>
) -> Result<T, NymAPIError>
where
B: Serialize + ?Sized,
for<'a> T: Deserialize<'a>,
@@ -121,21 +121,17 @@ impl Client {
if response.status().is_success() {
Ok(response.json().await?)
} else {
Err(ValidatorAPIError::GenericRequestFailure(
response.text().await?,
))
Err(NymAPIError::GenericRequestFailure(response.text().await?))
}
}
pub async fn get_mixnodes(&self) -> Result<Vec<MixNodeDetails>, ValidatorAPIError> {
self.query_validator_api(&[routes::API_VERSION, routes::MIXNODES], NO_PARAMS)
pub async fn get_mixnodes(&self) -> Result<Vec<MixNodeDetails>, NymAPIError> {
self.query_nym_api(&[routes::API_VERSION, routes::MIXNODES], NO_PARAMS)
.await
}
pub async fn get_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorAPIError> {
self.query_validator_api(
pub async fn get_mixnodes_detailed(&self) -> Result<Vec<MixNodeBondAnnotated>, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -147,13 +143,13 @@ impl Client {
.await
}
pub async fn get_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorAPIError> {
self.query_validator_api(&[routes::API_VERSION, routes::GATEWAYS], NO_PARAMS)
pub async fn get_gateways(&self) -> Result<Vec<GatewayBond>, NymAPIError> {
self.query_nym_api(&[routes::API_VERSION, routes::GATEWAYS], NO_PARAMS)
.await
}
pub async fn get_active_mixnodes(&self) -> Result<Vec<MixNodeDetails>, ValidatorAPIError> {
self.query_validator_api(
pub async fn get_active_mixnodes(&self) -> Result<Vec<MixNodeDetails>, NymAPIError> {
self.query_nym_api(
&[routes::API_VERSION, routes::MIXNODES, routes::ACTIVE],
NO_PARAMS,
)
@@ -162,8 +158,8 @@ impl Client {
pub async fn get_active_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorAPIError> {
self.query_validator_api(
) -> Result<Vec<MixNodeBondAnnotated>, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -176,8 +172,8 @@ impl Client {
.await
}
pub async fn get_rewarded_mixnodes(&self) -> Result<Vec<MixNodeDetails>, ValidatorAPIError> {
self.query_validator_api(
pub async fn get_rewarded_mixnodes(&self) -> Result<Vec<MixNodeDetails>, NymAPIError> {
self.query_nym_api(
&[routes::API_VERSION, routes::MIXNODES, routes::REWARDED],
NO_PARAMS,
)
@@ -187,8 +183,8 @@ impl Client {
pub async fn get_mixnode_report(
&self,
mix_id: MixId,
) -> Result<MixnodeStatusReportResponse, ValidatorAPIError> {
self.query_validator_api(
) -> Result<MixnodeStatusReportResponse, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -204,8 +200,8 @@ impl Client {
pub async fn get_gateway_report(
&self,
identity: IdentityKeyRef<'_>,
) -> Result<GatewayStatusReportResponse, ValidatorAPIError> {
self.query_validator_api(
) -> Result<GatewayStatusReportResponse, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -221,8 +217,8 @@ impl Client {
pub async fn get_mixnode_history(
&self,
mix_id: MixId,
) -> Result<MixnodeUptimeHistoryResponse, ValidatorAPIError> {
self.query_validator_api(
) -> Result<MixnodeUptimeHistoryResponse, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -238,8 +234,8 @@ impl Client {
pub async fn get_gateway_history(
&self,
identity: IdentityKeyRef<'_>,
) -> Result<GatewayUptimeHistoryResponse, ValidatorAPIError> {
self.query_validator_api(
) -> Result<GatewayUptimeHistoryResponse, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -254,8 +250,8 @@ impl Client {
pub async fn get_rewarded_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorAPIError> {
self.query_validator_api(
) -> Result<Vec<MixNodeBondAnnotated>, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS,
@@ -272,9 +268,9 @@ impl Client {
&self,
identity: IdentityKeyRef<'_>,
since: Option<i64>,
) -> Result<GatewayCoreStatusResponse, ValidatorAPIError> {
) -> Result<GatewayCoreStatusResponse, NymAPIError> {
if let Some(since) = since {
self.query_validator_api(
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -286,7 +282,7 @@ impl Client {
)
.await
} else {
self.query_validator_api(
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -303,9 +299,9 @@ impl Client {
&self,
mix_id: MixId,
since: Option<i64>,
) -> Result<MixnodeCoreStatusResponse, ValidatorAPIError> {
) -> Result<MixnodeCoreStatusResponse, NymAPIError> {
if let Some(since) = since {
self.query_validator_api(
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -317,7 +313,7 @@ impl Client {
)
.await
} else {
self.query_validator_api(
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -334,8 +330,8 @@ impl Client {
pub async fn get_mixnode_status(
&self,
mix_id: MixId,
) -> Result<MixnodeStatusResponse, ValidatorAPIError> {
self.query_validator_api(
) -> Result<MixnodeStatusResponse, NymAPIError> {
self.query_nym_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -351,8 +347,8 @@ impl Client {
pub async fn get_mixnode_reward_estimation(
&self,
mix_id: MixId,
) -> Result<RewardEstimationResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
) -> Result<RewardEstimationResponse, NymAPIError> {
self.query_nym_api_fallible(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -368,8 +364,8 @@ impl Client {
pub async fn get_mixnode_stake_saturation(
&self,
mix_id: MixId,
) -> Result<StakeSaturationResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
) -> Result<StakeSaturationResponse, NymAPIError> {
self.query_nym_api_fallible(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -385,8 +381,8 @@ impl Client {
pub async fn get_mixnode_inclusion_probability(
&self,
mix_id: MixId,
) -> Result<InclusionProbabilityResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
) -> Result<InclusionProbabilityResponse, NymAPIError> {
self.query_nym_api_fallible(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -402,8 +398,8 @@ impl Client {
pub async fn get_mixnode_avg_uptime(
&self,
mix_id: MixId,
) -> Result<UptimeResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
) -> Result<UptimeResponse, NymAPIError> {
self.query_nym_api_fallible(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -419,8 +415,8 @@ impl Client {
pub async fn blind_sign(
&self,
request_body: &BlindSignRequestBody,
) -> Result<BlindedSignatureResponse, ValidatorAPIError> {
self.post_validator_api(
) -> Result<BlindedSignatureResponse, NymAPIError> {
self.post_nym_api(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
@@ -436,8 +432,8 @@ impl Client {
pub async fn partial_bandwidth_credential(
&self,
request_body: &str,
) -> Result<BlindedSignatureResponse, ValidatorAPIError> {
self.post_validator_api(
) -> Result<BlindedSignatureResponse, NymAPIError> {
self.post_nym_api(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
@@ -453,8 +449,8 @@ impl Client {
pub async fn verify_bandwidth_credential(
&self,
request_body: &VerifyCredentialBody,
) -> Result<VerifyCredentialResponse, ValidatorAPIError> {
self.post_validator_api(
) -> Result<VerifyCredentialResponse, NymAPIError> {
self.post_nym_api(
&[
routes::API_VERSION,
routes::COCONUT_ROUTES,
@@ -1,9 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use network_defaults::VALIDATOR_API_VERSION;
use network_defaults::NYM_API_VERSION;
pub const API_VERSION: &str = VALIDATOR_API_VERSION;
pub const API_VERSION: &str = NYM_API_VERSION;
pub const MIXNODES: &str = "mixnodes";
pub const GATEWAYS: &str = "gateways";
+10 -10
View File
@@ -7,8 +7,8 @@ use network_defaults::{
NymNetworkDetails,
};
use tap::prelude::*;
pub use validator_client::nym_api::Client as NymApiClient;
use validator_client::nymd::{self, AccountId, NymdClient, QueryNymdClient, SigningNymdClient};
pub use validator_client::validator_api::Client as ValidatorApiClient;
use crate::context::errors::ContextError;
@@ -16,14 +16,14 @@ pub mod errors;
pub type SigningClient = validator_client::nymd::NymdClient<SigningNymdClient>;
pub type QueryClient = validator_client::nymd::NymdClient<QueryNymdClient>;
pub type SigningClientWithValidatorAPI = validator_client::Client<SigningNymdClient>;
pub type QueryClientWithValidatorAPI = validator_client::Client<QueryNymdClient>;
pub type SigningClientWithNymd = validator_client::Client<SigningNymdClient>;
pub type QueryClientWithNymd = validator_client::Client<QueryNymdClient>;
#[derive(Debug)]
pub struct ClientArgs {
pub config_env_file: Option<std::path::PathBuf>,
pub nymd_url: Option<String>,
pub validator_api_url: Option<String>,
pub nym_api_url: Option<String>,
pub mnemonic: Option<bip39::Mnemonic>,
pub mixnet_contract_address: Option<AccountId>,
pub vesting_contract_address: Option<AccountId>,
@@ -38,8 +38,8 @@ pub fn get_network_details(args: &ClientArgs) -> Result<NymNetworkDetails, Conte
if let Some(nymd_url) = args.nymd_url.as_ref() {
std::env::set_var(NYMD_VALIDATOR, nymd_url);
}
if let Some(validator_api_url) = args.validator_api_url.as_ref() {
std::env::set_var(API_VALIDATOR, validator_api_url);
if let Some(nym_api_url) = args.nym_api_url.as_ref() {
std::env::set_var(API_VALIDATOR, nym_api_url);
}
if let Some(mixnet_contract_address) = args.mixnet_contract_address.as_ref() {
std::env::set_var(MIXNET_CONTRACT_ADDRESS, mixnet_contract_address.to_string());
@@ -103,10 +103,10 @@ pub fn create_query_client(
}
}
pub fn create_signing_client_with_validator_api(
pub fn create_signing_client_with_nym_api(
args: ClientArgs,
network_details: &NymNetworkDetails,
) -> Result<SigningClientWithValidatorAPI, ContextError> {
) -> Result<SigningClientWithNymd, ContextError> {
let client_config = validator_client::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?;
@@ -126,9 +126,9 @@ pub fn create_signing_client_with_validator_api(
}
}
pub fn create_query_client_with_validator_api(
pub fn create_query_client_with_nym_api(
network_details: &NymNetworkDetails,
) -> Result<QueryClientWithValidatorAPI, ContextError> {
) -> Result<QueryClientWithNymd, ContextError> {
let client_config = validator_client::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?;
@@ -4,7 +4,7 @@
use clap::Parser;
use log::info;
use crate::context::SigningClientWithValidatorAPI;
use crate::context::SigningClientWithNymd;
use crate::utils::{pretty_cosmwasm_coin, show_error_passthrough};
use comfy_table::Table;
@@ -14,7 +14,7 @@ use mixnet_contract_common::{Delegation, PendingEpochEvent, PendingEpochEventKin
#[derive(Debug, Parser)]
pub struct Args {}
pub async fn execute(_args: Args, client: SigningClientWithValidatorAPI) {
pub async fn execute(_args: Args, client: SigningClientWithNymd) {
info!(
"Getting delegations for account {}...",
client.nymd.address()
@@ -48,14 +48,14 @@ pub async fn execute(_args: Args, client: SigningClientWithValidatorAPI) {
}
}
async fn to_iso_timestamp(block_height: u32, client: &SigningClientWithValidatorAPI) -> String {
async fn to_iso_timestamp(block_height: u32, client: &SigningClientWithNymd) -> String {
match client.nymd.get_block_timestamp(Some(block_height)).await {
Ok(res) => res.to_rfc3339(),
Err(_e) => "-".to_string(),
}
}
async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientWithValidatorAPI) {
async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientWithNymd) {
let mut table = Table::new();
table.set_header(vec!["Timestamp", "Mix Id", "Delegation", "Proxy"]);
@@ -75,10 +75,7 @@ async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientW
println!("{table}");
}
async fn print_delegation_events(
events: Vec<PendingEpochEvent>,
client: &SigningClientWithValidatorAPI,
) {
async fn print_delegation_events(events: Vec<PendingEpochEvent>, client: &SigningClientWithNymd) {
let mut table = Table::new();
table.set_header(vec![
@@ -4,7 +4,7 @@
use clap::Parser;
use comfy_table::Table;
use crate::context::QueryClientWithValidatorAPI;
use crate::context::QueryClientWithNymd;
use crate::utils::{pretty_cosmwasm_coin, show_error};
#[derive(Debug, Parser)]
@@ -14,8 +14,8 @@ pub struct Args {
pub identity_key: Option<String>,
}
pub async fn query(args: Args, client: &QueryClientWithValidatorAPI) {
match client.validator_api.get_gateways().await {
pub async fn query(args: Args, client: &QueryClientWithNymd) {
match client.nym_api.get_gateways().await {
Ok(res) => match args.identity_key {
Some(identity_key) => {
let node = res.iter().find(|node| {
@@ -4,7 +4,7 @@
use clap::Parser;
use comfy_table::Table;
use crate::context::QueryClientWithValidatorAPI;
use crate::context::QueryClientWithNymd;
use crate::utils::{pretty_decimal_with_denom, show_error};
#[derive(Debug, Parser)]
@@ -14,8 +14,8 @@ pub struct Args {
pub identity_key: Option<String>,
}
pub async fn query(args: Args, client: &QueryClientWithValidatorAPI) {
match client.validator_api.get_mixnodes().await {
pub async fn query(args: Args, client: &QueryClientWithNymd) {
match client.nym_api.get_mixnodes().await {
Ok(res) => match args.identity_key {
Some(identity_key) => {
let node = res.iter().find(|node| {
+1 -1
View File
@@ -13,7 +13,7 @@ thiserror = "1.0"
# I guess temporarily until we get serde support in coconut up and running
coconut-interface = { path = "../coconut-interface" }
crypto = { path = "../crypto", features = ["rand", "asymmetric", "symmetric", "hashing"] }
validator-api-requests = { path = "../../validator-api/validator-api-requests" }
nym-api-requests = { path = "../../nym-api/nym-api-requests" }
validator-client = { path = "../client-libs/validator-client" }
[dev-dependencies]
+2 -2
View File
@@ -9,7 +9,7 @@ type Aes128Ctr = ctr::Ctr64LE<Aes128>;
/// Hashing algorithm used during hkdf for ephemeral shared key generation per blinded signature
/// response encryption.
pub type ValidatorApiCredentialHkdfAlgorithm = blake3::Hasher;
pub type NymApiCredentialHkdfAlgorithm = blake3::Hasher;
/// Encryption algorithm used for end-to-end encryption of blinded signature response
pub type ValidatorApiCredentialEncryptionAlgorithm = Aes128Ctr;
pub type NymApiCredentialEncryptionAlgorithm = Aes128Ctr;
+6 -8
View File
@@ -8,13 +8,11 @@ use coconut_interface::{
use crypto::asymmetric::encryption::PublicKey;
use crypto::shared_key::recompute_shared_key;
use crypto::symmetric::stream_cipher;
use validator_api_requests::coconut::BlindSignRequestBody;
use nym_api_requests::coconut::BlindSignRequestBody;
use validator_client::client::CoconutApiClient;
use crate::coconut::bandwidth::{BandwidthVoucher, PRIVATE_ATTRIBUTES, PUBLIC_ATTRIBUTES};
use crate::coconut::params::{
ValidatorApiCredentialEncryptionAlgorithm, ValidatorApiCredentialHkdfAlgorithm,
};
use crate::coconut::params::{NymApiCredentialEncryptionAlgorithm, NymApiCredentialHkdfAlgorithm};
use crate::error::Error;
pub async fn obtain_aggregate_verification_key(
@@ -66,11 +64,11 @@ async fn obtain_partial_credential(
let remote_key = PublicKey::from_bytes(&response.remote_key)?;
let encryption_key = recompute_shared_key::<
ValidatorApiCredentialEncryptionAlgorithm,
ValidatorApiCredentialHkdfAlgorithm,
NymApiCredentialEncryptionAlgorithm,
NymApiCredentialHkdfAlgorithm,
>(&remote_key, attributes.encryption_key());
let zero_iv = stream_cipher::zero_iv::<ValidatorApiCredentialEncryptionAlgorithm>();
let blinded_signature_bytes = stream_cipher::decrypt::<ValidatorApiCredentialEncryptionAlgorithm>(
let zero_iv = stream_cipher::zero_iv::<NymApiCredentialEncryptionAlgorithm>();
let blinded_signature_bytes = stream_cipher::decrypt::<NymApiCredentialEncryptionAlgorithm>(
&encryption_key,
&zero_iv,
&encrypted_signature,
+13 -16
View File
@@ -69,8 +69,8 @@ pub struct Config {
/// due to being unable to get the list of nodes.
retry_timeout: Duration,
/// URLs to the validator apis for obtaining network topology.
validator_api_urls: Vec<Url>,
/// URLs to the nym apis for obtaining network topology.
nym_api_urls: Vec<Url>,
}
impl Config {
@@ -132,15 +132,15 @@ impl ConfigBuilder {
self
}
pub fn validator_api_urls(mut self, validator_api_urls: Vec<Url>) -> Self {
self.0.validator_api_urls = validator_api_urls;
pub fn nym_api_urls(mut self, nym_api_urls: Vec<Url>) -> Self {
self.0.nym_api_urls = nym_api_urls;
self
}
pub fn build(self) -> Config {
// panics here are fine as those are only ever constructed at the initial setup
assert!(
!self.0.validator_api_urls.is_empty(),
!self.0.nym_api_urls.is_empty(),
"at least one validator endpoint must be provided",
);
self.0
@@ -159,7 +159,7 @@ impl Default for ConfigBuilder {
tested_nodes_batch_size: DEFAULT_BATCH_SIZE,
testing_interval: DEFAULT_TESTING_INTERVAL,
retry_timeout: DEFAULT_RETRY_TIMEOUT,
validator_api_urls: vec![],
nym_api_urls: vec![],
})
}
}
@@ -186,7 +186,7 @@ impl VerlocMeasurer {
identity: Arc<identity::KeyPair>,
shutdown_listener: ShutdownListener,
) -> Self {
config.validator_api_urls.shuffle(&mut thread_rng());
config.nym_api_urls.shuffle(&mut thread_rng());
VerlocMeasurer {
packet_sender: Arc::new(PacketSender::new(
@@ -204,24 +204,21 @@ impl VerlocMeasurer {
)),
shutdown_listener,
currently_used_api: 0,
validator_client: validator_client::ApiClient::new(
config.validator_api_urls[0].clone(),
),
validator_client: validator_client::ApiClient::new(config.nym_api_urls[0].clone()),
config,
results: AtomicVerlocResult::new(),
}
}
fn use_next_validator_api(&mut self) {
if self.config.validator_api_urls.len() == 1 {
fn use_next_nym_api(&mut self) {
if self.config.nym_api_urls.len() == 1 {
warn!("There's only a single validator API available - it won't be possible to use a different one");
return;
}
self.currently_used_api =
(self.currently_used_api + 1) % self.config.validator_api_urls.len();
self.currently_used_api = (self.currently_used_api + 1) % self.config.nym_api_urls.len();
self.validator_client
.change_validator_api(self.config.validator_api_urls[self.currently_used_api].clone())
.change_nym_api(self.config.nym_api_urls[self.currently_used_api].clone())
}
pub fn get_verloc_results_pointer(&self) -> AtomicVerlocResult {
@@ -308,7 +305,7 @@ impl VerlocMeasurer {
"failed to obtain list of mixnodes from the validator - {}. Going to attempt to use another validator API in the next run",
err
);
self.use_next_validator_api();
self.use_next_nym_api();
sleep(self.config.retry_timeout).await;
continue;
}
+4 -4
View File
@@ -355,14 +355,14 @@ pub const DEFAULT_WEBSOCKET_LISTENING_PORT: u16 = 1977;
// 'SOCKS5' CLIENT
pub const DEFAULT_SOCKS5_LISTENING_PORT: u16 = 1080;
// VALIDATOR-API
pub const DEFAULT_VALIDATOR_API_PORT: u16 = 8080;
// NYM-API
pub const DEFAULT_NYM_API_PORT: u16 = 8080;
pub const VALIDATOR_API_VERSION: &str = "v1";
pub const NYM_API_VERSION: &str = "v1";
// REWARDING
/// We'll be assuming a few more things, profit margin and cost function. Since we don't have relialable package measurement, we'll be using uptime. We'll also set the value of 1 Nym to 1 $, to be able to translate interval costs to Nyms. We'll also assume a cost of 40$ per interval(month), converting that to Nym at our 1$ rate translates to 40_000_000 uNyms
/// We'll be assuming a few more things, profit margin and cost function. Since we don't have reliable package measurement, we'll be using uptime. We'll also set the value of 1 Nym to 1 $, to be able to translate interval costs to Nyms. We'll also assume a cost of 40$ per interval(month), converting that to Nym at our 1$ rate translates to 40_000_000 uNyms
// pub const DEFAULT_OPERATOR_INTERVAL_COST: u64 = 40_000_000; // 40$/(30 days) at 1 Nym == 1$
// pub const DEFAULT_OPERATOR_INTERVAL_COST: u64 = 55_556; // 40$/1hr at 1 Nym == 1$
// pub const DEFAULT_OPERATOR_INTERVAL_COST: u64 = 9259; // 40$/1hr/6 at 1 Nym == 1$
+7 -7
View File
@@ -1,7 +1,7 @@
use serde::{Serialize, Serializer};
use std::io;
use thiserror::Error;
use validator_client::validator_api::error::ValidatorAPIError;
use validator_client::nym_api::error::NymAPIError;
use validator_client::{nymd::error::NymdError, ValidatorClientError};
// TODO: ask @MS why this even exists
@@ -23,9 +23,9 @@ pub enum TypesError {
source: eyre::Report,
},
#[error("{source}")]
ValidatorApiError {
NymApiError {
#[from]
source: ValidatorAPIError,
source: NymAPIError,
},
#[error("{source}")]
IOError {
@@ -52,8 +52,8 @@ pub enum TypesError {
#[from]
source: cosmwasm_std::DecimalRangeExceeded,
},
#[error("No validator API URL configured")]
NoValidatorApiUrlConfigured,
#[error("No nym API URL configured")]
NoNymApiUrlConfigured,
#[error("{0} is not a valid amount string")]
InvalidAmount(String),
#[error("{0} is not a valid denomination string")]
@@ -88,10 +88,10 @@ impl Serialize for TypesError {
impl From<ValidatorClientError> for TypesError {
fn from(e: ValidatorClientError) -> Self {
match e {
ValidatorClientError::ValidatorAPIError { source } => source.into(),
ValidatorClientError::NymAPIError { source } => source.into(),
ValidatorClientError::MalformedUrlProvided(e) => e.into(),
ValidatorClientError::NymdError(e) => e.into(),
ValidatorClientError::NoAPIUrlAvailable => TypesError::NoValidatorApiUrlConfigured,
ValidatorClientError::NoAPIUrlAvailable => TypesError::NoNymApiUrlConfigured,
}
}
}
+1 -1
View File
@@ -408,7 +408,7 @@ pub mod tests {
let env = test.env();
// note: we don't have to test for cases where `is_unbonding` is set to true on a mixnode
// since before performing the validator-api should clear out the event queue
// since before performing the nym-api should clear out the event queue
// manually adjust delegation info as to indicate the rewarding information shouldnt get removed
let mut rewarding_details = storage::MIXNODE_REWARDING
+1 -1
View File
@@ -21,7 +21,7 @@ impl ThreadsafeValidatorClient {
}
pub(crate) fn api_endpoint(&self) -> &Url {
self.0.validator_api.current_url()
self.0.nym_api.current_url()
}
}
+2 -2
View File
@@ -54,8 +54,8 @@ impl ExplorerApi {
async fn run(&mut self) {
info!("Explorer API starting up...");
let validator_api_url = self.state.inner.validator_client.api_endpoint();
info!("Using validator API - {}", validator_api_url);
let nym_api_url = self.state.inner.validator_client.api_endpoint();
info!("Using validator API - {}", nym_api_url);
let shutdown = ShutdownNotifier::default();
+4 -9
View File
@@ -13,31 +13,26 @@ pub(crate) async fn retrieve_mixnode_econ_stats(
) -> Option<EconomicDynamicsStats> {
let stake_saturation = client
.0
.validator_api
.nym_api
.get_mixnode_stake_saturation(mix_id)
.await
.ok()?;
let inclusion_probability = client
.0
.validator_api
.nym_api
.get_mixnode_inclusion_probability(mix_id)
.await
.ok()?;
let reward_estimation = client
.0
.validator_api
.nym_api
.get_mixnode_reward_estimation(mix_id)
.await
.ok()?;
let uptime_response = client
.0
.validator_api
.get_mixnode_avg_uptime(mix_id)
.await
.ok()?;
let uptime_response = client.0.nym_api.get_mixnode_avg_uptime(mix_id).await.ok()?;
Some(EconomicDynamicsStats {
stake_saturation: best_effort_small_dec_to_f64(stake_saturation.saturation) as f32,
+1 -1
View File
@@ -1,5 +1,5 @@
EXPLORER_API_URL=https://explorer.nymtech.net/api/v1
VALIDATOR_API_URL=https://validator.nymtech.net
NYM_API_URL=https://validator.nymtech.net
VALIDATOR_URL=https://rpc.nymtech.net
BIG_DIPPER_URL=https://blocks.nymtech.net
CURRENCY_DENOM=unym
+1 -1
View File
@@ -1,5 +1,5 @@
EXPLORER_API_URL=https://qa-explorer.nymtech.net/api/v1
VALIDATOR_API_URL=https://qa-validator-api.nymtech.net
NYM_API_URL=https://qa-validator-api.nymtech.net
VALIDATOR_URL=https://qa-validator.nymtech.net
BIG_DIPPER_URL=https://qa-blocks.nymtech.net
CURRENCY_DENOM=unym
+5 -5
View File
@@ -1,6 +1,6 @@
// master APIs
export const API_BASE_URL = process.env.EXPLORER_API_URL;
export const VALIDATOR_API_BASE_URL = process.env.VALIDATOR_API_URL;
export const NYM_API_BASE_URL = process.env.NYM_API_URL;
export const VALIDATOR_BASE_URL = process.env.VALIDATOR_URL;
export const BIG_DIPPER = process.env.BIG_DIPPER_URL;
@@ -9,12 +9,12 @@ export const OVERVIEW_API = `${API_BASE_URL}/overview`;
export const MIXNODE_PING = `${API_BASE_URL}/ping`;
export const MIXNODES_API = `${API_BASE_URL}/mix-nodes`;
export const MIXNODE_API = `${API_BASE_URL}/mix-node`;
export const GATEWAYS_API = `${VALIDATOR_API_BASE_URL}/api/v1/gateways`;
export const GATEWAYS_API = `${NYM_API_BASE_URL}/api/v1/gateways`;
export const VALIDATORS_API = `${VALIDATOR_BASE_URL}/validators`;
export const BLOCK_API = `${VALIDATOR_API_BASE_URL}/block`;
export const BLOCK_API = `${NYM_API_BASE_URL}/block`;
export const COUNTRY_DATA_API = `${API_BASE_URL}/countries`;
export const UPTIME_STORY_API = `${VALIDATOR_API_BASE_URL}/api/v1/status/mixnode`; // add ID then '/history' to this.
export const UPTIME_STORY_API_GATEWAY = `${VALIDATOR_API_BASE_URL}/api/v1/status/gateway`; // add ID then '/history' or '/report' to this.
export const UPTIME_STORY_API = `${NYM_API_BASE_URL}/api/v1/status/mixnode`; // add ID then '/history' to this.
export const UPTIME_STORY_API_GATEWAY = `${NYM_API_BASE_URL}/api/v1/status/gateway`; // add ID then '/history' or '/report' to this.
// errors
export const MIXNODE_API_ERROR = "We're having trouble finding that record, please try again or Contact Us.";
+2 -2
View File
@@ -64,7 +64,7 @@ network-defaults = { path = "../common/network-defaults" }
nymsphinx = { path = "../common/nymsphinx" }
pemstore = { path = "../common/pemstore" }
statistics-common = { path = "../common/statistics" }
validator-api-requests = { path = "../validator-api/validator-api-requests" }
nym-api-requests = { path = "../nym-api/nym-api-requests" }
validator-client = { path = "../common/client-libs/validator-client", features = [
"nymd-client",
] }
@@ -75,7 +75,7 @@ coconut = [
"coconut-interface",
"gateway-requests/coconut",
"credentials/coconut",
"validator-api-requests/coconut",
"nym-api-requests/coconut",
]
[build-dependencies]
+4 -4
View File
@@ -39,9 +39,9 @@ pub struct Init {
#[clap(long)]
datastore: Option<String>,
/// Comma separated list of endpoints of the validators APIs
/// Comma separated list of endpoints of nym APIs
#[clap(long)]
validator_apis: Option<String>,
nym_apis: Option<String>,
/// Comma separated list of endpoints of the validator
#[clap(long)]
@@ -75,7 +75,7 @@ impl From<Init> for OverrideConfig {
clients_port: init_config.clients_port,
datastore: init_config.datastore,
announce_host: init_config.announce_host,
validator_apis: init_config.validator_apis,
nym_apis: init_config.nym_apis,
validators: init_config.validators,
mnemonic: init_config.mnemonic,
@@ -165,7 +165,7 @@ mod tests {
clients_port: Some(43),
announce_host: Some("foo-announce-host".to_string()),
datastore: Some("foo-datastore".to_string()),
validator_apis: None,
nym_apis: None,
validators: None,
mnemonic: None,
statistics_service_url: None,
+4 -4
View File
@@ -55,7 +55,7 @@ pub(crate) struct OverrideConfig {
announce_host: Option<String>,
enabled_statistics: Option<bool>,
statistics_service_url: Option<String>,
validator_apis: Option<String>,
nym_apis: Option<String>,
validators: Option<String>,
mnemonic: Option<String>,
@@ -119,11 +119,11 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
}
}
if let Some(raw_validators) = args.validator_apis {
config = config.with_custom_validator_apis(parse_validators(&raw_validators));
if let Some(raw_validators) = args.nym_apis {
config = config.with_custom_nym_apis(parse_validators(&raw_validators));
} else if std::env::var(CONFIGURED).is_ok() {
if let Some(raw_validators) = read_var_if_not_default(API_VALIDATOR) {
config = config.with_custom_validator_apis(::config::parse_validators(&raw_validators))
config = config.with_custom_nym_apis(::config::parse_validators(&raw_validators))
}
}
+3 -3
View File
@@ -39,9 +39,9 @@ pub struct Run {
#[clap(long)]
datastore: Option<String>,
/// Comma separated list of endpoints of the validators APIs
/// Comma separated list of endpoints of the nym APIs
#[clap(long)]
validator_apis: Option<String>,
nym_apis: Option<String>,
/// Comma separated list of endpoints of the validator
#[clap(long)]
@@ -75,7 +75,7 @@ impl From<Run> for OverrideConfig {
clients_port: run_config.clients_port,
datastore: run_config.datastore,
announce_host: run_config.announce_host,
validator_apis: run_config.validator_apis,
nym_apis: run_config.nym_apis,
validators: run_config.validators,
mnemonic: run_config.mnemonic,
+7 -7
View File
@@ -144,8 +144,8 @@ impl Config {
self
}
pub fn with_custom_validator_apis(mut self, validator_api_urls: Vec<Url>) -> Self {
self.gateway.validator_api_urls = validator_api_urls;
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.gateway.nym_api_urls = nym_api_urls;
self
}
@@ -240,8 +240,8 @@ impl Config {
self.gateway.statistics_service_url.clone()
}
pub fn get_validator_api_endpoints(&self) -> Vec<Url> {
self.gateway.validator_api_urls.clone()
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
self.gateway.nym_api_urls.clone()
}
#[cfg(feature = "coconut")]
@@ -359,8 +359,8 @@ pub struct Gateway {
/// Domain address of the statistics service
statistics_service_url: Url,
/// Addresses to APIs running on validator from which the node gets the view of the network.
validator_api_urls: Vec<Url>,
/// Addresses to APIs from which the node gets the view of the network.
nym_api_urls: Vec<Url>,
/// Addresses to validators which the node uses to check for double spending of ERC20 tokens.
validator_nymd_urls: Vec<Url>,
@@ -418,7 +418,7 @@ impl Default for Gateway {
public_sphinx_key_file: Default::default(),
enabled_statistics: false,
statistics_service_url: Url::from_str(STATISTICS_SERVICE_DOMAIN_ADDRESS).expect("Invalid default statistics service URL"),
validator_api_urls: vec![Url::from_str(API_VALIDATOR).expect("Invalid default API URL")],
nym_api_urls: vec![Url::from_str(API_VALIDATOR).expect("Invalid default API URL")],
validator_nymd_urls: vec![Url::from_str(NYMD_VALIDATOR).expect("Invalid default nymd URL")],
cosmos_mnemonic: bip39::Mnemonic::from_str("exact antique hybrid width raise anchor puzzle degree fee quit long crack net vague hip despair write put useless civil mechanic broom music day").unwrap(),
nym_root_directory: Config::default_root_directory(),
+2 -2
View File
@@ -60,8 +60,8 @@ enabled_statistics = {{ gateway.enabled_statistics }}
statistics_service_url = '{{ gateway.statistics_service_url }}'
# Addresses to APIs running on validator from which the node gets the view of the network.
validator_api_urls = [
{{#each gateway.validator_api_urls }}
nym_api_urls = [
{{#each gateway.nym_api_urls }}
'{{this}}',
{{/each}}
]
@@ -56,8 +56,8 @@ pub(crate) enum RequestHandlingError {
APIError(#[from] validator_client::ValidatorClientError),
#[cfg(feature = "coconut")]
#[error("Not enough validator API endpoints provided. Needed {needed}, received {received}")]
NotEnoughValidatorAPIs { received: usize, needed: usize },
#[error("Not enough nym API endpoints provided. Needed {needed}, received {received}")]
NotEnoughNymAPIs { received: usize, needed: usize },
#[cfg(feature = "coconut")]
#[error("There was a problem with the proposal id: {reason}")]
@@ -21,7 +21,7 @@ const ONE_HOUR_SEC: u64 = 3600;
const MAX_FEEGRANT_UNYM: u128 = 10000;
pub(crate) struct CoconutVerifier {
api_clients: Vec<CoconutApiClient>,
nym_api_clients: Vec<CoconutApiClient>,
nymd_client: Client<SigningNymdClient>,
mix_denom_base: String,
aggregated_verification_key: VerificationKey,
@@ -35,13 +35,13 @@ impl CoconutVerifier {
aggregated_verification_key: VerificationKey,
) -> Result<Self, RequestHandlingError> {
if api_clients.is_empty() {
return Err(RequestHandlingError::NotEnoughValidatorAPIs {
return Err(RequestHandlingError::NotEnoughNymAPIs {
received: 0,
needed: 1,
});
}
Ok(CoconutVerifier {
api_clients,
nym_api_clients: api_clients,
nymd_client,
mix_denom_base,
aggregated_verification_key,
@@ -87,12 +87,12 @@ impl CoconutVerifier {
});
}
let req = validator_api_requests::coconut::VerifyCredentialBody::new(
let req = nym_api_requests::coconut::VerifyCredentialBody::new(
credential.clone(),
proposal_id,
self.nymd_client.nymd.address().clone(),
);
for client in self.api_clients.iter() {
for client in self.nym_api_clients.iter() {
self.nymd_client
.nymd
.grant_allowance(
@@ -115,7 +115,7 @@ impl CoconutVerifier {
)
.await?;
if !ret?.verification_result {
debug!("Validator {} didn't accept the credential. It will probably vote No on the spending proposal", client.api_client.validator_api.current_url());
debug!("Validator {} didn't accept the credential. It will probably vote No on the spending proposal", client.api_client.nym_api_client.current_url());
}
}
+3 -3
View File
@@ -231,12 +231,12 @@ where
}
fn random_api_client(&self) -> validator_client::ApiClient {
let endpoints = self.config.get_validator_api_endpoints();
let validator_api = endpoints
let endpoints = self.config.get_nym_api_endpoints();
let nym_api = endpoints
.choose(&mut thread_rng())
.expect("The list of validator apis is empty");
validator_client::ApiClient::new(validator_api.clone())
validator_client::ApiClient::new(nym_api.clone())
}
#[cfg(feature = "coconut")]
+2 -2
View File
@@ -96,10 +96,10 @@ fn override_config(mut config: Config, args: OverrideConfig) -> Config {
}
if let Some(ref raw_validators) = args.validators {
config = config.with_custom_validator_apis(parse_validators(raw_validators));
config = config.with_custom_nym_apis(parse_validators(raw_validators));
} else if std::env::var(CONFIGURED).is_ok() {
if let Some(raw_validators) = read_var_if_not_default(API_VALIDATOR) {
config = config.with_custom_validator_apis(::config::parse_validators(&raw_validators))
config = config.with_custom_nym_apis(::config::parse_validators(&raw_validators))
}
}
+7 -7
View File
@@ -155,8 +155,8 @@ impl Config {
self
}
pub fn with_custom_validator_apis(mut self, validator_api_urls: Vec<Url>) -> Self {
self.mixnode.validator_api_urls = validator_api_urls;
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.mixnode.nym_api_urls = nym_api_urls;
self
}
@@ -233,8 +233,8 @@ impl Config {
self.mixnode.public_sphinx_key_file.clone()
}
pub fn get_validator_api_endpoints(&self) -> Vec<Url> {
self.mixnode.validator_api_urls.clone()
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
self.mixnode.nym_api_urls.clone()
}
pub fn get_node_stats_logging_delay(&self) -> Duration {
@@ -369,8 +369,8 @@ struct MixNode {
/// Path to file containing public sphinx key.
public_sphinx_key_file: PathBuf,
/// Addresses to APIs running on validator from which the node gets the view of the network.
validator_api_urls: Vec<Url>,
/// Addresses to nym APIs from which the node gets the view of the network.
nym_api_urls: Vec<Url>,
/// nym_home_directory specifies absolute path to the home nym MixNodes directory.
/// It is expected to use default value and hence .toml file should not redefine this field.
@@ -412,7 +412,7 @@ impl Default for MixNode {
public_identity_key_file: Default::default(),
private_sphinx_key_file: Default::default(),
public_sphinx_key_file: Default::default(),
validator_api_urls: vec![Url::from_str(API_VALIDATOR).expect("Invalid default API URL")],
nym_api_urls: vec![Url::from_str(API_VALIDATOR).expect("Invalid default API URL")],
nym_root_directory: Config::default_root_directory(),
wallet_address: "nymXXXXXXXX".to_string(),
}
+2 -2
View File
@@ -54,8 +54,8 @@ verloc_port = {{ mixnode.verloc_port }}
http_api_port = {{ mixnode.http_api_port }}
# Addresses to APIs running on validator from which the node gets the view of the network.
validator_api_urls = [
{{#each mixnode.validator_api_urls }}
nym_api_urls = [
{{#each mixnode.nym_api_urls }}
'{{this}}',
{{/each}}
]
+4 -4
View File
@@ -245,7 +245,7 @@ impl MixNode {
.tested_nodes_batch_size(self.config.get_measurement_tested_nodes_batch_size())
.testing_interval(self.config.get_measurement_testing_interval())
.retry_timeout(self.config.get_measurement_retry_timeout())
.validator_api_urls(self.config.get_validator_api_endpoints())
.nym_api_urls(self.config.get_nym_api_endpoints())
.build();
let mut verloc_measurer =
@@ -256,12 +256,12 @@ impl MixNode {
}
fn random_api_client(&self) -> validator_client::ApiClient {
let endpoints = self.config.get_validator_api_endpoints();
let validator_api = endpoints
let endpoints = self.config.get_nym_api_endpoints();
let nym_api = endpoints
.choose(&mut thread_rng())
.expect("The list of validator apis is empty");
validator_client::ApiClient::new(validator_api.clone())
validator_client::ApiClient::new(nym_api.clone())
}
// TODO: ask DH whether this function still makes sense in ^0.10
@@ -84,7 +84,7 @@ nymsphinx = { path = "../common/nymsphinx" }
pemstore = { path = "../common/pemstore", optional = true }
task = { path = "../common/task" }
topology = { path = "../common/topology" }
validator-api-requests = { path = "validator-api-requests" }
nym-api-requests = { path = "nym-api-requests" }
validator-client = { path = "../common/client-libs/validator-client", features = [
"nymd-client",
] }
@@ -97,7 +97,7 @@ coconut = [
"cw3",
"gateway-client/coconut",
"credentials/coconut",
"validator-api-requests/coconut",
"nym-api-requests/coconut",
"nymcoconut",
"coconut-dkg-common",
"dkg",
+1 -1
View File
@@ -5,7 +5,7 @@ use vergen::{vergen, Config};
#[tokio::main]
async fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let database_path = format!("{}/validator-api-example.sqlite", out_dir);
let database_path = format!("{}/nym-api-example.sqlite", out_dir);
let mut conn = SqliteConnection::connect(&format!("sqlite://{}?mode=rwc", database_path))
.await
@@ -1,5 +1,5 @@
[package]
name = "validator-api-requests"
name = "nym-api-requests"
version = "0.1.0"
edition = "2021"
@@ -8,7 +8,7 @@ use coconut_bandwidth_contract_common::events::{
use credentials::coconut::bandwidth::BandwidthVoucher;
use crypto::asymmetric::encryption;
use crypto::asymmetric::identity::{self, Signature};
use validator_api_requests::coconut::BlindSignRequestBody;
use nym_api_requests::coconut::BlindSignRequestBody;
use validator_client::nymd::TxResponse;
use super::error::{CoconutError, Result};
@@ -14,7 +14,7 @@ use crypto::asymmetric::{
use dkg::error::DkgError;
use validator_client::nymd::error::NymdError;
use crate::node_status_api::models::ValidatorApiStorageError;
use crate::node_status_api::models::NymApiStorageError;
pub type Result<T> = std::result::Result<T, CoconutError>;
@@ -77,7 +77,7 @@ pub enum CoconutError {
CoconutInterfaceError(#[from] coconut_interface::error::CoconutInterfaceError),
#[error("Storage error - {0}")]
StorageError(#[from] ValidatorApiStorageError),
StorageError(#[from] NymApiStorageError),
#[error("Credentials error - {0}")]
CredentialsError(#[from] credentials::error::Error),
@@ -13,7 +13,7 @@ pub(crate) mod tests;
use crate::coconut::client::Client as LocalClient;
use crate::coconut::deposit::extract_encryption_key;
use crate::coconut::error::{CoconutError, Result};
use crate::ValidatorApiStorage;
use crate::NymApiStorage;
use coconut_bandwidth_contract_common::spend_credential::{
funds_from_cosmos_msgs, SpendCredentialStatus,
@@ -22,19 +22,19 @@ use coconut_interface::KeyPair as CoconutKeyPair;
use coconut_interface::{
Attribute, BlindSignRequest, BlindedSignature, Parameters, VerificationKey,
};
use config::defaults::VALIDATOR_API_VERSION;
use config::defaults::NYM_API_VERSION;
use credentials::coconut::params::{
ValidatorApiCredentialEncryptionAlgorithm, ValidatorApiCredentialHkdfAlgorithm,
NymApiCredentialEncryptionAlgorithm, NymApiCredentialHkdfAlgorithm,
};
use crypto::asymmetric::encryption;
use crypto::shared_key::new_ephemeral_shared_key;
use crypto::symmetric::stream_cipher;
use keypair::KeyPair;
use validator_api_requests::coconut::{
use nym_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use validator_client::nym_api::routes::{BANDWIDTH, COCONUT_ROUTES};
use validator_client::nymd::{Coin, Fee};
use validator_client::validator_api::routes::{BANDWIDTH, COCONUT_ROUTES};
use getset::{CopyGetters, Getters};
use rand_07::rngs::OsRng;
@@ -51,7 +51,7 @@ pub struct State {
mix_denom: String,
key_pair: KeyPair,
comm_channel: Arc<dyn APICommunicationChannel + Send + Sync>,
storage: ValidatorApiStorage,
storage: NymApiStorage,
rng: Arc<Mutex<OsRng>>,
}
@@ -61,7 +61,7 @@ impl State {
mix_denom: String,
key_pair: KeyPair,
comm_channel: D,
storage: ValidatorApiStorage,
storage: NymApiStorage,
) -> Self
where
C: LocalClient + Send + Sync + 'static,
@@ -100,16 +100,16 @@ impl State {
let (keypair, shared_key) = {
let mut rng = *self.rng.lock().await;
new_ephemeral_shared_key::<
ValidatorApiCredentialEncryptionAlgorithm,
ValidatorApiCredentialHkdfAlgorithm,
NymApiCredentialEncryptionAlgorithm,
NymApiCredentialHkdfAlgorithm,
_,
>(&mut rng, remote_key)
};
let chunk_data = signature.to_bytes();
let zero_iv = stream_cipher::zero_iv::<ValidatorApiCredentialEncryptionAlgorithm>();
let encrypted_data = stream_cipher::encrypt::<ValidatorApiCredentialEncryptionAlgorithm>(
let zero_iv = stream_cipher::zero_iv::<NymApiCredentialEncryptionAlgorithm>();
let encrypted_data = stream_cipher::encrypt::<NymApiCredentialEncryptionAlgorithm>(
&shared_key,
&zero_iv,
&chunk_data,
@@ -169,7 +169,7 @@ impl InternalSignRequest {
mix_denom: String,
key_pair: KeyPair,
comm_channel: D,
storage: ValidatorApiStorage,
storage: NymApiStorage,
) -> AdHoc
where
C: LocalClient + Send + Sync + 'static,
@@ -179,10 +179,7 @@ impl InternalSignRequest {
AdHoc::on_ignite("Internal Sign Request Stage", |rocket| async {
rocket.manage(state).mount(
// this format! is so ugly...
format!(
"/{}/{}/{}",
VALIDATOR_API_VERSION, COCONUT_ROUTES, BANDWIDTH
),
format!("/{}/{}/{}", NYM_API_VERSION, COCONUT_ROUTES, BANDWIDTH),
routes![
post_blind_sign,
post_partial_bandwidth_credential,
@@ -15,26 +15,26 @@ use config::defaults::VOUCHER_INFO;
use cosmwasm_std::{to_binary, Addr, CosmosMsg, Decimal, WasmMsg};
use credentials::coconut::bandwidth::BandwidthVoucher;
use credentials::coconut::params::{
ValidatorApiCredentialEncryptionAlgorithm, ValidatorApiCredentialHkdfAlgorithm,
NymApiCredentialEncryptionAlgorithm, NymApiCredentialHkdfAlgorithm,
};
use crypto::shared_key::recompute_shared_key;
use crypto::symmetric::stream_cipher;
use nym_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use nymcoconut::tests::helpers::theta_from_keys_and_attributes;
use nymcoconut::{
prepare_blind_sign, ttp_keygen, Base58, BlindSignRequest, BlindedSignature, Parameters,
};
use validator_api_requests::coconut::{
BlindSignRequestBody, BlindedSignatureResponse, VerifyCredentialBody, VerifyCredentialResponse,
};
use validator_client::nymd::Coin;
use validator_client::nymd::{tx::Hash, AccountId, DeliverTx, Event, Fee, Tag, TxResponse};
use validator_client::validator_api::routes::{
use validator_client::nym_api::routes::{
API_VERSION, BANDWIDTH, COCONUT_BLIND_SIGN, COCONUT_PARTIAL_BANDWIDTH_CREDENTIAL,
COCONUT_ROUTES, COCONUT_VERIFY_BANDWIDTH_CREDENTIAL,
};
use validator_client::nymd::Coin;
use validator_client::nymd::{tx::Hash, AccountId, DeliverTx, Event, Fee, Tag, TxResponse};
use crate::coconut::State;
use crate::ValidatorApiStorage;
use crate::NymApiStorage;
use async_trait::async_trait;
use coconut_dkg_common::dealer::{
ContractDealing, DealerDetails, DealerDetailsResponse, DealerType,
@@ -456,7 +456,7 @@ async fn signed_before() {
let key_pair = ttp_keygen(&params, 1, 1).unwrap().remove(0);
let mut db_dir = std::env::temp_dir();
db_dir.push(&key_pair.verification_key().to_bs58()[..8]);
let storage = ValidatorApiStorage::init(db_dir).await.unwrap();
let storage = NymApiStorage::init(db_dir).await.unwrap();
let tx_db = Arc::new(RwLock::new(HashMap::new()));
tx_db
.write()
@@ -532,7 +532,7 @@ async fn state_functions() {
let key_pair = ttp_keygen(&params, 1, 1).unwrap().remove(0);
let mut db_dir = std::env::temp_dir();
db_dir.push(&key_pair.verification_key().to_bs58()[..8]);
let storage = ValidatorApiStorage::init(db_dir).await.unwrap();
let storage = NymApiStorage::init(db_dir).await.unwrap();
let comm_channel = DummyCommunicationChannel::new(key_pair.verification_key());
let staged_key_pair = crate::coconut::KeyPair::new();
staged_key_pair.set(key_pair).await;
@@ -601,11 +601,11 @@ async fn state_functions() {
crypto::asymmetric::encryption::PublicKey::from_bytes(&response.remote_key).unwrap();
let encryption_key = recompute_shared_key::<
ValidatorApiCredentialEncryptionAlgorithm,
ValidatorApiCredentialHkdfAlgorithm,
NymApiCredentialEncryptionAlgorithm,
NymApiCredentialHkdfAlgorithm,
>(&remote_key, encryption_keypair.private_key());
let zero_iv = stream_cipher::zero_iv::<ValidatorApiCredentialEncryptionAlgorithm>();
let blinded_signature_bytes = stream_cipher::decrypt::<ValidatorApiCredentialEncryptionAlgorithm>(
let zero_iv = stream_cipher::zero_iv::<NymApiCredentialEncryptionAlgorithm>();
let blinded_signature_bytes = stream_cipher::decrypt::<NymApiCredentialEncryptionAlgorithm>(
&encryption_key,
&zero_iv,
&response.encrypted_signature,
@@ -665,7 +665,7 @@ async fn blind_sign_correct() {
let key_pair = ttp_keygen(&params, 1, 1).unwrap().remove(0);
let mut db_dir = std::env::temp_dir();
db_dir.push(&key_pair.verification_key().to_bs58()[..8]);
let storage = ValidatorApiStorage::init(db_dir).await.unwrap();
let storage = NymApiStorage::init(db_dir).await.unwrap();
let tx_db = Arc::new(RwLock::new(HashMap::new()));
let mut tx_entry = tx_entry_fixture(&tx_hash.to_string());
@@ -776,7 +776,7 @@ async fn signature_test() {
let key_pair = ttp_keygen(&params, 1, 1).unwrap().remove(0);
let mut db_dir = std::env::temp_dir();
db_dir.push(&key_pair.verification_key().to_bs58()[..8]);
let storage = ValidatorApiStorage::init(db_dir).await.unwrap();
let storage = NymApiStorage::init(db_dir).await.unwrap();
let nymd_client =
DummyClient::new(AccountId::from_str(TEST_REWARDING_VALIDATOR_ADDRESS).unwrap());
let comm_channel = DummyCommunicationChannel::new(key_pair.verification_key());
@@ -865,7 +865,7 @@ async fn verification_of_bandwidth_credential() {
theta_from_keys_and_attributes(&params, &key_pairs, &indices, &public_attributes).unwrap();
let key_pair = key_pairs.remove(0);
db_dir.push(&key_pair.verification_key().to_bs58()[..8]);
let storage1 = ValidatorApiStorage::init(db_dir).await.unwrap();
let storage1 = NymApiStorage::init(db_dir).await.unwrap();
let comm_channel = DummyCommunicationChannel::new(key_pair.verification_key());
let staged_key_pair = crate::coconut::KeyPair::new();
staged_key_pair.set(key_pair).await;
@@ -3,7 +3,7 @@
use crate::config::template::config_template;
use config::defaults::mainnet::MIXNET_CONTRACT_ADDRESS;
use config::defaults::DEFAULT_VALIDATOR_API_PORT;
use config::defaults::DEFAULT_NYM_API_PORT;
use config::NymConfig;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
@@ -67,11 +67,11 @@ impl NymConfig for Config {
dirs::home_dir()
.expect("Failed to evaluate $HOME value")
.join(".nym")
.join("validator-api")
.join("nym-api")
}
fn try_default_root_directory() -> Option<PathBuf> {
dirs::home_dir().map(|path| path.join(".nym").join("validator-api"))
dirs::home_dir().map(|path| path.join(".nym").join("nym-api"))
}
fn root_directory(&self) -> PathBuf {
@@ -90,7 +90,7 @@ impl NymConfig for Config {
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(default)]
pub struct Base {
/// ID specifies the human readable ID of this particular validator-api.
/// ID specifies the human readable ID of this particular nym-api.
id: String,
local_validator: Url,
@@ -114,7 +114,7 @@ impl Default for Base {
.expect("default local validator is malformed!");
let mut default_announce_address = default_validator.clone();
default_announce_address
.set_port(Some(DEFAULT_VALIDATOR_API_PORT))
.set_port(Some(DEFAULT_NYM_API_PORT))
.expect("default local validator is malformed!");
Base {
id: String::default(),
@@ -6,11 +6,11 @@ pub(crate) fn config_template() -> &'static str {
# This is a TOML config file.
# For more information, see https://github.com/toml-lang/toml
##### main base validator-api config options #####
##### main base nym-api config options #####
[base]
# ID specifies the human readable ID of this particular validator-api.
# ID specifies the human readable ID of this particular nym-api.
id = '{{ base.id }}'
# Validator server to which the API will be getting information about the network.
@@ -9,6 +9,7 @@ use mixnet_contract_common::{
mixnode::MixNodeDetails, reward_params::RewardingParams, GatewayBond, IdentityKey, Interval,
MixId, MixNodeBond, RewardedSetNodeStatus,
};
use nym_api_requests::models::MixnodeStatus;
use okapi::openapi3::OpenApi;
use rocket::fairing::AdHoc;
use rocket::Route;
@@ -23,7 +24,6 @@ use std::time::Duration;
use task::ShutdownListener;
use tokio::sync::{watch, RwLock};
use tokio::time;
use validator_api_requests::models::MixnodeStatus;
use validator_client::nymd::CosmWasmClient;
pub(crate) mod routes;
@@ -11,7 +11,7 @@ use crate::{
use mixnet_contract_common::{
mixnode::MixNodeDetails, reward_params::RewardingParams, GatewayBond, Interval, MixId,
};
use validator_api_requests::models::MixNodeBondAnnotated;
use nym_api_requests::models::MixNodeBondAnnotated;
use rocket::{serde::json::Json, State};
use rocket_okapi::openapi;
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::node_status_api::models::ValidatorApiStorageError;
use crate::node_status_api::models::NymApiStorageError;
use thiserror::Error;
use validator_client::nymd::error::NymdError;
use validator_client::ValidatorClientError;
@@ -15,7 +15,7 @@ pub enum RewardingError {
// The inner error should be modified at some point...
#[error("We run into storage issues - {0}")]
StorageError(ValidatorApiStorageError),
StorageError(NymApiStorageError),
#[error("Failed to query the smart contract - {0}")]
ValidatorClientError(ValidatorClientError),
@@ -38,8 +38,8 @@ impl From<NymdError> for RewardingError {
}
}
impl From<ValidatorApiStorageError> for RewardingError {
fn from(err: ValidatorApiStorageError) -> Self {
impl From<NymApiStorageError> for RewardingError {
fn from(err: NymApiStorageError) -> Self {
RewardingError::StorageError(err)
}
}
@@ -15,7 +15,7 @@
use crate::contract_cache::ValidatorCache;
use crate::nymd_client::Client;
use crate::storage::models::RewardingReport;
use crate::storage::ValidatorApiStorage;
use crate::storage::NymApiStorage;
use mixnet_contract_common::families::FamilyHead;
use mixnet_contract_common::{
reward_params::Performance, CurrentIntervalResponse, ExecuteMsg, Interval, MixId,
@@ -56,7 +56,7 @@ impl From<MixnodeToReward> for ExecuteMsg {
pub struct RewardedSetUpdater {
nymd_client: Client<SigningNymdClient>,
validator_cache: ValidatorCache,
storage: ValidatorApiStorage,
storage: NymApiStorage,
}
// Weight of a layer being chose is reciprocal to current count in layer
@@ -79,7 +79,7 @@ impl RewardedSetUpdater {
pub(crate) async fn new(
nymd_client: Client<SigningNymdClient>,
validator_cache: ValidatorCache,
storage: ValidatorApiStorage,
storage: NymApiStorage,
) -> Result<Self, RewardingError> {
Ok(RewardedSetUpdater {
nymd_client,
@@ -9,7 +9,7 @@ use crate::contract_cache::ValidatorCacheRefresher;
use crate::network_monitor::NetworkMonitorBuilder;
use crate::node_status_api::uptime_updater::HistoricalUptimeUpdater;
use crate::nymd_client::Client;
use crate::storage::ValidatorApiStorage;
use crate::storage::NymApiStorage;
use ::config::defaults::mainnet::read_var_if_not_default;
use ::config::defaults::setup_env;
use ::config::defaults::var_names::{CONFIGURED, MIXNET_CONTRACT_ADDRESS, MIX_DENOM};
@@ -113,20 +113,20 @@ fn long_version() -> String {
fn parse_args() -> ArgMatches {
let build_details = long_version();
let base_app = App::new("Nym Validator API")
let base_app = App::new("Nym API")
.version(crate_version!())
.long_version(&*build_details)
.author("Nymtech")
.arg(
Arg::with_name(CONFIG_ENV_FILE)
.help("Path pointing to an env file that configures the validator API")
.help("Path pointing to an env file that configures the Nym API")
.long(CONFIG_ENV_FILE)
.short('c')
.takes_value(true)
)
.arg(
Arg::with_name(ID)
.help("Id of the validator-api we want to run")
.help("Id of the nym-api we want to run")
.long(ID)
.takes_value(true)
)
@@ -145,13 +145,13 @@ fn parse_args() -> ArgMatches {
)
.arg(
Arg::with_name(NYMD_VALIDATOR_ARG)
.help("Endpoint to nymd part of the validator from which the monitor will grab nodes to test")
.help("Endpoint to nymd instance from which the monitor will grab nodes to test")
.long(NYMD_VALIDATOR_ARG)
.takes_value(true)
)
.arg(Arg::with_name(MIXNET_CONTRACT_ARG)
.long(MIXNET_CONTRACT_ARG)
.help("Address of the validator contract managing the network")
.help("Address of the mixnet contract managing the network")
.takes_value(true),
)
.arg(Arg::with_name(MNEMONIC_ARG)
@@ -174,19 +174,19 @@ fn parse_args() -> ArgMatches {
.arg(
Arg::with_name(MIN_MIXNODE_RELIABILITY_ARG)
.long(MIN_MIXNODE_RELIABILITY_ARG)
.help("Mixnodes with relialability lower the this get blacklisted by network monitor, get no traffic and cannot be selected into a rewarded set.")
.help("Mixnodes with reliability lower the this get blacklisted by network monitor, get no traffic and cannot be selected into a rewarded set.")
.takes_value(true)
)
.arg(
Arg::with_name(MIN_GATEWAY_RELIABILITY_ARG)
.long(MIN_GATEWAY_RELIABILITY_ARG)
.help("Gateways with relialability lower the this get blacklisted by network monitor, get no traffic and cannot be selected into a rewarded set.")
.help("Gateways with reliability lower the this get blacklisted by network monitor, get no traffic and cannot be selected into a rewarded set.")
.takes_value(true)
)
.arg(
Arg::with_name(ENABLED_CREDENTIALS_MODE_ARG_NAME)
.long(ENABLED_CREDENTIALS_MODE_ARG_NAME)
.help("Set this validator api to work in a enabled credentials that would attempt to use gateway with the bandwidth credential requirement")
.help("Set this nym api to work in a enabled credentials that would attempt to use gateway with the bandwidth credential requirement")
);
#[cfg(feature = "coconut")]
@@ -215,7 +215,7 @@ async fn wait_for_interrupt(mut shutdown: ShutdownNotifier) {
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
shutdown.wait_for_shutdown().await;
log::info!("Stopping nym validator API");
log::info!("Stopping nym API");
}
#[cfg(unix)]
@@ -380,7 +380,7 @@ fn setup_network_monitor<'a>(
}
// get instances of managed states
let node_status_storage = rocket.state::<ValidatorApiStorage>().unwrap().clone();
let node_status_storage = rocket.state::<NymApiStorage>().unwrap().clone();
let validator_cache = rocket.state::<ValidatorCache>().unwrap().clone();
Some(NetworkMonitorBuilder::new(
@@ -433,7 +433,7 @@ async fn setup_rocket(
// This is not a very nice approach. A lazy value would be more suitable, but that's still
// a nightly feature: https://github.com/rust-lang/rust/issues/74465
let storage = if cfg!(feature = "coconut") || config.get_network_monitor_enabled() {
Some(ValidatorApiStorage::init(config.get_node_status_api_database_path()).await?)
Some(NymApiStorage::init(config.get_node_status_api_database_path()).await?)
} else {
None
};
@@ -453,7 +453,7 @@ async fn setup_rocket(
// see if we should start up network monitor
let rocket = if config.get_network_monitor_enabled() {
rocket.attach(storage::ValidatorApiStorage::stage(storage.unwrap()))
rocket.attach(storage::NymApiStorage::stage(storage.unwrap()))
} else {
rocket
};
@@ -490,7 +490,7 @@ fn get_servers() -> Vec<rocket_okapi::okapi::openapi3::Server> {
}]
}
async fn run_validator_api(matches: ArgMatches) -> Result<()> {
async fn run_nym_api(matches: ArgMatches) -> Result<()> {
let system_version = env!("CARGO_PKG_VERSION");
// try to load config from the file, if it doesn't exist, use default values
@@ -565,7 +565,7 @@ async fn run_validator_api(matches: ArgMatches) -> Result<()> {
// we're not starting signing client
let validator_cache_listener = if config.get_network_monitor_enabled() {
// Main storage
let storage = rocket.state::<ValidatorApiStorage>().unwrap().clone();
let storage = rocket.state::<NymApiStorage>().unwrap().clone();
// setup our daily uptime updater. Note that if network monitor is disabled, then we have
// no data for the updates and hence we don't need to start it up
@@ -610,8 +610,8 @@ async fn run_validator_api(matches: ArgMatches) -> Result<()> {
// Spawn the node status cache refresher.
// It is primarily refreshed in-sync with the validator cache, however provide a fallback
// caching interval that is twice the validator cache
let storage = rocket.state::<ValidatorApiStorage>().cloned();
let mut validator_api_cache_refresher = node_status_api::NodeStatusCacheRefresher::new(
let storage = rocket.state::<NymApiStorage>().cloned();
let mut nym_api_cache_refresher = node_status_api::NodeStatusCacheRefresher::new(
node_status_cache,
config.get_caching_interval().saturating_mul(2),
validator_cache,
@@ -619,12 +619,12 @@ async fn run_validator_api(matches: ArgMatches) -> Result<()> {
storage,
);
let shutdown_listener = shutdown.subscribe();
tokio::spawn(async move { validator_api_cache_refresher.run(shutdown_listener).await });
tokio::spawn(async move { nym_api_cache_refresher.run(shutdown_listener).await });
// launch the rocket!
// Rocket handles shutdown on it's own, but its shutdown handling should be incorporated
// with that of the rest of the tasks.
// Currently it's runtime is forcefully terminated once the validator-api exits.
// Currently it's runtime is forcefully terminated once the nym-api exits.
let shutdown_handle = rocket.shutdown();
tokio::spawn(rocket.launch());
@@ -663,5 +663,5 @@ async fn main() -> Result<()> {
.value_of(CONFIG_ENV_FILE)
.map(|s| PathBuf::from_str(s).expect("invalid env config file"));
setup_env(config_env_file);
run_validator_api(args).await
run_nym_api(args).await
}

Some files were not shown because too many files have changed in this diff Show More