Skip to content

Commit

Permalink
pos: return sorted validator sets and code re-use for queries
Browse files Browse the repository at this point in the history
  • Loading branch information
tzemanovic authored and brentstone committed Jul 12, 2023
1 parent aae3f54 commit b39d3ef
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 74 deletions.
22 changes: 6 additions & 16 deletions apps/src/lib/client/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Client RPC queries

use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs::File;
use std::io::{self, Write};
use std::iter::Iterator;
Expand All @@ -10,7 +10,7 @@ use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};
use data_encoding::HEXLOWER;
use itertools::{Either, Itertools};
use itertools::Either;
use masp_primitives::asset_type::AssetType;
use masp_primitives::merkle_tree::MerklePath;
use masp_primitives::sapling::{Node, ViewingKey};
Expand Down Expand Up @@ -1567,31 +1567,26 @@ pub async fn query_bonded_stake<C: namada::ledger::queries::Client + Sync>(
}
None => {
let consensus =
unwrap_client_response::<C, HashSet<WeightedValidator>>(
unwrap_client_response::<C, BTreeSet<WeightedValidator>>(
RPC.vp()
.pos()
.consensus_validator_set(client, &Some(epoch))
.await,
);
let below_capacity =
unwrap_client_response::<C, HashSet<WeightedValidator>>(
unwrap_client_response::<C, BTreeSet<WeightedValidator>>(
RPC.vp()
.pos()
.below_capacity_validator_set(client, &Some(epoch))
.await,
);

let sorted_consensus = consensus.into_iter().sorted_by_key(|v| {
-(i128::try_from(v.bonded_stake.change()))
.expect("Failed to sort consensus validators")
});

// Iterate all validators
let stdout = io::stdout();
let mut w = stdout.lock();

writeln!(w, "Consensus validators:").unwrap();
for val in sorted_consensus {
for val in consensus.into_iter().rev() {
writeln!(
w,
" {}: {}",
Expand All @@ -1601,13 +1596,8 @@ pub async fn query_bonded_stake<C: namada::ledger::queries::Client + Sync>(
.unwrap();
}
if !below_capacity.is_empty() {
let sorted_below_capacity =
below_capacity.into_iter().sorted_by_key(|v| {
-(i128::try_from(v.bonded_stake.change()))
.expect("Failed to sort consensus validators")
});
writeln!(w, "Below capacity validators:").unwrap();
for val in sorted_below_capacity {
for val in below_capacity.into_iter().rev() {
writeln!(
w,
" {}: {}",
Expand Down
4 changes: 2 additions & 2 deletions proof_of_stake/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ where
pub fn read_consensus_validator_set_addresses_with_stake<S>(
storage: &S,
epoch: namada_core::types::storage::Epoch,
) -> storage_api::Result<HashSet<WeightedValidator>>
) -> storage_api::Result<BTreeSet<WeightedValidator>>
where
S: StorageRead,
{
Expand Down Expand Up @@ -792,7 +792,7 @@ where
pub fn read_below_capacity_validator_set_addresses_with_stake<S>(
storage: &S,
epoch: namada_core::types::storage::Epoch,
) -> storage_api::Result<HashSet<WeightedValidator>>
) -> storage_api::Result<BTreeSet<WeightedValidator>>
where
S: StorageRead,
{
Expand Down
68 changes: 17 additions & 51 deletions shared/src/ledger/queries/vp/pos.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Queries router and handlers for PoS validity predicate

use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use namada_core::ledger::storage_api::collections::lazy_map;
Expand All @@ -10,13 +10,14 @@ use namada_proof_of_stake::types::{
Slash, ValidatorState, WeightedValidator,
};
use namada_proof_of_stake::{
self, below_capacity_validator_set_handle, bond_amount, bond_handle,
consensus_validator_set_handle, find_all_enqueued_slashes,
self, bond_amount, bond_handle, find_all_enqueued_slashes,
find_all_slashes, find_delegation_validators, find_delegations,
read_all_validator_addresses, read_pos_params, read_total_stake,
read_validator_max_commission_rate_change, read_validator_stake,
unbond_handle, validator_commission_rate_handle, validator_slashes_handle,
validator_state_handle,
read_all_validator_addresses,
read_below_capacity_validator_set_addresses_with_stake,
read_consensus_validator_set_addresses_with_stake, read_pos_params,
read_total_stake, read_validator_max_commission_rate_change,
read_validator_stake, unbond_handle, validator_commission_rate_handle,
validator_slashes_handle, validator_state_handle,
};

use crate::ledger::queries::types::RequestCtx;
Expand Down Expand Up @@ -51,10 +52,10 @@ router! {POS,

( "validator_set" ) = {
( "consensus" / [epoch: opt Epoch] )
-> HashSet<WeightedValidator> = consensus_validator_set,
-> BTreeSet<WeightedValidator> = consensus_validator_set,

( "below_capacity" / [epoch: opt Epoch] )
-> HashSet<WeightedValidator> = below_capacity_validator_set,
-> BTreeSet<WeightedValidator> = below_capacity_validator_set,

// TODO: add "below_threshold"
},
Expand Down Expand Up @@ -253,64 +254,29 @@ where
fn consensus_validator_set<D, H>(
ctx: RequestCtx<'_, D, H>,
epoch: Option<Epoch>,
) -> storage_api::Result<HashSet<WeightedValidator>>
) -> storage_api::Result<BTreeSet<WeightedValidator>>
where
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
{
let epoch = epoch.unwrap_or(ctx.wl_storage.storage.last_epoch);
consensus_validator_set_handle()
.at(&epoch)
.iter(ctx.wl_storage)?
.map(|next_result| {
next_result.map(
|(
lazy_map::NestedSubKey::Data {
key: bonded_stake,
nested_sub_key: _position,
},
address,
)| {
WeightedValidator {
bonded_stake,
address,
}
},
)
})
.collect()
read_consensus_validator_set_addresses_with_stake(ctx.wl_storage, epoch)
}

/// Get all the validator in the below-capacity set with their bonded stake.
fn below_capacity_validator_set<D, H>(
ctx: RequestCtx<'_, D, H>,
epoch: Option<Epoch>,
) -> storage_api::Result<HashSet<WeightedValidator>>
) -> storage_api::Result<BTreeSet<WeightedValidator>>
where
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
{
let epoch = epoch.unwrap_or(ctx.wl_storage.storage.last_epoch);
below_capacity_validator_set_handle()
.at(&epoch)
.iter(ctx.wl_storage)?
.map(|next_result| {
next_result.map(
|(
lazy_map::NestedSubKey::Data {
key: bonded_stake,
nested_sub_key: _position,
},
address,
)| {
WeightedValidator {
bonded_stake: bonded_stake.into(),
address,
}
},
)
})
.collect()
read_below_capacity_validator_set_addresses_with_stake(
ctx.wl_storage,
epoch,
)
}

/// Get the total stake in PoS system at the given epoch or current when `None`.
Expand Down
6 changes: 3 additions & 3 deletions wasm/wasm_source/src/tx_bond.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn apply_tx(ctx: &mut Ctx, tx_data: Tx) -> TxResult {

#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::collections::BTreeSet;

use namada::ledger::pos::{GenesisValidator, PosParams, PosVP};
use namada::proof_of_stake::{
Expand Down Expand Up @@ -132,7 +132,7 @@ mod tests {
// Read some data before the tx is executed
let mut epoched_total_stake_pre: Vec<token::Amount> = Vec::new();
let mut epoched_validator_stake_pre: Vec<token::Amount> = Vec::new();
let mut epoched_validator_set_pre: Vec<HashSet<WeightedValidator>> =
let mut epoched_validator_set_pre: Vec<BTreeSet<WeightedValidator>> =
Vec::new();

for epoch in 0..=pos_params.unbonding_len {
Expand Down Expand Up @@ -163,7 +163,7 @@ mod tests {
// Read the data after the tx is executed.
let mut epoched_total_stake_post: Vec<token::Amount> = Vec::new();
let mut epoched_validator_stake_post: Vec<token::Amount> = Vec::new();
let mut epoched_validator_set_post: Vec<HashSet<WeightedValidator>> =
let mut epoched_validator_set_post: Vec<BTreeSet<WeightedValidator>> =
Vec::new();

println!("\nFILLING POST STATE\n");
Expand Down
4 changes: 2 additions & 2 deletions wasm/wasm_source/src/tx_unbond.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn apply_tx(ctx: &mut Ctx, tx_data: Tx) -> TxResult {

#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::collections::BTreeSet;

use namada::ledger::pos::{GenesisValidator, PosParams, PosVP};
use namada::proof_of_stake::types::WeightedValidator;
Expand Down Expand Up @@ -164,7 +164,7 @@ mod tests {
let mut epoched_total_stake_pre: Vec<token::Amount> = Vec::new();
let mut epoched_validator_stake_pre: Vec<token::Amount> = Vec::new();
let mut epoched_bonds_pre: Vec<Option<token::Amount>> = Vec::new();
let mut epoched_validator_set_pre: Vec<HashSet<WeightedValidator>> =
let mut epoched_validator_set_pre: Vec<BTreeSet<WeightedValidator>> =
Vec::new();

for epoch in 0..=pos_params.unbonding_len {
Expand Down

0 comments on commit b39d3ef

Please sign in to comment.