Skip to content

Commit

Permalink
Merge branch 'origin/bat/feature/uint256-amount' (#1282)
Browse files Browse the repository at this point in the history
  • Loading branch information
batconjurer committed Jun 29, 2023
1 parent cd77fb1 commit 202b1fc
Show file tree
Hide file tree
Showing 15 changed files with 685 additions and 320 deletions.
396 changes: 270 additions & 126 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions apps/src/lib/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3023,9 +3023,9 @@ pub mod args {
"The token address that queried transfers must involve.",
))
.arg(
SUB_PREFIX.def().about(
"The token's sub prefix whose balance to query.",
),
SUB_PREFIX
.def()
.help("The token's sub prefix whose balance to query."),
)
}
}
Expand Down
8 changes: 4 additions & 4 deletions apps/src/lib/node/ledger/storage/rocksdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1312,7 +1312,7 @@ fn iter_subspace_prefix<'iter>(
.get_column_family(SUBSPACE_CF)
.expect("{SUBSPACE_CF} column family should exist");
let db_prefix = "".to_owned();
let prefix = prefix.map(|k| k.to_string()).unwrap_or_default();
let prefix = prefix.map(|k| k.to_string());
iter_prefix(db, subspace_cf, db_prefix, prefix)
}

Expand Down Expand Up @@ -1632,19 +1632,19 @@ mod test {
db.exec_batch(batch.0).unwrap();

let itered_keys: Vec<Key> = db
.iter_optional_prefix(Some(&prefix_0))
.iter_prefix(Some(&prefix_0))
.map(|(key, _val, _)| Key::parse(key).unwrap())
.collect();
itertools::assert_equal(keys_0, itered_keys);

let itered_keys: Vec<Key> = db
.iter_optional_prefix(Some(&prefix_1))
.iter_prefix(Some(&prefix_1))
.map(|(key, _val, _)| Key::parse(key).unwrap())
.collect();
itertools::assert_equal(keys_1, itered_keys);

let itered_keys: Vec<Key> = db
.iter_optional_prefix(None)
.iter_prefix(None)
.map(|(key, _val, _)| Key::parse(key).unwrap())
.collect();
itertools::assert_equal(all_keys, itered_keys);
Expand Down
33 changes: 19 additions & 14 deletions core/src/types/dec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,6 @@ pub type Result<T> = std::result::Result<T, Error>;
#[serde(into = "String")]
pub struct Dec(pub I256);

impl std::ops::Deref for Dec {
type Target = I256;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl std::ops::DerefMut for Dec {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

impl Dec {
/// Division with truncation (TODO: better description)
pub fn trunc_div(&self, rhs: &Self) -> Option<Self> {
Expand All @@ -89,6 +75,11 @@ impl Dec {
Self(I256::zero())
}

/// Check if value is zero
pub fn is_zero(&self) -> bool {
*self == Self::zero()
}

/// The representation of 1
pub fn one() -> Self {
Self(I256(
Expand Down Expand Up @@ -131,6 +122,11 @@ impl Dec {
}
}

/// Get the absolute value of self as integer
pub fn abs(&self) -> Uint {
self.0.abs()
}

/// Convert the Dec type into a I256 with truncation
pub fn to_i256(&self) -> I256 {
self.0 / Uint::exp10(POS_DECIMAL_PRECISION as usize)
Expand Down Expand Up @@ -617,4 +613,13 @@ mod test_dec {
.unwrap()
);
}

#[test]
fn test_dec_to_string() {
let one = Dec::one();
let string = one.to_string();
assert_eq!(&string, "1");
let one_third = Dec::new(6667, 4).expect("Test failed");
assert_eq!(&one_third.to_string(), "0.6667")
}
}
5 changes: 0 additions & 5 deletions core/src/types/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,6 @@ impl Amount {
self.raw.try_into().unwrap()
}

/// Get the raw micro amount as a u64 value
pub fn raw_amount(&self) -> u64 {
self.micro
}

/// Spend a given amount.
/// Panics when given `amount` > `self.raw` amount.
pub fn spend(&mut self, amount: &Amount) {
Expand Down
6 changes: 6 additions & 0 deletions proof_of_stake/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3290,6 +3290,9 @@ where
.at(&epoch)
.at(&token::Amount::from_change(amount_pre))
.remove(storage, &val_position)?;
validator_set_positions_handle()
.at(&epoch)
.remove(storage, validator)?;

// For the pipeline epoch only:
// promote the next max inactive validator to the active
Expand Down Expand Up @@ -3346,6 +3349,9 @@ where
.at(&epoch)
.at(&token::Amount::from_change(amount_pre).into())
.remove(storage, &val_position)?;
validator_set_positions_handle()
.at(&epoch)
.remove(storage, validator)?;
}
ValidatorState::BelowThreshold => {
println!("Below-threshold");
Expand Down
2 changes: 1 addition & 1 deletion proof_of_stake/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl Default for PosParams {
light_client_attack_min_slash_rate: Dec::new(1, 3)
.expect("Test failed"),
cubic_slashing_window_length: 1,
validator_stake_threshold: token::Amount::whole(1_u64),
validator_stake_threshold: token::Amount::native_whole(1_u64),
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions proof_of_stake/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1973,8 +1973,9 @@ fn arb_genesis_validators(
// If there's a threshold, make sure that at least one validator
// has at least a stake greater or equal to the threshold to
// avoid having an empty consensus set.
threshold.map(|token| token.raw_amount().as_u64()).unwrap_or(1)
..=10_000_000_u64
threshold
.map(|token| token.raw_amount().as_u64())
.unwrap_or(1)..=10_000_000_u64
} else {
1..=10_000_000_u64
}
Expand All @@ -1994,7 +1995,8 @@ fn arb_genesis_validators(
let consensus_key = consensus_sk.to_public();

let commission_rate = Dec::new(5, 2).expect("Test failed");
let max_commission_rate_change = Dec::new(1, 2).expect("Test failed");
let max_commission_rate_change =
Dec::new(1, 2).expect("Test failed");
GenesisValidator {
address,
tokens,
Expand Down
7 changes: 4 additions & 3 deletions proof_of_stake/src/tests/state_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1091,7 +1091,7 @@ impl ConcretePosState {
tracing::debug!(
"Below-thresh val {}, stake {}",
&validator,
stake
stake.to_string_native()
);

let state = crate::validator_state_handle(&validator)
Expand Down Expand Up @@ -2983,7 +2983,8 @@ impl AbstractPosState {
if max_bc > min_consensus {
println!(
"min_consensus = {}, max_bc = {}",
min_consensus, max_bc
min_consensus.to_string_native(),
max_bc.to_string_native()
);
}
assert!(min_consensus >= max_bc);
Expand All @@ -3006,7 +3007,7 @@ impl AbstractPosState {
tracing::debug!(
"Below-thresh val {}, stake {} - ({:?})",
addr,
&stake,
stake.to_string_native(),
state
);

Expand Down
2 changes: 1 addition & 1 deletion shared/src/ledger/queries/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub trait Router {
pub trait Client {
/// `std::io::Error` can happen in decoding with
/// `BorshDeserialize::try_from_slice`
type Error: From<std::io::Error>;
type Error: From<std::io::Error> + std::fmt::Display;

/// Send a simple query request at the given path. For more options, use the
/// `request` method.
Expand Down
4 changes: 2 additions & 2 deletions shared/src/ledger/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ pub async fn query_block<C: crate::ledger::queries::Client + Sync>(
fn unwrap_client_response<C: crate::ledger::queries::Client, T>(
response: Result<T, C::Error>,
) -> T {
response.unwrap_or_else(|_err| {
panic!("Error in the query");
response.unwrap_or_else(|err| {
panic!("Error in the query: {}", err);
})
}

Expand Down
40 changes: 29 additions & 11 deletions shared/src/ledger/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use masp_primitives::transaction::components::Amount;
use namada_core::types::address::{masp, masp_tx_key, Address};
use namada_core::types::dec::Dec;
use namada_core::types::storage::Key;
use namada_core::types::token::MaspDenom;
use namada_core::types::token::{MaspDenom, TokenAddress};
use namada_proof_of_stake::parameters::PosParams;
use namada_proof_of_stake::types::CommissionPair;
use prost::EncodeError;
Expand All @@ -37,7 +37,10 @@ use crate::ibc_proto::cosmos::base::v1beta1::Coin;
use crate::ledger::args::{self, InputAmount};
use crate::ledger::governance::storage as gov_storage;
use crate::ledger::masp::{ShieldedContext, ShieldedUtils};
use crate::ledger::rpc::{self, validate_amount, TxBroadcastData, TxResponse};
use crate::ledger::rpc::{
self, format_denominated_amount, validate_amount, TxBroadcastData,
TxResponse,
};
use crate::ledger::signing::{find_keypair, sign_tx, tx_signer, TxSigningKey};
use crate::ledger::wallet::{Wallet, WalletUtils};
use crate::proto::{Code, Data, MaspBuilder, Section, Signature, Tx};
Expand Down Expand Up @@ -970,7 +973,10 @@ pub async fn submit_bond<

// TODO Should we state the same error message for the native token?
check_balance_too_low_err(
&args.native_token,
&TokenAddress {
address: args.native_token,
sub_prefix: None,
},
bond_source,
args.amount,
balance_key,
Expand Down Expand Up @@ -1072,7 +1078,10 @@ pub async fn submit_ibc_transfer<
};

check_balance_too_low_err(
&token,
&TokenAddress {
address: token.clone(),
sub_prefix: sub_prefix.clone(),
},
&source,
args.amount,
balance_key,
Expand Down Expand Up @@ -1283,9 +1292,15 @@ pub async fn submit_transfer<

args.amount = InputAmount::Validated(validated_amount);
args.tx.fee_amount = InputAmount::Validated(validate_fee);

let sub_prefix = args
.sub_prefix
.as_ref()
.map(|k| k.parse().expect("Could not parse multi-token sub-prefix"));
check_balance_too_low_err::<C>(
&token,
&TokenAddress {
address: token.clone(),
sub_prefix: sub_prefix.clone(),
},
&source,
validated_amount.amount,
balance_key,
Expand Down Expand Up @@ -1765,7 +1780,7 @@ async fn target_exists_or_err<C: crate::ledger::queries::Client + Sync>(
/// given amount, along with the balance even existing. force
/// overrides this
async fn check_balance_too_low_err<C: crate::ledger::queries::Client + Sync>(
token: &Address,
token: &TokenAddress,
source: &Address,
amount: token::Amount,
balance_key: storage::Key,
Expand All @@ -1784,14 +1799,14 @@ async fn check_balance_too_low_err<C: crate::ledger::queries::Client + Sync>(
transfer is {} and the balance is {}.",
source,
token,
amount.to_string_native(),
balance.to_string_native()
format_denominated_amount(client, token, amount).await,
format_denominated_amount(client, token, balance).await,
);
Ok(())
} else {
Err(Error::BalanceTooLow(
source.clone(),
token.clone(),
token.address.clone(),
amount.to_string_native(),
balance.to_string_native(),
))
Expand All @@ -1808,7 +1823,10 @@ async fn check_balance_too_low_err<C: crate::ledger::queries::Client + Sync>(
);
Ok(())
} else {
Err(Error::NoBalanceForToken(source.clone(), token.clone()))
Err(Error::NoBalanceForToken(
source.clone(),
token.address.clone(),
))
}
}
}
Expand Down
Loading

0 comments on commit 202b1fc

Please sign in to comment.