Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/upgrade rewarding sandbox #1167

Merged
merged 4 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions common/client-libs/validator-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,32 +546,6 @@ impl<C> Client<C> {
Ok(delegations)
}

pub async fn get_all_network_delegations(&self) -> Result<Vec<Delegation>, ValidatorClientError>
where
C: CosmWasmClient + Sync,
{
let mut delegations = Vec::new();
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.get_all_network_delegations_paged(
start_after.take(),
self.mixnode_delegations_page_limit,
)
.await?;
delegations.append(&mut paged_response.delegations);

if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}

Ok(delegations)
}

pub async fn get_all_delegator_delegations(
&self,
delegation_owner: &cosmrs::AccountId,
Expand Down
24 changes: 3 additions & 21 deletions common/client-libs/validator-client/src/nymd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ use mixnet_contract_common::mixnode::DelegationEvent;
use mixnet_contract_common::{
ContractStateParams, Delegation, ExecuteMsg, Gateway, GatewayBond, GatewayOwnershipResponse,
IdentityKey, Interval, LayerDistribution, MixNode, MixNodeBond, MixOwnershipResponse,
MixnetContractVersion, MixnodeRewardingStatusResponse, PagedAllDelegationsResponse,
PagedDelegatorDelegationsResponse, PagedGatewayResponse, PagedMixDelegationsResponse,
PagedMixnodeResponse, PagedRewardedSetResponse, QueryMsg, RewardedSetUpdateDetails,
MixnetContractVersion, MixnodeRewardingStatusResponse, PagedDelegatorDelegationsResponse,
PagedGatewayResponse, PagedMixDelegationsResponse, PagedMixnodeResponse,
PagedRewardedSetResponse, QueryMsg, RewardedSetUpdateDetails,
};
use serde::Serialize;
use std::convert::TryInto;
Expand Down Expand Up @@ -564,24 +564,6 @@ impl<C> NymdClient<C> {
.await
}

/// Gets list of all mixnode delegations on particular page.
pub async fn get_all_network_delegations_paged(
&self,
start_after: Option<(IdentityKey, Vec<u8>, u64)>,
page_limit: Option<u32>,
) -> Result<PagedAllDelegationsResponse, NymdError>
where
C: CosmWasmClient + Sync,
{
let request = QueryMsg::GetAllNetworkDelegations {
start_after,
limit: page_limit,
};
self.client
.query_contract_smart(self.mixnet_contract_address()?, &request)
.await
}

/// Gets list of all the mixnodes on which a particular address delegated.
pub async fn get_delegator_delegations_paged(
&self,
Expand Down
10 changes: 1 addition & 9 deletions common/cosmwasm-smart-contracts/mixnet-contract/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ use crate::{Gateway, IdentityKey, MixNode};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

type BlockHeight = u64;
type DelegateAddress = Vec<u8>;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
pub rewarding_validator_address: String,
Expand All @@ -18,6 +15,7 @@ pub struct InstantiateMsg {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
InitEpoch {},
ReconcileDelegations {},
CheckpointMixnodes {},
CompoundOperatorRewardOnBehalf {
Expand Down Expand Up @@ -119,12 +117,6 @@ pub enum QueryMsg {
address: String,
},
StateParams {},
// gets all [paged] delegations in the entire network
// TODO: do we even want that?
GetAllNetworkDelegations {
start_after: Option<(IdentityKey, DelegateAddress, BlockHeight)>,
limit: Option<u32>,
},
// gets all [paged] delegations associated with particular mixnode
GetMixnodeDelegations {
mix_identity: IdentityKey,
Expand Down
2 changes: 1 addition & 1 deletion common/nymsphinx/params/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crypto::aes::Aes128;
use crypto::blake3;
use crypto::ctr;

type Aes128Ctr = ctr::Ctr64LE<Aes128>;
type Aes128Ctr = ctr::Ctr64BE<Aes128>;

// Re-export for ease of use
pub use packet_modes::PacketMode;
Expand Down
9 changes: 3 additions & 6 deletions contracts/mixnet/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

use crate::constants::{ACTIVE_SET_WORK_FACTOR, INTERVAL_REWARD_PERCENT, SYBIL_RESISTANCE_PERCENT};
use crate::delegations::queries::query_all_network_delegations_paged;
use crate::delegations::queries::query_delegator_delegations_paged;
use crate::delegations::queries::query_mixnode_delegation;
use crate::delegations::queries::{
Expand All @@ -16,7 +15,7 @@ use crate::interval::queries::{
query_current_rewarded_set_height, query_rewarded_set,
query_rewarded_set_refresh_minimum_blocks, query_rewarded_set_update_details,
};
use crate::interval::transactions::init_epoch;
use crate::interval::transactions::{init_epoch, try_init_epoch};
use crate::mixnet_contract_settings::models::ContractState;
use crate::mixnet_contract_settings::queries::{
query_contract_settings_params, query_contract_version,
Expand Down Expand Up @@ -97,6 +96,7 @@ pub fn execute(
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::InitEpoch {} => try_init_epoch(info, deps.storage, env),
ExecuteMsg::BondMixnode {
mix_node,
owner_signature,
Expand Down Expand Up @@ -299,9 +299,6 @@ pub fn query(deps: Deps<'_>, env: Env, msg: QueryMsg) -> Result<QueryResponse, C
start_after,
limit,
)?),
QueryMsg::GetAllNetworkDelegations { start_after, limit } => to_binary(
&query_all_network_delegations_paged(deps, start_after, limit)?,
),
QueryMsg::GetDelegatorDelegations {
delegator: delegation_owner,
start_after,
Expand Down Expand Up @@ -423,7 +420,7 @@ fn migrate_delegations(deps: DepsMut<'_>) -> Result<(), ContractError> {

#[entry_point]
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
// TODO: Uncomment for sandbox and mainnet
// TODO: Uncomment mainnet
// migrate_delegations(deps)?;

Ok(Default::default())
Expand Down
146 changes: 1 addition & 145 deletions contracts/mixnet/src/delegations/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ use cosmwasm_std::{Api, Deps, Storage};
use cw_storage_plus::{Bound, PrimaryKey};
use mixnet_contract_common::mixnode::DelegationEvent;
use mixnet_contract_common::{
Delegation, IdentityKey, PagedAllDelegationsResponse, PagedDelegatorDelegationsResponse,
PagedMixDelegationsResponse,
Delegation, IdentityKey, PagedDelegatorDelegationsResponse, PagedMixDelegationsResponse,
};

pub(crate) fn query_pending_delegation_events(
Expand All @@ -25,33 +24,6 @@ pub(crate) fn query_pending_delegation_events(
.collect::<Vec<DelegationEvent>>())
}

pub(crate) fn query_all_network_delegations_paged(
deps: Deps<'_>,
start_after: Option<(IdentityKey, Vec<u8>, u64)>,
limit: Option<u32>,
) -> StdResult<PagedAllDelegationsResponse> {
let limit = limit
.unwrap_or(storage::DELEGATION_PAGE_DEFAULT_LIMIT)
.min(storage::DELEGATION_PAGE_MAX_LIMIT) as usize;

let start = start_after.map(Bound::exclusive);

let delegations = storage::delegations()
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|record| record.map(|r| r.1))
.collect::<StdResult<Vec<_>>>()?;

let start_next_after = delegations
.last()
.map(|delegation| delegation.storage_key());

Ok(PagedAllDelegationsResponse::new(
delegations,
start_next_after,
))
}

pub(crate) fn query_delegator_delegations_paged(
deps: Deps<'_>,
delegation_owner: String,
Expand Down Expand Up @@ -309,122 +281,6 @@ pub(crate) mod tests {
}
}

#[cfg(test)]
mod querying_for_all_mixnode_delegations_paged {
use super::*;
use crate::support::tests::test_helpers;
use mixnet_contract_common::IdentityKey;

#[test]
fn retrieval_obeys_limits() {
let mut deps = test_helpers::init_contract();
let limit = 2;
let node_identity: IdentityKey = "foo".into();
store_n_mix_delegations(100, &mut deps.storage, &node_identity);

let page1 =
query_all_network_delegations_paged(deps.as_ref(), None, Option::from(limit))
.unwrap();
assert_eq!(limit, page1.delegations.len() as u32);
}

#[test]
fn retrieval_has_default_limit() {
let mut deps = test_helpers::init_contract();
let node_identity: IdentityKey = "foo".into();
store_n_mix_delegations(
storage::DELEGATION_PAGE_DEFAULT_LIMIT * 10,
&mut deps.storage,
&node_identity,
);

// query without explicitly setting a limit
let page1 = query_all_network_delegations_paged(deps.as_ref(), None, None).unwrap();
assert_eq!(
storage::DELEGATION_PAGE_DEFAULT_LIMIT,
page1.delegations.len() as u32
);
}

#[test]
fn retrieval_has_max_limit() {
let mut deps = test_helpers::init_contract();
let node_identity: IdentityKey = "foo".into();
store_n_mix_delegations(
storage::DELEGATION_PAGE_DEFAULT_LIMIT * 10,
&mut deps.storage,
&node_identity,
);

// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * storage::DELEGATION_PAGE_DEFAULT_LIMIT;
let page1 =
query_all_network_delegations_paged(deps.as_ref(), None, Option::from(crazy_limit))
.unwrap();

// we default to a decent sized upper bound instead
let expected_limit = storage::DELEGATION_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.delegations.len() as u32);
}

#[test]
fn pagination_works() {
let mut deps = test_helpers::init_contract();
let node_identity: IdentityKey = "foo".into();

test_helpers::save_dummy_delegation(&mut deps.storage, &node_identity, "100");

let per_page = 2;
let page1 =
query_all_network_delegations_paged(deps.as_ref(), None, Option::from(per_page))
.unwrap();

// page should have 1 result on it
assert_eq!(1, page1.delegations.len());

// save another
test_helpers::save_dummy_delegation(&mut deps.storage, &node_identity, "200");

// page1 should have 2 results on it
let page1 =
query_all_network_delegations_paged(deps.as_ref(), None, Option::from(per_page))
.unwrap();
assert_eq!(2, page1.delegations.len());

test_helpers::save_dummy_delegation(&mut deps.storage, &node_identity, "300");

// page1 still has 2 results
let page1 =
query_all_network_delegations_paged(deps.as_ref(), None, Option::from(per_page))
.unwrap();
assert_eq!(2, page1.delegations.len());

// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_all_network_delegations_paged(
deps.as_ref(),
Option::from(start_after.clone()),
Option::from(per_page),
)
.unwrap();

assert_eq!(1, page2.delegations.len());

// save another one
test_helpers::save_dummy_delegation(&mut deps.storage, &node_identity, "400");

let page2 = query_all_network_delegations_paged(
deps.as_ref(),
Option::from(start_after),
Option::from(per_page),
)
.unwrap();

// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.delegations.len());
}
}

#[test]
fn mix_deletion_query_returns_current_delegation_value() {
let mut deps = test_helpers::init_contract();
Expand Down
12 changes: 12 additions & 0 deletions contracts/mixnet/src/interval/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ pub fn try_write_rewarded_set(
)))
}

pub fn try_init_epoch(
info: MessageInfo,
storage: &mut dyn Storage,
env: Env,
) -> Result<Response, ContractError> {
is_authorized(info.sender.as_str().to_string(), storage)?;

init_epoch(storage, env)?;

Ok(Response::default())
}

pub fn init_epoch(storage: &mut dyn Storage, env: Env) -> Result<Interval, ContractError> {
let epoch = Interval::init_epoch(env);
storage::save_epoch(storage, &epoch)?;
Expand Down
9 changes: 1 addition & 8 deletions explorer-api/src/mix_node/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ use rocket_okapi::settings::OpenApiSettings;
use mixnet_contract_common::Delegation;

use crate::mix_node::models::{NodeDescription, NodeStats, PrettyDetailedMixNodeBond};
use crate::mix_nodes::delegations::{get_mixnode_delegations, get_single_mixnode_delegations};
use crate::mix_nodes::delegations::get_single_mixnode_delegations;
use crate::state::ExplorerApiStateContext;

pub fn mix_node_make_default_routes(settings: &OpenApiSettings) -> (Vec<Route>, OpenApi) {
openapi_get_routes_spec![
settings: get_delegations,
get_by_id,
get_all_delegations,
get_description,
get_stats,
]
Expand Down Expand Up @@ -48,12 +47,6 @@ pub(crate) async fn get_delegations(pubkey: &str) -> Json<Vec<Delegation>> {
Json(get_single_mixnode_delegations(pubkey).await)
}

#[openapi(tag = "mix_node")]
#[get("/all_mix_delegations")]
pub(crate) async fn get_all_delegations() -> Json<Vec<Delegation>> {
Json(get_mixnode_delegations().await)
}

#[openapi(tag = "mix_node")]
#[get("/<pubkey>/description")]
pub(crate) async fn get_description(
Expand Down
12 changes: 0 additions & 12 deletions explorer-api/src/mix_nodes/delegations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,3 @@ pub(crate) async fn get_single_mixnode_delegations(pubkey: &str) -> Vec<Delegati
};
delegates
}

pub(crate) async fn get_mixnode_delegations() -> Vec<Delegation> {
let client = crate::client::new_nymd_client();
let delegates = match client.get_all_network_delegations().await {
Ok(result) => result,
Err(e) => {
error!("Could not get all mix delegations: {:?}", e);
vec![]
}
};
delegates
}
3 changes: 3 additions & 0 deletions validator-api/src/network_monitor/monitor/preparer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,9 @@ impl PacketPreparer {
let rand_l3 = l3.choose_multiple(&mut rng, n).collect::<Vec<_>>();
let rand_gateways = gateways.choose_multiple(&mut rng, n).collect::<Vec<_>>();

// let rand_gateways = gateways.iter().filter(|g| g.gateway.host == "109.74.196.254".to_string()).collect::<Vec<_>>();
// let rand_gateways = gateways.iter().filter(|g| g.gateway.host == "185.3.94.33".to_string()).collect::<Vec<_>>();

// the unwrap on `min()` is fine as we know the iterator is not empty
let most_available = *[
rand_l1.len(),
Expand Down