136666d759
* 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>
106 lines
2.6 KiB
Rust
106 lines
2.6 KiB
Rust
use std::borrow::Borrow;
|
|
use std::collections::HashMap;
|
|
use std::hash::Hash;
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
const DEFAULT_CACHE_VALIDITY: Duration = Duration::from_secs(60);
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct Cache<K, V: Clone> {
|
|
inner: HashMap<K, CacheItem<V>>,
|
|
cache_validity_duration: Duration,
|
|
}
|
|
|
|
impl<K, V: Clone> Cache<K, V>
|
|
where
|
|
K: Eq + Hash,
|
|
{
|
|
pub(crate) fn new() -> Self {
|
|
Cache {
|
|
inner: HashMap::new(),
|
|
cache_validity_duration: DEFAULT_CACHE_VALIDITY,
|
|
}
|
|
}
|
|
|
|
// it felt like this might be an useful addition if we want to keep our caches with different
|
|
// validity durations
|
|
#[allow(unused)]
|
|
pub(crate) fn with_validity_duration(mut self, new_cache_validity: Duration) -> Self {
|
|
self.cache_validity_duration = new_cache_validity;
|
|
self
|
|
}
|
|
|
|
pub(crate) fn len(&self) -> usize {
|
|
self.inner.len()
|
|
}
|
|
|
|
pub(crate) fn get_all(&self) -> Vec<V> {
|
|
self.inner
|
|
.values()
|
|
.map(|cache_item| cache_item.value.clone())
|
|
.collect()
|
|
}
|
|
|
|
pub(crate) fn get<Q: ?Sized>(&self, key: &Q) -> Option<V>
|
|
where
|
|
K: Borrow<Q>,
|
|
Q: Hash + Eq,
|
|
{
|
|
self.inner
|
|
.get(key)
|
|
.filter(|cache_item| cache_item.valid_until >= SystemTime::now())
|
|
.map(|cache_item| cache_item.value.clone())
|
|
}
|
|
|
|
pub(crate) fn set(&mut self, key: K, value: V) {
|
|
self.inner.insert(
|
|
key,
|
|
CacheItem {
|
|
valid_until: SystemTime::now() + self.cache_validity_duration,
|
|
value,
|
|
},
|
|
);
|
|
}
|
|
|
|
#[allow(unused)]
|
|
pub(crate) fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
|
|
where
|
|
K: Borrow<Q>,
|
|
Q: Hash + Eq,
|
|
{
|
|
self.inner.remove(key).map(|item| item.value)
|
|
}
|
|
|
|
#[allow(unused)]
|
|
pub(crate) fn remove_if_expired<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
|
|
where
|
|
K: Borrow<Q>,
|
|
Q: Hash + Eq,
|
|
{
|
|
if self.inner.get(key)?.has_expired() {
|
|
self.remove(key)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
// it seems like something should be running on timer calling this method on all of our caches
|
|
#[allow(unused)]
|
|
pub(crate) fn remove_all_expired(&mut self) {
|
|
self.inner.retain(|_, v| !v.has_expired())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct CacheItem<T> {
|
|
pub(crate) value: T,
|
|
pub(crate) valid_until: std::time::SystemTime,
|
|
}
|
|
|
|
impl<T> CacheItem<T> {
|
|
fn has_expired(&self) -> bool {
|
|
let now = SystemTime::now();
|
|
self.valid_until < now
|
|
}
|
|
}
|