Skip to content

Commit

Permalink
refactor out VotingPower in proof_of_stake::types
Browse files Browse the repository at this point in the history
  • Loading branch information
brentstone committed Sep 13, 2022
1 parent 03bf5ee commit f83cc5d
Showing 1 changed file with 13 additions and 143 deletions.
156 changes: 13 additions & 143 deletions proof_of_stake/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::convert::TryFrom;
use std::fmt::Display;
use std::hash::Hash;
use std::num::TryFromIntError;
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::ops::{Add, AddAssign, Sub};

use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use rust_decimal::prelude::ToPrimitive;
Expand All @@ -25,9 +25,7 @@ pub type ValidatorStates = Epoched<ValidatorState, OffsetPipelineLen>;
/// Epoched validator's total deltas.
pub type ValidatorTotalDeltas<TokenChange> =
EpochedDelta<TokenChange, OffsetUnbondingLen>;
/// Epoched validator's voting power.
pub type ValidatorVotingPowers =
EpochedDelta<VotingPowerDelta, OffsetUnbondingLen>;

/// Epoched bond.
pub type Bonds<TokenAmount> =
EpochedDelta<Bond<TokenAmount>, OffsetUnbondingLen>;
Expand All @@ -37,8 +35,8 @@ pub type Unbonds<TokenAmount> =
/// Epoched validator set.
pub type ValidatorSets<Address> =
Epoched<ValidatorSet<Address>, OffsetUnbondingLen>;
/// Epoched total voting power.
pub type TotalVotingPowers = EpochedDelta<VotingPowerDelta, OffsetUnbondingLen>;
/// Epoched total total deltas.
pub type TotalDeltas<TokenChange> = EpochedDelta<TokenChange, OffsetUnbondingLen>;

/// Epoch identifier. Epochs are identified by consecutive natural numbers.
///
Expand All @@ -61,23 +59,6 @@ pub type TotalVotingPowers = EpochedDelta<VotingPowerDelta, OffsetUnbondingLen>;
)]
pub struct Epoch(u64);

/// Voting power is calculated from staked tokens.
#[derive(
Debug,
Default,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
BorshDeserialize,
BorshSerialize,
BorshSchema,
)]
pub struct VotingPower(u64);

/// A change of voting power.
#[derive(
Debug,
Expand Down Expand Up @@ -135,8 +116,8 @@ pub enum ValidatorSetUpdate<PK> {
pub struct ActiveValidator<PK> {
/// A public key used for signing validator's consensus actions
pub consensus_key: PK,
/// Voting power
pub voting_power: VotingPower,
/// Total bonded stake of the validator
pub bonded_stake: u64,
}

/// ID of a bond and/or an unbond.
Expand Down Expand Up @@ -197,11 +178,11 @@ where
+ BorshSchema
+ BorshSerialize,
{
/// The `voting_power` field must be on top, because lexicographic ordering
/// The `total_stake` field must be on top, because lexicographic ordering
/// is based on the top-to-bottom declaration order and in the
/// `ValidatorSet` the `WeightedValidator`s these need to be sorted by
/// the `voting_power`.
pub voting_power: VotingPower,
/// the `total_stake`.
pub bonded_stake: u64,
/// Validator's address
pub address: Address,
}
Expand All @@ -224,7 +205,7 @@ where
write!(
f,
"{} with voting power {}",
self.address, self.voting_power
self.address, self.bonded_stake
)
}
}
Expand Down Expand Up @@ -348,8 +329,8 @@ pub struct VoteInfo {
/// from tendermint
pub validator_address: Vec<u8>,
/// validator voting power
pub validator_vp: VotingPower,
/// whether the validator signature was included in the last block
pub validator_vp: u64,
/// was the validator signature was included in the last block?
pub signed_last_block: bool,
}

Expand All @@ -359,7 +340,7 @@ impl From<tendermint_proto::abci::VoteInfo> for VoteInfo {
let val_info = info.validator.clone().unwrap();
VoteInfo {
validator_address: info.validator.unwrap().address,
validator_vp: VotingPower::from(val_info.power as u64),
validator_vp: val_info.power as u64,
signed_last_block: info.signed_last_block,
}
}
Expand All @@ -371,86 +352,8 @@ pub trait PublicKeyTmRawHash {
fn tm_raw_hash(&self) -> String;
}

impl VotingPower {
/// Convert token amount into a voting power.
pub fn from_tokens(tokens: impl Into<u64>, params: &PosParams) -> Self {
// The token amount is expected to be in micro units already
let vp = decimal_mult_u64(params.tm_votes_per_token, tokens.into());
Self(vp)
}
}

impl Add for VotingPower {
type Output = VotingPower;

fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}

impl Sub for VotingPower {
type Output = VotingPower;

fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}

impl VotingPowerDelta {
/// Try to convert token change into a voting power change.
pub fn try_from_token_change(
change: impl Into<i128>,
params: &PosParams,
) -> Result<Self, TryFromIntError> {
// The token amount is expected to be in micro units already
let vp = params.tm_votes_per_token
* Decimal::from(Into::<i128>::into(change));
let delta: i128 = vp.to_i128().unwrap();
let delta: i64 = TryFrom::try_from(delta)?;
Ok(Self(delta))
}

/// Try to convert token amount into a voting power change.
pub fn try_from_tokens(
tokens: impl Into<u64>,
params: &PosParams,
) -> Result<Self, TryFromIntError> {
// The token amount is expected to be in micro units already
let vp = decimal_mult_u64(params.tm_votes_per_token, tokens.into());
let delta: i64 = TryFrom::try_from(vp.to_i64().unwrap())?;
Ok(Self(delta))
}
}

impl TryFrom<VotingPower> for VotingPowerDelta {
type Error = TryFromIntError;

fn try_from(value: VotingPower) -> Result<Self, Self::Error> {
let delta: i64 = TryFrom::try_from(value.0)?;
Ok(Self(delta))
}
}

impl TryFrom<VotingPowerDelta> for VotingPower {
type Error = TryFromIntError;

fn try_from(value: VotingPowerDelta) -> Result<Self, Self::Error> {
let vp: u64 = TryFrom::try_from(value.0)?;
Ok(Self(vp))
}
}

impl Display for VotingPower {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

impl Display for VotingPowerDelta {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

impl Epoch {
/// Iterate a range of consecutive epochs starting from `self` of a given
Expand Down Expand Up @@ -647,29 +550,6 @@ where
}
}

impl From<u64> for VotingPower {
fn from(voting_power: u64) -> Self {
Self(voting_power)
}
}

impl From<VotingPower> for u64 {
fn from(vp: VotingPower) -> Self {
vp.0
}
}

impl AddAssign for VotingPower {
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0
}
}

impl SubAssign for VotingPower {
fn sub_assign(&mut self, rhs: Self) {
self.0 -= rhs.0
}
}

impl From<i64> for VotingPowerDelta {
fn from(delta: i64) -> Self {
Expand Down Expand Up @@ -713,16 +593,6 @@ impl Sub<i64> for VotingPowerDelta {
}
}

impl<Address, Token, PK> GenesisValidator<Address, Token, PK>
where
Token: Copy + Into<u64>,
{
/// Calculate validator's voting power
pub fn voting_power(&self, params: &PosParams) -> VotingPower {
VotingPower::from_tokens(self.tokens, params)
}
}

impl SlashType {
/// Get the slash rate applicable to the given slash type from the PoS
/// parameters.
Expand Down

0 comments on commit f83cc5d

Please sign in to comment.