Feature/rewarding revamp (#1472)
* Query for node stake saturation * Queries for currently pending events * Rewarded set query * Moved ContractState to common types since it's being returned as a result of one of the queries on the mixnet contract and thus it needs to be accessible outside the contract itself * Cleaend up storage initialisation * started restoring unit tests * Removed attached 1ucoin for cross-contract execute msgs * wip * query for rewarding details of a mix node * Changes for mixnodes and gateways * Furher progress on v2 changelog(-ish) description * wip * first version of the description * mixnode bonding queries tests and fixes * ibid for storage * MixnodeEventType enum + created events for missing mixnode txs * tests for adding new mixnode * Additional mixnode-related tests + bug fixes * Display for Percent * Bunch of tests for try_reward_mixnode * More tests and fixes * ibid * tests for updating rewarding params + important bug fix * Started removing unused imports * rewarding queries tests + undelegation bugfix * A lot of todo()-ing and commenting out unimplemented code * implements https://github.com/nymtech/team-core/issues/113 * Delegation tests + fixes * Emiting events by top level interval txs + incorporating limit * question * Missing events emissions * removed some code duplication * wip * pending delegation tests * Vesting contract update * More tests (and fixes) for pending events txs * Restored gateway tx tests * Another cleanup iteration * removed redundant comment * Unit tests, fixes and simplifcations for interval-related txs * Unit tests for helper functions * Interval queries unit tests * Test for correct contract initialisation * Another round of cleanup * Work on mixnet_query_client trait * mixnet_signing_client trait * Removed redundant methods * Slowly restoring validator client functionality * Added deprecated query for mix details by identity * wip restoration of validator-api * Work on deprecating validator API routes * Further validator-api routes * Restored rest of status api routes * Resolved all todos in ValidatorApiStorage There's still bunch left in StorageManager though * Changed NodeId from u64 to u32 * Updating sql code * Network monitor internals * Changed behaviour of full_epoch_id and updated epoch operations * Fixed sql queries * [most likely] finished updating rest of the validator API * Post rebasing fixes * Feature/rewarding revamp explorer api changes (#1511) * Changed cache to allow for non-string keys * Helper method for best-effort conversion of pubkey to nodeid * Updated validator-api client routes * Updated routes to use mix-id indexing * Introduction of deprecated routes callable by identity key * Fixed mixnode compatibility by changing read node details fields (#1512) * Fixed bond to topology conversion for client compatibility (#1513) * Updated 'verify_gateway_owner' to use correct nymd_client method for obtaining gateway details (#1515) * Updated constructor for ValidatorCacheInner * Fixed wasm client topology construction * Run cargo fmt on the entire codebase * Feature/rewarding revamp wallet backend changes (#1529) * Updated mixnode-related ts types * Updated nym-wallet-types * Updated 'get_contract_settings' and commented out code of other tauri commands * 'update_contract_settings' * 'bond_gateway' * unbond_gateway' * Utility commands for the transition period * 'bond_mixnode' * 'unbond_mixnode' * Ability to update mixnode cost paramaters * Mixnode config update * Updated mixnode_bond_details It also returns a different underlying type now * Updated 'gateway_bond_details' * Obtaining pending operator rewards * Improved way of obtaining number of mixnode delegators * simplified error handling in 'fetch_mix_node_description' * mixnode and gateway ownership queries * updated get_number_of_mixnode_delegators to use mix_id since we have the conversion utils helper * mixnode delegation * undelegating * Obtaining pending delegator rewards * Command for obtaining current interval details * Queries to handle paging for pending events * Additional level of indirection to pending events to incorporate event id into response * Wallet compatible pending event types * Commands fo obtaining pending events * Re-implemented pending delegation events * Further work on delegation * Removed unused imports * Commands for withdrawing rewards * Admin-related simulations * mixnet-related simulation commands * Validator-api related routes * Bond-related vesting operations * Vesting simulations * Vesting handler for UpdateMixnodeCostParams * Vesting reward claiming * Vesting queries * claim_locked_and_unlocked_delegator_reward * The massive delegation query * cleanup * updated typescript requests * sorted the new type exports in ts-rs-cli * Regenerated typescript types * temporarily ignoring unreachable code in vesting migration * Updated missed test fixture * Fixed missing coconut-specific import * cargo fmt * Exporting reward-related types * utility to convert stringified decimal to cosmjs Decimal * deriving Eq alongside PartialEq * wip - typescript fixes * using default operating cost when bonding mixnode * Using default operating cost when updating mixnode cost params * most delegation fixes * Wrapping delegation with node identity * Added MultiIndex on owner and identity key to unbonded mixnodes * Support for queries for unbonded nodes by owner or by identity key * Cargo fmt + ts types update * feature locking unused imports * fix(nym-wallet): typing and error (#1548) * post-rebase fixes * Changed storage key for new delegations map in vesting contract * fix(wallet): typing issues (#1562) * fix(wallet): error UI feedback (#1565) * clean(wallet): remove useless files (with flamethrowers 🔥) (#1567) * Changed default_mixnode_cost_params to allow accepting f32 instead * Revert "Changed default_mixnode_cost_params to allow accepting f32 instead" This reverts commitfb62a0014f. * Fixed APY calculation for 0 pledge value * Don't send rewarding transactions for empty rewarded set * Fixed mixnode rewarding in validator API * fix(nym-wallet): profit margin (#1574) * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * Removed todo!() from vesting contract migration since its going to be dealt with differently * fix(nym-wallet): stake saturation and delegations (#1578) * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): stake saturation percentage * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * fix(nym-wallet): get rid of delegation history * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * fix(nym-wallet): welcome back pending events and delegation menu * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): get rid of delegation history * Updated typescript side of things * fix(nym-wallet): welcome back pending events and delegation menu * fix(nym-wallet): fix clippy Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com> * Updated vesting contract migration to update the mixnet contract address * feat(wallet): add confirmation/warning modal for unbonding * Post rebasing fixes * commented out all code * Bunch of work in progres, but working simulator * Removing redundant fields + increased precision to 9decimal places * deserialization of Percent with value validation * wip * Further moving things around + mixnode bonding * Mixnode unbonding * Starting restoration on contract state * Revamping interval * More work on epoch/interval * progress on mixnode rewarding * Moved MixNodeRewarding to rewards storage * wip on delegations * Removed concept of periods and historical records and moved cummulative reward ratio directly to delegation * more wip delegation * Full delegation flow * mixnode config updates * Mixnode cost function updates * Work on moving mixnode unbonding to post-epoch actions * Unbonding * Processing undelegation * changing cost params * Uncommented existing gateways features without much changes so far, however, things like unbonding should probably also go to epoch queue * ExecuteMsg cleanup * unit tests for withdrawing rewards against known values * Transactions for withdrawing rewards * Transactions for updating various parameters * First round of post-tx cleanup * Moved all storage keys to constants.rs * Using correct initial gateway pledge amount * Renamed sybil_resistance_percent to sybil_resistance with percent being implicit from the typ * Starting with contract queries * Keeping minimal details of unbonded mixnoces * Checking for owner address rather than rewarding validator when updating rewarding params * Mixnode-related queries * Gateway-related queries * Query for paged unbonded mixnodes * Delegations queries * Query for current interval details * Removed 'fixed' dependency from the mixnet common * wip on implementing rewards-related queries * Pending rewards queries * Query for node stake saturation * Queries for currently pending events * Rewarded set query * Moved ContractState to common types since it's being returned as a result of one of the queries on the mixnet contract and thus it needs to be accessible outside the contract itself * Cleaend up storage initialisation * started restoring unit tests * Removed attached 1ucoin for cross-contract execute msgs * wip * query for rewarding details of a mix node * Changes for mixnodes and gateways * Furher progress on v2 changelog(-ish) description * wip * first version of the description * mixnode bonding queries tests and fixes * ibid for storage * MixnodeEventType enum + created events for missing mixnode txs * tests for adding new mixnode * Additional mixnode-related tests + bug fixes * Display for Percent * Bunch of tests for try_reward_mixnode * More tests and fixes * ibid * tests for updating rewarding params + important bug fix * Started removing unused imports * rewarding queries tests + undelegation bugfix * A lot of todo()-ing and commenting out unimplemented code * implements https://github.com/nymtech/team-core/issues/113 * Delegation tests + fixes * Emiting events by top level interval txs + incorporating limit * question * Missing events emissions * removed some code duplication * wip * pending delegation tests * Vesting contract update * More tests (and fixes) for pending events txs * Restored gateway tx tests * Another cleanup iteration * removed redundant comment * Unit tests, fixes and simplifcations for interval-related txs * Unit tests for helper functions * Interval queries unit tests * Test for correct contract initialisation * Another round of cleanup * Work on mixnet_query_client trait * mixnet_signing_client trait * Removed redundant methods * Slowly restoring validator client functionality * Added deprecated query for mix details by identity * wip restoration of validator-api * Work on deprecating validator API routes * Further validator-api routes * Restored rest of status api routes * Resolved all todos in ValidatorApiStorage There's still bunch left in StorageManager though * Changed NodeId from u64 to u32 * Updating sql code * Network monitor internals * Changed behaviour of full_epoch_id and updated epoch operations * Fixed sql queries * [most likely] finished updating rest of the validator API * Post rebasing fixes * Feature/rewarding revamp explorer api changes (#1511) * Changed cache to allow for non-string keys * Helper method for best-effort conversion of pubkey to nodeid * Updated validator-api client routes * Updated routes to use mix-id indexing * Introduction of deprecated routes callable by identity key * Fixed mixnode compatibility by changing read node details fields (#1512) * Fixed bond to topology conversion for client compatibility (#1513) * Updated 'verify_gateway_owner' to use correct nymd_client method for obtaining gateway details (#1515) * Updated constructor for ValidatorCacheInner * Fixed wasm client topology construction * Run cargo fmt on the entire codebase * Feature/rewarding revamp wallet backend changes (#1529) * Updated mixnode-related ts types * Updated nym-wallet-types * Updated 'get_contract_settings' and commented out code of other tauri commands * 'update_contract_settings' * 'bond_gateway' * unbond_gateway' * Utility commands for the transition period * 'bond_mixnode' * 'unbond_mixnode' * Ability to update mixnode cost paramaters * Mixnode config update * Updated mixnode_bond_details It also returns a different underlying type now * Updated 'gateway_bond_details' * Obtaining pending operator rewards * Improved way of obtaining number of mixnode delegators * simplified error handling in 'fetch_mix_node_description' * mixnode and gateway ownership queries * updated get_number_of_mixnode_delegators to use mix_id since we have the conversion utils helper * mixnode delegation * undelegating * Obtaining pending delegator rewards * Command for obtaining current interval details * Queries to handle paging for pending events * Additional level of indirection to pending events to incorporate event id into response * Wallet compatible pending event types * Commands fo obtaining pending events * Re-implemented pending delegation events * Further work on delegation * Removed unused imports * Commands for withdrawing rewards * Admin-related simulations * mixnet-related simulation commands * Validator-api related routes * Bond-related vesting operations * Vesting simulations * Vesting handler for UpdateMixnodeCostParams * Vesting reward claiming * Vesting queries * claim_locked_and_unlocked_delegator_reward * The massive delegation query * cleanup * updated typescript requests * sorted the new type exports in ts-rs-cli * Regenerated typescript types * temporarily ignoring unreachable code in vesting migration * Updated missed test fixture * Fixed missing coconut-specific import * cargo fmt * Exporting reward-related types * utility to convert stringified decimal to cosmjs Decimal * deriving Eq alongside PartialEq * wip - typescript fixes * using default operating cost when bonding mixnode * Using default operating cost when updating mixnode cost params * most delegation fixes * Wrapping delegation with node identity * Added MultiIndex on owner and identity key to unbonded mixnodes * Support for queries for unbonded nodes by owner or by identity key * Cargo fmt + ts types update * feature locking unused imports * fix(nym-wallet): typing and error (#1548) * post-rebase fixes * Changed storage key for new delegations map in vesting contract * fix(wallet): typing issues (#1562) * fix(wallet): error UI feedback (#1565) * clean(wallet): remove useless files (with flamethrowers 🔥) (#1567) * Changed default_mixnode_cost_params to allow accepting f32 instead * Revert "Changed default_mixnode_cost_params to allow accepting f32 instead" This reverts commitfb62a0014f. * Fixed APY calculation for 0 pledge value * Don't send rewarding transactions for empty rewarded set * Fixed mixnode rewarding in validator API * fix(nym-wallet): profit margin (#1574) * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * Removed todo!() from vesting contract migration since its going to be dealt with differently * fix(nym-wallet): stake saturation and delegations (#1578) * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): stake saturation percentage * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * fix(nym-wallet): get rid of delegation history * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * Correctly assigning Delegate event type to PendingEpochEventData::Delegate * Replaced 'history' in with 'pending_events' in DelegationWithEverything * Updated typescript side of things * fix(nym-wallet): welcome back pending events and delegation menu * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): stake saturation percentage * fix(nym-wallet): get rid of delegation history * Updated typescript side of things * fix(nym-wallet): welcome back pending events and delegation menu * fix(nym-wallet): fix clippy Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com> * Updated vesting contract migration to update the mixnet contract address * feat(wallet): add confirmation/warning modal for unbonding * Post rebasing fixes * Removed deprecation on GetMixnodeDetailsByIdentity * Fixed nym-cli * Removed needless borrow * Updated colorMap and textMap Co-authored-by: durch <durch@users.noreply.github.com> Co-authored-by: Mark Sinclair <mmsinclair@gmail.com> Co-authored-by: Pierre Dommerc <dommerc.pierre@gmail.com>
This commit is contained in:
committed by
GitHub
parent
ecbf5296a5
commit
136666d759
@@ -1,22 +1,20 @@
|
||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::contract_cache::{Cache, CacheNotification, ValidatorCache};
|
||||
use mixnet_contract_common::rewarding::helpers::truncate_decimal;
|
||||
use mixnet_contract_common::{MixNodeDetails, NodeId, RewardingParams};
|
||||
use rocket::fairing::AdHoc;
|
||||
use serde::Serialize;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tap::TapFallible;
|
||||
use task::ShutdownListener;
|
||||
use tokio::{
|
||||
sync::{watch, RwLock},
|
||||
time,
|
||||
};
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use mixnet_contract_common::{reward_params::EpochRewardParams, MixNodeBond};
|
||||
use task::ShutdownListener;
|
||||
use validator_api_requests::models::InclusionProbability;
|
||||
|
||||
use crate::contract_cache::{Cache, CacheNotification, ValidatorCache};
|
||||
|
||||
const CACHE_TIMOUT_MS: u64 = 100;
|
||||
const MAX_SIMULATION_SAMPLES: u64 = 5000;
|
||||
const MAX_SIMULATION_TIME_SEC: u64 = 15;
|
||||
@@ -48,8 +46,8 @@ pub(crate) struct InclusionProbabilities {
|
||||
}
|
||||
|
||||
impl InclusionProbabilities {
|
||||
pub fn node(&self, id: &str) -> Option<&InclusionProbability> {
|
||||
self.inclusion_probabilities.iter().find(|x| x.id == id)
|
||||
pub fn node(&self, mix_id: NodeId) -> Option<&InclusionProbability> {
|
||||
self.inclusion_probabilities.iter().find(|x| x.id == mix_id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,7 +175,12 @@ impl NodeStatusCacheRefresher {
|
||||
async fn refresh_cache(&self) -> Result<(), NodeStatusCacheError> {
|
||||
log::info!("Updating node status cache");
|
||||
let mixnode_bonds = self.contract_cache.mixnodes().await;
|
||||
let params = self.contract_cache.epoch_reward_params().await.into_inner();
|
||||
let params = self
|
||||
.contract_cache
|
||||
.interval_reward_params()
|
||||
.await
|
||||
.into_inner()
|
||||
.ok_or(NodeStatusCacheError::SimulationFailed)?;
|
||||
let inclusion_probabilities = compute_inclusion_probabilities(&mixnode_bonds, params)
|
||||
.ok_or_else(|| {
|
||||
error!(
|
||||
@@ -192,30 +195,23 @@ impl NodeStatusCacheRefresher {
|
||||
}
|
||||
|
||||
fn compute_inclusion_probabilities(
|
||||
mixnode_bonds: &[MixNodeBond],
|
||||
params: EpochRewardParams,
|
||||
mixnodes: &[MixNodeDetails],
|
||||
params: RewardingParams,
|
||||
) -> Option<InclusionProbabilities> {
|
||||
let active_set_size = params
|
||||
.active_set_size()
|
||||
.try_into()
|
||||
.tap_err(|e| error!("Active set size unexpectantly large: {e}"))
|
||||
.ok()?;
|
||||
let standby_set_size = (params.rewarded_set_size() - params.active_set_size())
|
||||
.try_into()
|
||||
.tap_err(|e| error!("Active set size larger than rewarded set size, a contradiction: {e}"))
|
||||
.ok()?;
|
||||
let active_set_size = params.active_set_size;
|
||||
let standby_set_size = params.rewarded_set_size - active_set_size;
|
||||
|
||||
// Unzip list of total bonds into ids and bonds.
|
||||
// We need to go through this zip/unzip procedure to make sure we have matching identities
|
||||
// for the input to the simulator, which assumes the identity is the position in the vec
|
||||
let (ids, mixnode_total_bonds) = unzip_into_mixnode_ids_and_total_bonds(mixnode_bonds);
|
||||
let (ids, mixnode_total_bonds) = unzip_into_mixnode_ids_and_total_bonds(mixnodes);
|
||||
|
||||
// Compute inclusion probabilitites and keep track of how long time it took.
|
||||
let mut rng = rand::thread_rng();
|
||||
let results = inclusion_probability::simulate_selection_probability_mixnodes(
|
||||
&mixnode_total_bonds,
|
||||
active_set_size,
|
||||
standby_set_size,
|
||||
active_set_size as usize,
|
||||
standby_set_size as usize,
|
||||
MAX_SIMULATION_SAMPLES,
|
||||
Duration::from_secs(MAX_SIMULATION_TIME_SEC),
|
||||
&mut rng,
|
||||
@@ -232,24 +228,22 @@ fn compute_inclusion_probabilities(
|
||||
})
|
||||
}
|
||||
|
||||
fn unzip_into_mixnode_ids_and_total_bonds(
|
||||
mixnode_bonds: &[MixNodeBond],
|
||||
) -> (Vec<&String>, Vec<u128>) {
|
||||
mixnode_bonds
|
||||
fn unzip_into_mixnode_ids_and_total_bonds(mixnodes: &[MixNodeDetails]) -> (Vec<NodeId>, Vec<u128>) {
|
||||
mixnodes
|
||||
.iter()
|
||||
.filter_map(|m| m.total_bond().map(|b| (m.identity(), b)))
|
||||
.map(|m| (m.mix_id(), truncate_decimal(m.total_stake()).u128()))
|
||||
.unzip()
|
||||
}
|
||||
|
||||
fn zip_ids_together_with_results(
|
||||
ids: &[&String],
|
||||
ids: &[NodeId],
|
||||
results: &inclusion_probability::SelectionProbability,
|
||||
) -> Vec<InclusionProbability> {
|
||||
ids.iter()
|
||||
.zip(results.active_set_probability.iter())
|
||||
.zip(results.reserve_set_probability.iter())
|
||||
.map(|((id, a), r)| InclusionProbability {
|
||||
id: (*id).to_string(),
|
||||
.map(|((&id, a), r)| InclusionProbability {
|
||||
id,
|
||||
in_active: *a,
|
||||
in_reserve: *r,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::node_status_api::helpers::{
|
||||
_compute_mixnode_reward_estimation, _get_mixnode_avg_uptime,
|
||||
_get_mixnode_inclusion_probability, _get_mixnode_reward_estimation,
|
||||
_get_mixnode_stake_saturation, _get_mixnode_status, _mixnode_core_status_count,
|
||||
_mixnode_report, _mixnode_uptime_history,
|
||||
};
|
||||
use crate::node_status_api::models::{ErrorResponse, MixnodeStatusReport, MixnodeUptimeHistory};
|
||||
use crate::{NodeStatusCache, ValidatorApiStorage, ValidatorCache};
|
||||
use mixnet_contract_common::NodeId;
|
||||
use rocket::http::Status;
|
||||
use rocket::serde::json::Json;
|
||||
use rocket::State;
|
||||
use rocket_okapi::openapi;
|
||||
use validator_api_requests::models::{
|
||||
DeprecatedComputeRewardEstParam, DeprecatedRewardEstimationResponse, DeprecatedUptimeResponse,
|
||||
InclusionProbabilityResponse, MixnodeCoreStatusResponse, MixnodeStatus, MixnodeStatusResponse,
|
||||
StakeSaturationResponse,
|
||||
};
|
||||
use validator_api_requests::{Deprecatable, Deprecated};
|
||||
|
||||
// Note: this is a very dangerous method to call as the same identity in the past might have
|
||||
// referred to a completely different node id!
|
||||
async fn mixnode_identity_to_current_node_id(
|
||||
storage: &ValidatorApiStorage,
|
||||
identity: &str,
|
||||
) -> Result<NodeId, ErrorResponse> {
|
||||
storage
|
||||
.mix_identity_to_latest_mix_id(identity)
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))?
|
||||
.ok_or_else(|| ErrorResponse::new("no mixnode with provided identity", Status::NotFound))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/report")]
|
||||
pub(crate) async fn mixnode_report_by_identity(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<Deprecated<MixnodeStatusReport>>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
Ok(Json(_mixnode_report(storage, mix_id).await?.deprecate()))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/history")]
|
||||
pub(crate) async fn mixnode_uptime_history_by_identity(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<Deprecated<MixnodeUptimeHistory>>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
Ok(Json(
|
||||
_mixnode_uptime_history(storage, mix_id).await?.deprecate(),
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/core-status-count?<since>")]
|
||||
pub(crate) async fn mixnode_core_status_count_by_identity(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
since: Option<i64>,
|
||||
) -> Result<Json<Deprecated<MixnodeCoreStatusResponse>>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
Ok(Json(
|
||||
_mixnode_core_status_count(storage, mix_id, since)
|
||||
.await?
|
||||
.deprecate(),
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/status")]
|
||||
pub(crate) async fn get_mixnode_status_by_identity(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
cache: &State<ValidatorCache>,
|
||||
identity: &str,
|
||||
) -> Json<Deprecated<MixnodeStatusResponse>> {
|
||||
match mixnode_identity_to_current_node_id(storage, identity).await {
|
||||
Ok(mix_id) => Json(_get_mixnode_status(cache, mix_id).await.deprecate()),
|
||||
Err(_) => Json(
|
||||
MixnodeStatusResponse {
|
||||
status: MixnodeStatus::NotFound,
|
||||
}
|
||||
.deprecate(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/reward-estimation")]
|
||||
pub(crate) async fn get_mixnode_reward_estimation_by_identity(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<DeprecatedRewardEstimationResponse>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
let new_estimation = _get_mixnode_reward_estimation(cache, mix_id).await?;
|
||||
|
||||
Ok(Json(new_estimation.into()))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[post(
|
||||
"/mixnode/deprecated/<identity>/compute-reward-estimation",
|
||||
data = "<user_reward_param>"
|
||||
)]
|
||||
pub(crate) async fn compute_mixnode_reward_estimation_by_identity(
|
||||
user_reward_param: Json<DeprecatedComputeRewardEstParam>,
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<DeprecatedRewardEstimationResponse>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
let estimation =
|
||||
_compute_mixnode_reward_estimation(user_reward_param.into_inner().into(), cache, mix_id)
|
||||
.await?;
|
||||
|
||||
Ok(Json(estimation.into()))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/stake-saturation")]
|
||||
pub(crate) async fn get_mixnode_stake_saturation_by_identity(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<Deprecated<StakeSaturationResponse>>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
|
||||
Ok(Json(
|
||||
_get_mixnode_stake_saturation(cache, mix_id)
|
||||
.await?
|
||||
.deprecate(),
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/inclusion-probability")]
|
||||
pub(crate) async fn get_mixnode_inclusion_probability_by_identity(
|
||||
cache: &State<NodeStatusCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<Deprecated<InclusionProbabilityResponse>>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
|
||||
Ok(Json(
|
||||
_get_mixnode_inclusion_probability(cache, mix_id)
|
||||
.await?
|
||||
.deprecate(),
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/deprecated/<identity>/avg_uptime")]
|
||||
pub(crate) async fn get_mixnode_avg_uptime_by_identity(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<DeprecatedUptimeResponse>, ErrorResponse> {
|
||||
let mix_id = mixnode_identity_to_current_node_id(storage, identity).await?;
|
||||
|
||||
let new_response = _get_mixnode_avg_uptime(cache, storage, mix_id).await?;
|
||||
|
||||
Ok(Json(DeprecatedUptimeResponse {
|
||||
identity: identity.into(),
|
||||
avg_uptime: new_response.avg_uptime,
|
||||
deprecated: true,
|
||||
}))
|
||||
}
|
||||
|
||||
// DEPRECATED: the uptime is available as part of the `/mixnodes/detailed` endpoint
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnodes/deprecated/avg_uptime")]
|
||||
pub(crate) async fn get_mixnode_avg_uptimes_by_identity(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
) -> Result<Json<Vec<DeprecatedUptimeResponse>>, ErrorResponse> {
|
||||
let mixnodes = cache.mixnodes().await;
|
||||
|
||||
let mut response = Vec::new();
|
||||
for mixnode in mixnodes {
|
||||
let new_response = _get_mixnode_avg_uptime(cache, storage, mixnode.mix_id()).await?;
|
||||
|
||||
response.push(DeprecatedUptimeResponse {
|
||||
identity: mixnode.bond_information.identity().into(),
|
||||
avg_uptime: new_response.avg_uptime,
|
||||
deprecated: true,
|
||||
})
|
||||
}
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::contract_cache::reward_estimate::compute_reward_estimate;
|
||||
use crate::contract_cache::Cache;
|
||||
use crate::node_status_api::models::{ErrorResponse, MixnodeStatusReport, MixnodeUptimeHistory};
|
||||
use crate::storage::ValidatorApiStorage;
|
||||
use crate::{NodeStatusCache, ValidatorCache};
|
||||
use cosmwasm_std::Decimal;
|
||||
use mixnet_contract_common::reward_params::Performance;
|
||||
use mixnet_contract_common::{Interval, NodeId, RewardedSetNodeStatus};
|
||||
use rocket::http::Status;
|
||||
use rocket::State;
|
||||
use validator_api_requests::models::{
|
||||
ComputeRewardEstParam, InclusionProbabilityResponse, MixnodeCoreStatusResponse,
|
||||
MixnodeStatusResponse, RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
|
||||
};
|
||||
|
||||
pub(crate) async fn _mixnode_report(
|
||||
storage: &ValidatorApiStorage,
|
||||
mix_id: NodeId,
|
||||
) -> Result<MixnodeStatusReport, ErrorResponse> {
|
||||
storage
|
||||
.construct_mixnode_report(mix_id)
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
pub(crate) async fn _mixnode_uptime_history(
|
||||
storage: &ValidatorApiStorage,
|
||||
mix_id: NodeId,
|
||||
) -> Result<MixnodeUptimeHistory, ErrorResponse> {
|
||||
storage
|
||||
.get_mixnode_uptime_history(mix_id)
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
pub(crate) async fn _mixnode_core_status_count(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
mix_id: NodeId,
|
||||
since: Option<i64>,
|
||||
) -> Result<MixnodeCoreStatusResponse, ErrorResponse> {
|
||||
let count = storage
|
||||
.get_core_mixnode_status_count(mix_id, since)
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))?;
|
||||
|
||||
Ok(MixnodeCoreStatusResponse { mix_id, count })
|
||||
}
|
||||
|
||||
pub(crate) async fn _get_mixnode_status(
|
||||
cache: &ValidatorCache,
|
||||
mix_id: NodeId,
|
||||
) -> MixnodeStatusResponse {
|
||||
MixnodeStatusResponse {
|
||||
status: cache.mixnode_status(mix_id).await,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn _get_mixnode_reward_estimation(
|
||||
cache: &State<ValidatorCache>,
|
||||
mix_id: NodeId,
|
||||
) -> Result<RewardEstimationResponse, ErrorResponse> {
|
||||
let (mixnode, status) = cache.mixnode_details(mix_id).await;
|
||||
if let Some(mixnode) = mixnode {
|
||||
let reward_params = cache.interval_reward_params().await;
|
||||
let as_at = reward_params.timestamp();
|
||||
let reward_params = reward_params
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
let current_interval = cache
|
||||
.current_interval()
|
||||
.await
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
|
||||
let reward_estimation = compute_reward_estimate(
|
||||
&mixnode.mixnode_details,
|
||||
mixnode.performance,
|
||||
status.into(),
|
||||
reward_params,
|
||||
current_interval,
|
||||
);
|
||||
|
||||
Ok(RewardEstimationResponse {
|
||||
estimation: reward_estimation,
|
||||
reward_params,
|
||||
epoch: current_interval,
|
||||
as_at,
|
||||
})
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn average_mixnode_performance(
|
||||
mix_id: NodeId,
|
||||
current_interval: Interval,
|
||||
storage: &ValidatorApiStorage,
|
||||
) -> Result<Performance, ErrorResponse> {
|
||||
storage
|
||||
.get_average_mixnode_uptime_in_the_last_24hrs(
|
||||
mix_id,
|
||||
current_interval.current_epoch_end_unix_timestamp(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
pub(crate) async fn _compute_mixnode_reward_estimation(
|
||||
user_reward_param: ComputeRewardEstParam,
|
||||
cache: &ValidatorCache,
|
||||
mix_id: NodeId,
|
||||
) -> Result<RewardEstimationResponse, ErrorResponse> {
|
||||
let (mixnode, actual_status) = cache.mixnode_details(mix_id).await;
|
||||
if let Some(mut mixnode) = mixnode {
|
||||
let reward_params = cache.interval_reward_params().await;
|
||||
let as_at = reward_params.timestamp();
|
||||
let reward_params = reward_params
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
let current_interval = cache
|
||||
.current_interval()
|
||||
.await
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
|
||||
// For these parameters we either use the provided ones, or fall back to the system ones
|
||||
let performance = user_reward_param.performance.unwrap_or(mixnode.performance);
|
||||
|
||||
let status = match user_reward_param.active_in_rewarded_set {
|
||||
Some(true) => Some(RewardedSetNodeStatus::Active),
|
||||
Some(false) => Some(RewardedSetNodeStatus::Standby),
|
||||
None => actual_status.into(),
|
||||
};
|
||||
|
||||
if let Some(pledge_amount) = user_reward_param.pledge_amount {
|
||||
mixnode.mixnode_details.rewarding_details.operator =
|
||||
Decimal::from_ratio(pledge_amount, 1u64);
|
||||
}
|
||||
if let Some(total_delegation) = user_reward_param.total_delegation {
|
||||
mixnode.mixnode_details.rewarding_details.delegates =
|
||||
Decimal::from_ratio(total_delegation, 1u64);
|
||||
}
|
||||
|
||||
if mixnode.mixnode_details.rewarding_details.operator
|
||||
+ mixnode.mixnode_details.rewarding_details.delegates
|
||||
> reward_params.interval.staking_supply
|
||||
{
|
||||
return Err(ErrorResponse::new(
|
||||
"Pledge plus delegation too large",
|
||||
Status::UnprocessableEntity,
|
||||
));
|
||||
}
|
||||
|
||||
let reward_estimation = compute_reward_estimate(
|
||||
&mixnode.mixnode_details,
|
||||
performance,
|
||||
status,
|
||||
reward_params,
|
||||
current_interval,
|
||||
);
|
||||
|
||||
Ok(RewardEstimationResponse {
|
||||
estimation: reward_estimation,
|
||||
reward_params,
|
||||
epoch: current_interval,
|
||||
as_at,
|
||||
})
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn _get_mixnode_stake_saturation(
|
||||
cache: &ValidatorCache,
|
||||
mix_id: NodeId,
|
||||
) -> Result<StakeSaturationResponse, ErrorResponse> {
|
||||
let (mixnode, _) = cache.mixnode_details(mix_id).await;
|
||||
if let Some(mixnode) = mixnode {
|
||||
// Recompute the stake saturation just so that we can confidently state that the `as_at`
|
||||
// field is consistent and correct. Luckily this is very cheap.
|
||||
let reward_params = cache.interval_reward_params().await;
|
||||
let as_at = reward_params.timestamp();
|
||||
let rewarding_params = reward_params
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
|
||||
Ok(StakeSaturationResponse {
|
||||
saturation: mixnode
|
||||
.mixnode_details
|
||||
.rewarding_details
|
||||
.bond_saturation(&rewarding_params),
|
||||
uncapped_saturation: mixnode
|
||||
.mixnode_details
|
||||
.rewarding_details
|
||||
.uncapped_bond_saturation(&rewarding_params),
|
||||
as_at,
|
||||
})
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn _get_mixnode_inclusion_probability(
|
||||
cache: &NodeStatusCache,
|
||||
mix_id: NodeId,
|
||||
) -> Result<InclusionProbabilityResponse, ErrorResponse> {
|
||||
cache
|
||||
.inclusion_probabilities()
|
||||
.await
|
||||
.map(Cache::into_inner)
|
||||
.and_then(|p| p.node(mix_id).cloned())
|
||||
.map(|p| InclusionProbabilityResponse {
|
||||
in_active: p.in_active.into(),
|
||||
in_reserve: p.in_reserve.into(),
|
||||
})
|
||||
.ok_or_else(|| ErrorResponse::new("mixnode bond not found", Status::NotFound))
|
||||
}
|
||||
|
||||
pub(crate) async fn _get_mixnode_avg_uptime(
|
||||
cache: &ValidatorCache,
|
||||
storage: &ValidatorApiStorage,
|
||||
mix_id: NodeId,
|
||||
) -> Result<UptimeResponse, ErrorResponse> {
|
||||
let current_interval = cache
|
||||
.current_interval()
|
||||
.await
|
||||
.into_inner()
|
||||
.ok_or_else(|| ErrorResponse::new("server error", Status::InternalServerError))?;
|
||||
|
||||
let performance = average_mixnode_performance(mix_id, current_interval, storage).await?;
|
||||
|
||||
Ok(UptimeResponse {
|
||||
mix_id,
|
||||
avg_uptime: performance.round_to_integer(),
|
||||
})
|
||||
}
|
||||
@@ -2,13 +2,13 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
pub(crate) use cache::{NodeStatusCache, NodeStatusCacheRefresher};
|
||||
|
||||
use okapi::openapi3::OpenApi;
|
||||
use rocket::Route;
|
||||
use rocket_okapi::{openapi_get_routes_spec, settings::OpenApiSettings};
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) mod cache;
|
||||
pub(crate) mod deprecated_routes;
|
||||
pub(crate) mod helpers;
|
||||
pub(crate) mod local_guard;
|
||||
pub(crate) mod models;
|
||||
pub(crate) mod routes;
|
||||
@@ -25,29 +25,47 @@ pub(crate) fn node_status_routes(
|
||||
) -> (Vec<Route>, OpenApi) {
|
||||
if enabled {
|
||||
openapi_get_routes_spec![
|
||||
settings: routes::mixnode_report,
|
||||
routes::gateway_report,
|
||||
routes::mixnode_uptime_history,
|
||||
settings: routes::gateway_report,
|
||||
routes::gateway_uptime_history,
|
||||
routes::mixnode_core_status_count,
|
||||
routes::gateway_core_status_count,
|
||||
routes::mixnode_report,
|
||||
routes::mixnode_uptime_history,
|
||||
routes::mixnode_core_status_count,
|
||||
routes::get_mixnode_status,
|
||||
routes::get_mixnode_reward_estimation,
|
||||
routes::compute_mixnode_reward_estimation,
|
||||
routes::get_mixnode_stake_saturation,
|
||||
routes::get_mixnode_inclusion_probability,
|
||||
routes::get_mixnode_avg_uptime,
|
||||
routes::get_mixnode_avg_uptimes,
|
||||
routes::get_mixnode_inclusion_probabilities,
|
||||
// =================================================
|
||||
// TO REMOVE ONCE OTHER PARTS OF THE SYSTEM MIGRATED
|
||||
// =================================================
|
||||
deprecated_routes::mixnode_report_by_identity,
|
||||
deprecated_routes::mixnode_uptime_history_by_identity,
|
||||
deprecated_routes::mixnode_core_status_count_by_identity,
|
||||
deprecated_routes::get_mixnode_status_by_identity,
|
||||
deprecated_routes::get_mixnode_reward_estimation_by_identity,
|
||||
deprecated_routes::compute_mixnode_reward_estimation_by_identity,
|
||||
deprecated_routes::get_mixnode_stake_saturation_by_identity,
|
||||
deprecated_routes::get_mixnode_inclusion_probability_by_identity,
|
||||
deprecated_routes::get_mixnode_avg_uptime_by_identity,
|
||||
deprecated_routes::get_mixnode_avg_uptimes_by_identity,
|
||||
]
|
||||
} else {
|
||||
// in the minimal variant we would not have access to endpoints relying on existence
|
||||
// of the network monitor and the associated storage
|
||||
openapi_get_routes_spec![
|
||||
routes::get_mixnode_status,
|
||||
settings: routes::get_mixnode_status,
|
||||
routes::get_mixnode_stake_saturation,
|
||||
routes::get_mixnode_inclusion_probability,
|
||||
routes::get_mixnode_inclusion_probabilities,
|
||||
// =================================================
|
||||
// TO REMOVE ONCE OTHER PARTS OF THE SYSTEM MIGRATED
|
||||
// =================================================
|
||||
deprecated_routes::get_mixnode_status_by_identity,
|
||||
deprecated_routes::get_mixnode_stake_saturation_by_identity,
|
||||
deprecated_routes::get_mixnode_inclusion_probability_by_identity,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
use crate::node_status_api::utils::NodeUptimes;
|
||||
use crate::storage::models::NodeStatus;
|
||||
use mixnet_contract_common::reward_params::Performance;
|
||||
use mixnet_contract_common::{IdentityKey, NodeId};
|
||||
use okapi::openapi3::{Responses, SchemaObject};
|
||||
use rocket::http::{ContentType, Status};
|
||||
use rocket::response::{self, Responder, Response};
|
||||
@@ -14,6 +16,7 @@ use schemars::gen::SchemaGenerator;
|
||||
use schemars::schema::{InstanceType, Schema};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::Error;
|
||||
use std::convert::TryFrom;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::io::Cursor;
|
||||
@@ -104,9 +107,16 @@ impl TryFrom<i64> for Uptime {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Uptime> for Performance {
|
||||
fn from(uptime: Uptime) -> Self {
|
||||
Performance::from_percentage_value(uptime.0 as u64).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
|
||||
pub struct MixnodeStatusReport {
|
||||
pub(crate) identity: String,
|
||||
pub(crate) mix_id: NodeId,
|
||||
pub(crate) identity: IdentityKey,
|
||||
pub(crate) owner: String,
|
||||
|
||||
pub(crate) most_recent: Uptime,
|
||||
@@ -118,7 +128,8 @@ pub struct MixnodeStatusReport {
|
||||
impl MixnodeStatusReport {
|
||||
pub(crate) fn construct_from_last_day_reports(
|
||||
report_time: OffsetDateTime,
|
||||
identity: String,
|
||||
mix_id: NodeId,
|
||||
identity: IdentityKey,
|
||||
owner: String,
|
||||
last_day: Vec<NodeStatus>,
|
||||
last_hour_test_runs: usize,
|
||||
@@ -132,6 +143,7 @@ impl MixnodeStatusReport {
|
||||
);
|
||||
|
||||
MixnodeStatusReport {
|
||||
mix_id,
|
||||
identity,
|
||||
owner,
|
||||
most_recent: node_uptimes.most_recent,
|
||||
@@ -180,6 +192,7 @@ impl GatewayStatusReport {
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
|
||||
pub struct MixnodeUptimeHistory {
|
||||
pub(crate) mix_id: NodeId,
|
||||
pub(crate) identity: String,
|
||||
pub(crate) owner: String,
|
||||
|
||||
@@ -187,8 +200,14 @@ pub struct MixnodeUptimeHistory {
|
||||
}
|
||||
|
||||
impl MixnodeUptimeHistory {
|
||||
pub(crate) fn new(identity: String, owner: String, history: Vec<HistoricalUptime>) -> Self {
|
||||
pub(crate) fn new(
|
||||
mix_id: NodeId,
|
||||
identity: String,
|
||||
owner: String,
|
||||
history: Vec<HistoricalUptime>,
|
||||
) -> Self {
|
||||
MixnodeUptimeHistory {
|
||||
mix_id,
|
||||
identity,
|
||||
owner,
|
||||
history,
|
||||
@@ -286,32 +305,38 @@ impl OpenApiResponderInner for ErrorResponse {
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ValidatorApiStorageError {
|
||||
MixnodeReportNotFound(String),
|
||||
MixnodeReportNotFound(NodeId),
|
||||
GatewayReportNotFound(String),
|
||||
MixnodeUptimeHistoryNotFound(String),
|
||||
MixnodeUptimeHistoryNotFound(NodeId),
|
||||
GatewayUptimeHistoryNotFound(String),
|
||||
|
||||
// I don't think we want to expose errors to the user about what really happened
|
||||
InternalDatabaseError(String),
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for ValidatorApiStorageError {
|
||||
fn from(err: Error) -> Self {
|
||||
ValidatorApiStorageError::InternalDatabaseError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ValidatorApiStorageError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ValidatorApiStorageError::MixnodeReportNotFound(identity) => write!(
|
||||
ValidatorApiStorageError::MixnodeReportNotFound(mix_id) => write!(
|
||||
f,
|
||||
"Could not find status report associated with mixnode {}",
|
||||
identity
|
||||
mix_id
|
||||
),
|
||||
ValidatorApiStorageError::GatewayReportNotFound(identity) => write!(
|
||||
f,
|
||||
"Could not find status report associated with gateway {}",
|
||||
identity
|
||||
),
|
||||
ValidatorApiStorageError::MixnodeUptimeHistoryNotFound(identity) => write!(
|
||||
ValidatorApiStorageError::MixnodeUptimeHistoryNotFound(mix_id) => write!(
|
||||
f,
|
||||
"Could not find uptime history associated with mixnode {}",
|
||||
identity
|
||||
mix_id
|
||||
),
|
||||
ValidatorApiStorageError::GatewayUptimeHistoryNotFound(identity) => write!(
|
||||
f,
|
||||
|
||||
@@ -1,83 +1,30 @@
|
||||
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
|
||||
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use crate::contract_cache::Cache;
|
||||
use super::NodeStatusCache;
|
||||
use crate::node_status_api::helpers::{
|
||||
_compute_mixnode_reward_estimation, _get_mixnode_avg_uptime,
|
||||
_get_mixnode_inclusion_probability, _get_mixnode_reward_estimation,
|
||||
_get_mixnode_stake_saturation, _get_mixnode_status, _mixnode_core_status_count,
|
||||
_mixnode_report, _mixnode_uptime_history,
|
||||
};
|
||||
use crate::node_status_api::models::{
|
||||
ErrorResponse, GatewayStatusReport, GatewayUptimeHistory, MixnodeStatusReport,
|
||||
MixnodeUptimeHistory,
|
||||
};
|
||||
use crate::storage::ValidatorApiStorage;
|
||||
use crate::ValidatorCache;
|
||||
use mixnet_contract_common::reward_params::{NodeRewardParams, RewardParams};
|
||||
use mixnet_contract_common::{Interval, MixNodeBond};
|
||||
use mixnet_contract_common::NodeId;
|
||||
use rocket::http::Status;
|
||||
use rocket::serde::json::Json;
|
||||
use rocket::State;
|
||||
use rocket_okapi::openapi;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use validator_api_requests::models::{
|
||||
AllInclusionProbabilitiesResponse, CoreNodeStatusResponse, InclusionProbabilityResponse,
|
||||
MixnodeStatusResponse, RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
|
||||
AllInclusionProbabilitiesResponse, ComputeRewardEstParam, GatewayCoreStatusResponse,
|
||||
InclusionProbabilityResponse, MixnodeCoreStatusResponse, MixnodeStatusResponse,
|
||||
RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
|
||||
};
|
||||
|
||||
use super::models::Uptime;
|
||||
use super::NodeStatusCache;
|
||||
|
||||
async fn average_mixnode_uptime(
|
||||
identity: &str,
|
||||
current_epoch: Option<Interval>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
) -> Result<Uptime, ErrorResponse> {
|
||||
Ok(if let Some(epoch) = current_epoch {
|
||||
storage
|
||||
.get_average_mixnode_uptime_in_the_last_24hrs(identity, epoch.end_unix_timestamp())
|
||||
.await
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))?
|
||||
} else {
|
||||
Uptime::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn estimate_reward(
|
||||
mixnode_bond: &MixNodeBond,
|
||||
base_operator_cost: u64,
|
||||
reward_params: RewardParams,
|
||||
as_at: i64,
|
||||
) -> Result<Json<RewardEstimationResponse>, ErrorResponse> {
|
||||
match mixnode_bond.estimate_reward(base_operator_cost, &reward_params) {
|
||||
Ok(reward_estimate) => {
|
||||
let reponse = RewardEstimationResponse {
|
||||
estimated_total_node_reward: reward_estimate.total_node_reward,
|
||||
estimated_operator_reward: reward_estimate.operator_reward,
|
||||
estimated_delegators_reward: reward_estimate.delegators_reward,
|
||||
estimated_node_profit: reward_estimate.node_profit,
|
||||
estimated_operator_cost: reward_estimate.operator_cost,
|
||||
reward_params,
|
||||
as_at,
|
||||
};
|
||||
Ok(Json(reponse))
|
||||
}
|
||||
Err(e) => Err(ErrorResponse::new(
|
||||
e.to_string(),
|
||||
Status::InternalServerError,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/report")]
|
||||
pub(crate) async fn mixnode_report(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<MixnodeStatusReport>, ErrorResponse> {
|
||||
storage
|
||||
.construct_mixnode_report(identity)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/gateway/<identity>/report")]
|
||||
pub(crate) async fn gateway_report(
|
||||
@@ -91,19 +38,6 @@ pub(crate) async fn gateway_report(
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/history")]
|
||||
pub(crate) async fn mixnode_uptime_history(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
) -> Result<Json<MixnodeUptimeHistory>, ErrorResponse> {
|
||||
storage
|
||||
.get_mixnode_uptime_history(identity)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/gateway/<identity>/history")]
|
||||
pub(crate) async fn gateway_uptime_history(
|
||||
@@ -117,252 +51,115 @@ pub(crate) async fn gateway_uptime_history(
|
||||
.map_err(|err| ErrorResponse::new(err.to_string(), Status::NotFound))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/core-status-count?<since>")]
|
||||
pub(crate) async fn mixnode_core_status_count(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
since: Option<i64>,
|
||||
) -> Json<CoreNodeStatusResponse> {
|
||||
let count = storage
|
||||
.get_core_mixnode_status_count(identity, since)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
Json(CoreNodeStatusResponse {
|
||||
identity: identity.to_string(),
|
||||
count,
|
||||
})
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/gateway/<identity>/core-status-count?<since>")]
|
||||
pub(crate) async fn gateway_core_status_count(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: &str,
|
||||
since: Option<i64>,
|
||||
) -> Json<CoreNodeStatusResponse> {
|
||||
) -> Json<GatewayCoreStatusResponse> {
|
||||
let count = storage
|
||||
.get_core_gateway_status_count(identity, since)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
Json(CoreNodeStatusResponse {
|
||||
Json(GatewayCoreStatusResponse {
|
||||
identity: identity.to_string(),
|
||||
count,
|
||||
})
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/status")]
|
||||
pub(crate) async fn get_mixnode_status(
|
||||
cache: &State<ValidatorCache>,
|
||||
identity: String,
|
||||
) -> Json<MixnodeStatusResponse> {
|
||||
Json(MixnodeStatusResponse {
|
||||
status: cache.mixnode_status(identity).await,
|
||||
})
|
||||
#[get("/mixnode/<mix_id>/report")]
|
||||
pub(crate) async fn mixnode_report(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<MixnodeStatusReport>, ErrorResponse> {
|
||||
Ok(Json(_mixnode_report(storage, mix_id).await?))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/reward-estimation")]
|
||||
pub(crate) async fn get_mixnode_reward_estimation(
|
||||
cache: &State<ValidatorCache>,
|
||||
#[get("/mixnode/<mix_id>/history")]
|
||||
pub(crate) async fn mixnode_uptime_history(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: String,
|
||||
) -> Result<Json<RewardEstimationResponse>, ErrorResponse> {
|
||||
let (bond, status) = cache.mixnode_details(&identity).await;
|
||||
if let Some(bond) = bond {
|
||||
let reward_params = cache.epoch_reward_params().await;
|
||||
let as_at = reward_params.timestamp();
|
||||
let reward_params = reward_params.into_inner();
|
||||
let base_operator_cost = cache.base_operator_cost().await.into_inner();
|
||||
|
||||
let current_epoch = cache.current_epoch().await.into_inner();
|
||||
info!("{:?}", current_epoch);
|
||||
|
||||
let uptime = average_mixnode_uptime(&identity, current_epoch, storage)
|
||||
.await?
|
||||
.u8();
|
||||
|
||||
let node_reward_params = NodeRewardParams::new(0, u128::from(uptime), status.is_active());
|
||||
let reward_params = RewardParams::new(reward_params, node_reward_params);
|
||||
|
||||
estimate_reward(&bond.mixnode_bond, base_operator_cost, reward_params, as_at)
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<MixnodeUptimeHistory>, ErrorResponse> {
|
||||
Ok(Json(_mixnode_uptime_history(storage, mix_id).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize, JsonSchema)]
|
||||
pub(crate) struct ComputeRewardEstParam {
|
||||
uptime: Option<u8>,
|
||||
is_active: Option<bool>,
|
||||
pledge_amount: Option<u64>,
|
||||
total_delegation: Option<u64>,
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<mix_id>/core-status-count?<since>")]
|
||||
pub(crate) async fn mixnode_core_status_count(
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
mix_id: NodeId,
|
||||
since: Option<i64>,
|
||||
) -> Result<Json<MixnodeCoreStatusResponse>, ErrorResponse> {
|
||||
Ok(Json(
|
||||
_mixnode_core_status_count(storage, mix_id, since).await?,
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<mix_id>/status")]
|
||||
pub(crate) async fn get_mixnode_status(
|
||||
cache: &State<ValidatorCache>,
|
||||
mix_id: NodeId,
|
||||
) -> Json<MixnodeStatusResponse> {
|
||||
Json(_get_mixnode_status(cache, mix_id).await)
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<mix_id>/reward-estimation")]
|
||||
pub(crate) async fn get_mixnode_reward_estimation(
|
||||
cache: &State<ValidatorCache>,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<RewardEstimationResponse>, ErrorResponse> {
|
||||
Ok(Json(_get_mixnode_reward_estimation(cache, mix_id).await?))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[post(
|
||||
"/mixnode/<identity>/compute-reward-estimation",
|
||||
"/mixnode/<mix_id>/compute-reward-estimation",
|
||||
data = "<user_reward_param>"
|
||||
)]
|
||||
pub(crate) async fn compute_mixnode_reward_estimation(
|
||||
user_reward_param: Json<ComputeRewardEstParam>,
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: String,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<RewardEstimationResponse>, ErrorResponse> {
|
||||
let (bond, status) = cache.mixnode_details(&identity).await;
|
||||
if let Some(mut bond) = bond {
|
||||
let reward_params = cache.epoch_reward_params().await;
|
||||
let as_at = reward_params.timestamp();
|
||||
let reward_params = reward_params.into_inner();
|
||||
let base_operator_cost = cache.base_operator_cost().await.into_inner();
|
||||
|
||||
let current_epoch = cache.current_epoch().await.into_inner();
|
||||
info!("{:?}", current_epoch);
|
||||
|
||||
// For these parameters we either use the provided ones, or fall back to the system ones
|
||||
|
||||
let uptime = if let Some(uptime) = user_reward_param.uptime {
|
||||
if uptime > 100 {
|
||||
return Err(ErrorResponse::new(
|
||||
"Provided uptime out of bounds",
|
||||
Status::UnprocessableEntity,
|
||||
));
|
||||
}
|
||||
uptime
|
||||
} else {
|
||||
average_mixnode_uptime(&identity, current_epoch, storage)
|
||||
.await?
|
||||
.u8()
|
||||
};
|
||||
|
||||
let is_active = user_reward_param
|
||||
.is_active
|
||||
.unwrap_or_else(|| status.is_active());
|
||||
|
||||
if let Some(pledge_amount) = user_reward_param.pledge_amount {
|
||||
bond.mixnode_bond.pledge_amount.amount = pledge_amount.into();
|
||||
}
|
||||
if let Some(total_delegation) = user_reward_param.total_delegation {
|
||||
bond.mixnode_bond.total_delegation.amount = total_delegation.into();
|
||||
}
|
||||
|
||||
if bond.mixnode_bond.pledge_amount.amount.u128()
|
||||
+ bond.mixnode_bond.total_delegation.amount.u128()
|
||||
> reward_params.staking_supply()
|
||||
{
|
||||
return Err(ErrorResponse::new(
|
||||
"Pledge plus delegation too large",
|
||||
Status::UnprocessableEntity,
|
||||
));
|
||||
}
|
||||
|
||||
let node_reward_params = NodeRewardParams::new(0, u128::from(uptime), is_active);
|
||||
let reward_params = RewardParams::new(reward_params, node_reward_params);
|
||||
|
||||
estimate_reward(&bond.mixnode_bond, base_operator_cost, reward_params, as_at)
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"Mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
Ok(Json(
|
||||
_compute_mixnode_reward_estimation(user_reward_param.into_inner(), cache, mix_id).await?,
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/stake-saturation")]
|
||||
#[get("/mixnode/<mix_id>/stake-saturation")]
|
||||
pub(crate) async fn get_mixnode_stake_saturation(
|
||||
cache: &State<ValidatorCache>,
|
||||
identity: String,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<StakeSaturationResponse>, ErrorResponse> {
|
||||
let (bond, _) = cache.mixnode_details(&identity).await;
|
||||
if let Some(bond) = bond {
|
||||
// Recompute the stake saturation just so that we can confidentaly state that the `as_at`
|
||||
// field is consistent and correct. Luckily this is very cheap.
|
||||
let interval_reward_params = cache.epoch_reward_params().await;
|
||||
let as_at = interval_reward_params.timestamp();
|
||||
let interval_reward_params = interval_reward_params.into_inner();
|
||||
|
||||
let saturation = bond.mixnode_bond.stake_saturation(
|
||||
interval_reward_params.staking_supply(),
|
||||
interval_reward_params.rewarded_set_size() as u32,
|
||||
);
|
||||
|
||||
Ok(Json(StakeSaturationResponse {
|
||||
saturation: saturation.to_num(),
|
||||
as_at,
|
||||
}))
|
||||
} else {
|
||||
Err(ErrorResponse::new(
|
||||
"mixnode bond not found",
|
||||
Status::NotFound,
|
||||
))
|
||||
}
|
||||
Ok(Json(_get_mixnode_stake_saturation(cache, mix_id).await?))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/inclusion-probability")]
|
||||
#[get("/mixnode/<mix_id>/inclusion-probability")]
|
||||
pub(crate) async fn get_mixnode_inclusion_probability(
|
||||
node_status_cache: &State<NodeStatusCache>,
|
||||
identity: String,
|
||||
) -> Json<Option<InclusionProbabilityResponse>> {
|
||||
node_status_cache
|
||||
.inclusion_probabilities()
|
||||
.await
|
||||
.map(Cache::into_inner)
|
||||
.and_then(|p| p.node(&identity).cloned())
|
||||
.map(|p| {
|
||||
Json(Some(InclusionProbabilityResponse {
|
||||
in_active: p.in_active.into(),
|
||||
in_reserve: p.in_reserve.into(),
|
||||
}))
|
||||
})
|
||||
.unwrap_or(Json(None))
|
||||
cache: &State<NodeStatusCache>,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<InclusionProbabilityResponse>, ErrorResponse> {
|
||||
Ok(Json(
|
||||
_get_mixnode_inclusion_probability(cache, mix_id).await?,
|
||||
))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnode/<identity>/avg_uptime")]
|
||||
#[get("/mixnode/<mix_id>/avg_uptime")]
|
||||
pub(crate) async fn get_mixnode_avg_uptime(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
identity: String,
|
||||
mix_id: NodeId,
|
||||
) -> Result<Json<UptimeResponse>, ErrorResponse> {
|
||||
let current_epoch = cache.current_epoch().await.into_inner();
|
||||
let uptime = average_mixnode_uptime(&identity, current_epoch, storage).await?;
|
||||
|
||||
Ok(Json(UptimeResponse {
|
||||
identity,
|
||||
avg_uptime: uptime.u8(),
|
||||
}))
|
||||
}
|
||||
|
||||
// DEPRECATED: the uptime is available as part of the `/mixnodes/detailed` endpoint
|
||||
#[openapi(tag = "status")]
|
||||
#[get("/mixnodes/avg_uptime")]
|
||||
pub(crate) async fn get_mixnode_avg_uptimes(
|
||||
cache: &State<ValidatorCache>,
|
||||
storage: &State<ValidatorApiStorage>,
|
||||
) -> Result<Json<Vec<UptimeResponse>>, ErrorResponse> {
|
||||
let mixnodes = cache.mixnodes().await;
|
||||
let current_epoch = cache.current_epoch().await.into_inner();
|
||||
|
||||
let mut response = Vec::new();
|
||||
for mixnode in mixnodes {
|
||||
let uptime = average_mixnode_uptime(mixnode.identity(), current_epoch, storage).await?;
|
||||
|
||||
response.push(UptimeResponse {
|
||||
identity: mixnode.identity().to_string(),
|
||||
avg_uptime: uptime.u8(),
|
||||
})
|
||||
}
|
||||
|
||||
Ok(Json(response))
|
||||
Ok(Json(_get_mixnode_avg_uptime(cache, storage, mix_id).await?))
|
||||
}
|
||||
|
||||
#[openapi(tag = "status")]
|
||||
|
||||
@@ -5,11 +5,20 @@ use crate::node_status_api::models::Uptime;
|
||||
use crate::node_status_api::{FIFTEEN_MINUTES, ONE_HOUR};
|
||||
use crate::storage::models::NodeStatus;
|
||||
use log::warn;
|
||||
use mixnet_contract_common::NodeId;
|
||||
use std::convert::TryInto;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
// A temporary helper struct used to produce reports for active nodes.
|
||||
pub(crate) struct ActiveNodeStatuses {
|
||||
// A temporary helper structs used to produce reports for active nodes.
|
||||
pub(crate) struct ActiveMixnodeStatuses {
|
||||
pub(crate) mix_id: NodeId,
|
||||
|
||||
pub(crate) identity: String,
|
||||
pub(crate) owner: String,
|
||||
pub(crate) statuses: Vec<NodeStatus>,
|
||||
}
|
||||
|
||||
pub(crate) struct ActiveGatewayStatuses {
|
||||
pub(crate) identity: String,
|
||||
pub(crate) owner: String,
|
||||
pub(crate) statuses: Vec<NodeStatus>,
|
||||
|
||||
Reference in New Issue
Block a user