Files
nym/nym-api/src/nym_contract_cache/cache/refresher.rs
T
Simon Wicky fc2eedfc66 Another Grand Ecash Squasheroo
add offline ecash library

minor changes in coconut benchmarks

add ecash smart contract

change contract traits from coconut to ecash

first wave of andrew's suggestion

first wave of andrew's suggestion

second wave of andrew's suggestion for ecash lib

andrew's suggestion for ecash contract

licensing commit

safety comments for most unwraps

more unwrap handling

change chrono crate for time

latest cargo lock

error revamp

small visibility fix

small fix

remove indexedmap from contract + some tweaks

add cw2 version in ecash contract

remove envryption key from contract

change types from coconut to ecash types

adapt api model for credential issuance

adapt issued credential storage on API

add signatures cache on API

change API routes for new blind signing

modify issued_credential table

add issuance logic client-side

credential and signature storage client side

utils for credential issuance

first wave of fix

some of andrew's suggestions

remove encryption key from deposit

freepass issuance client side

freepass issuance API side

andrew's suggested fixes

other suggested fix

adapt change from PR below

allow offline verification flag

credential spending models

credential spending models for client

credential preperation for the client

credential preperation for the client

credential storage for spending on client

bloom filter for API

spent credential storage on validators

API route for spending online and offline ecash

API routes in the client lib

credential storage on gateway

ecash verifier to replace coconut verifier

accept credentials on gateway

bandwidth expiration for gateways

client ask for more bandwidth if it runs out

credential import

adapt nym validator rewarder and sdk

fix tests api tests and add constants

cargo fmt and lock and small test fix

cargo fmt and lock and small test fix

cargo lock

move stuff where they belong in ecash and static parameters

move some constants, error handling and phase out time crate

error revamp part 2

secret key by ref instead of clone

change l in wallet and v visibility

rework payinfo

rework monster tuples

fix expiration date signature cloning

minor fixes

final bits and bobs fixes

final bits and bobs fixes

rename l accessor to tickets_spent

wave of fixes

second wave of fixes

change hash domain value

removed benchmark flag

remove useless stringification in storage

nuke Bandwidth voucher

change timestamps to offsetdatetime

key name change

post-rebase fixes

update nym-connect 'time' dep due to broken semver

upload ecash contract to the build server

make wasm zknym-lib compile

but it won't work properly just yet

make wasm zknym-lib compile

but it won't work properly just yet

fix typo in ecash contract deps

make sure to use 0.1.0 sphinx packet

optimise pairings in 'check_vk_pairing'

derive serde for ecash types

simplified g1 tuple byte conversion

further optimise the pairing

unified signature type + renamed nym-api coconut module to ecash

using bincode serialiser for more complex binary types

using multimiller loop instead of rayon for verifying coin indices signatures

batching signature verification wherever possible

feature-locked rayon

clippy

refactor ecash contract a bit + introduce deposit storage

reworked find_proposal_id

various minor fixed

add offline_zk_nyms to nym-node everywhere

add missing #query

change test value to fit new serialization

optimised deposits storage

removed duplicate decompression code

using deposit_id instead of transaction hash

removed freepasses

split up ecash handling

unified shared state

fixed deposit_id parsing

log recovered deposit id

removed online verification

add detailed build info to ecash contract

fixed deserialisation of deposit amount received from nyxd queries

changed deposit to only persist attached pubkey

first iteration of split of verification and redemption

basic tool for setting up new network

expanded the tool with the option to bypass DKG

rename + init network without DKG

setting up locally running apis

ecash key migration

more local functionalities

wip fixing sql schemas

gateway immediately submitting redemption proposal

and getting it passed if valid

most of the gateway logic for split redemption with error recovery

fixed gateway not persisting ecash signers

simplify creation of compatible client

create properly serialised ecash key from the beginning

rebuild missing tickets and proposals on startup

stop ticket issuance during DKG transition

fixing build issues

split out ecash storage on nym-api side

master-verification-key route

caching all the signatures and keys

implemented aggregated routes for nym-apis

swagger UI for ecash endpoints

added explicit annotation for index and expiration signatures

revamped client ticketbook storage

save all recovery information in the same underlying storage

wrapper for bloomfilter

being more aggressive with marking tickets as used

ensure client has correct signatures before making deposit

fix deserialisation of AggregatedExpirationDateSignatureResponse + add ticketbook table

split nym-api ecash routes handlers into multiple files

fixed deserialisation of encoded expiration date

add tt_gamma1 to challenge and change naming for paper consistency

rotating double spending bloomfilter

nym-api test fixes + make sure to insert initial BF params

fixed ecash benchmark code

updated contract schema

updated CI to not upload gateway/mixnode binaries

ticket bandwidth revocation

added default deserialisation for zk nym config

post-rebase fixes
2024-07-30 11:27:21 +01:00

206 lines
7.3 KiB
Rust

// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use super::NymContractCache;
use crate::nym_contract_cache::cache::data::{CachedContractInfo, CachedContractsInfo};
use crate::nyxd::Client;
use crate::support::caching::CacheNotification;
use anyhow::Result;
use nym_mixnet_contract_common::{MixId, MixNodeDetails, RewardedSetNodeStatus};
use nym_task::TaskClient;
use nym_validator_client::nyxd::contract_traits::{
MixnetQueryClient, NymContractsProvider, VestingQueryClient,
};
use std::{collections::HashMap, sync::atomic::Ordering, time::Duration};
use tokio::sync::watch;
use tokio::time;
pub struct NymContractCacheRefresher {
nyxd_client: Client,
cache: NymContractCache,
caching_interval: Duration,
// Notify listeners that the cache has been updated
update_notifier: watch::Sender<CacheNotification>,
}
impl NymContractCacheRefresher {
pub(crate) fn new(
nyxd_client: Client,
caching_interval: Duration,
cache: NymContractCache,
) -> Self {
let (tx, _) = watch::channel(CacheNotification::Start);
NymContractCacheRefresher {
nyxd_client,
cache,
caching_interval,
update_notifier: tx,
}
}
pub fn subscribe(&self) -> watch::Receiver<CacheNotification> {
self.update_notifier.subscribe()
}
async fn get_nym_contracts_info(&self) -> Result<CachedContractsInfo> {
use crate::query_guard;
let mut updated = HashMap::new();
let client_guard = self.nyxd_client.read().await;
let mixnet = query_guard!(client_guard, mixnet_contract_address());
let vesting = query_guard!(client_guard, vesting_contract_address());
let coconut_dkg = query_guard!(client_guard, dkg_contract_address());
let group = query_guard!(client_guard, group_contract_address());
let multisig = query_guard!(client_guard, multisig_contract_address());
let ecash = query_guard!(client_guard, ecash_contract_address());
for (address, name) in [
(mixnet, "nym-mixnet-contract"),
(vesting, "nym-vesting-contract"),
(coconut_dkg, "nym-coconut-dkg-contract"),
(group, "nym-cw4-group-contract"),
(multisig, "nym-cw3-multisig-contract"),
(ecash, "nym-ecash-contract"),
] {
let (cw2, build_info) = if let Some(address) = address {
let cw2 = query_guard!(client_guard, try_get_cw2_contract_version(address).await);
let mut build_info = query_guard!(
client_guard,
try_get_contract_build_information(address).await
);
// for backwards compatibility until we migrate the contracts
if build_info.is_none() {
match name {
"nym-mixnet-contract" => {
build_info = Some(query_guard!(
client_guard,
get_mixnet_contract_version().await
)?)
}
"nym-vesting-contract" => {
build_info = Some(query_guard!(
client_guard,
get_vesting_contract_version().await
)?)
}
_ => (),
}
}
(cw2, build_info)
} else {
(None, None)
};
updated.insert(
name.to_string(),
CachedContractInfo::new(address, cw2, build_info),
);
}
Ok(updated)
}
async fn refresh(&self) -> Result<()> {
let rewarding_params = self.nyxd_client.get_current_rewarding_parameters().await?;
let current_interval = self.nyxd_client.get_current_interval().await?.interval;
let mixnodes = self.nyxd_client.get_mixnodes().await?;
let gateways = self.nyxd_client.get_gateways().await?;
let mix_to_family = self.nyxd_client.get_all_family_members().await?;
let rewarded_set_map = self.get_rewarded_set_map().await;
let (rewarded_set, active_set) =
Self::collect_rewarded_and_active_set_details(&mixnodes, &rewarded_set_map);
let contract_info = self.get_nym_contracts_info().await?;
info!(
"Updating validator cache. There are {} mixnodes and {} gateways",
mixnodes.len(),
gateways.len(),
);
self.cache
.update(
mixnodes,
gateways,
rewarded_set,
active_set,
rewarding_params,
current_interval,
mix_to_family,
contract_info,
)
.await;
if let Err(err) = self.update_notifier.send(CacheNotification::Updated) {
warn!("Failed to notify validator cache refresh: {err}");
}
Ok(())
}
async fn get_rewarded_set_map(&self) -> HashMap<MixId, RewardedSetNodeStatus> {
self.nyxd_client
.get_rewarded_set_mixnodes()
.await
.map(|nodes| nodes.into_iter().collect())
.unwrap_or_default()
}
fn collect_rewarded_and_active_set_details(
all_mixnodes: &[MixNodeDetails],
rewarded_set_nodes: &HashMap<MixId, RewardedSetNodeStatus>,
) -> (Vec<MixNodeDetails>, Vec<MixNodeDetails>) {
let mut active_set = Vec::new();
let mut rewarded_set = Vec::new();
for mix in all_mixnodes {
if let Some(status) = rewarded_set_nodes.get(&mix.mix_id()) {
rewarded_set.push(mix.clone());
if status.is_active() {
active_set.push(mix.clone())
}
}
}
(rewarded_set, active_set)
}
pub(crate) async fn run(&self, mut shutdown: TaskClient) {
let mut interval = time::interval(self.caching_interval);
while !shutdown.is_shutdown() {
tokio::select! {
_ = interval.tick() => {
tokio::select! {
biased;
_ = shutdown.recv() => {
trace!("ValidatorCacheRefresher: Received shutdown");
}
ret = self.refresh() => {
if let Err(err) = ret {
error!("Failed to refresh validator cache - {err}");
} else {
// relaxed memory ordering is fine here. worst case scenario network monitor
// will just have to wait for an additional backoff to see the change.
// And so this will not really incur any performance penalties by setting it every loop iteration
self.cache.initialised.store(true, Ordering::Relaxed)
}
}
}
}
_ = shutdown.recv() => {
trace!("ValidatorCacheRefresher: Received shutdown");
}
}
}
}
}