From 66d026bcda634f7d81892670531e6d1d5047eb73 Mon Sep 17 00:00:00 2001 From: Christoph Otter Date: Mon, 15 May 2023 13:04:01 +0200 Subject: [PATCH] Check for missing amount when parsing Coin --- packages/std/src/coin.rs | 24 ++++++++++++++++++++---- packages/std/src/errors/std_error.rs | 2 ++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/std/src/coin.rs b/packages/std/src/coin.rs index 9c8798a005..b88a6da3ee 100644 --- a/packages/std/src/coin.rs +++ b/packages/std/src/coin.rs @@ -28,6 +28,10 @@ impl FromStr for Coin { .ok_or(CoinFromStrError::MissingDenom)?; let (amount, denom) = s.split_at(pos); + if amount.is_empty() { + return Err(CoinFromStrError::MissingAmount); + } + Ok(Coin { amount: amount.parse::()?.into(), denom: denom.to_string(), @@ -205,12 +209,24 @@ mod tests { CoinFromStrError::MissingDenom ); assert_eq!( - Coin::from_str("ucosm").unwrap_err().to_string(), - "Invalid amount: cannot parse integer from empty string" + Coin::from_str("ucosm").unwrap_err(), // no amount + CoinFromStrError::MissingAmount + ); + assert_eq!( + Coin::from_str("-123ucosm").unwrap_err(), // negative amount + CoinFromStrError::MissingAmount + ); + assert_eq!( + Coin::from_str("").unwrap_err(), // empty input + CoinFromStrError::MissingDenom + ); + assert_eq!( + Coin::from_str(" 1ucosm").unwrap_err(), // unsupported whitespace + CoinFromStrError::MissingAmount ); assert_eq!( - Coin::from_str("-123ucosm").unwrap_err().to_string(), - "Invalid amount: cannot parse integer from empty string" + Coin::from_str("�1ucosm").unwrap_err(), // other broken data + CoinFromStrError::MissingAmount ); assert_eq!( Coin::from_str("340282366920938463463374607431768211456ucosm") diff --git a/packages/std/src/errors/std_error.rs b/packages/std/src/errors/std_error.rs index 7093167590..d90171c74c 100644 --- a/packages/std/src/errors/std_error.rs +++ b/packages/std/src/errors/std_error.rs @@ -594,6 +594,8 @@ pub struct RoundUpOverflowError; pub enum CoinFromStrError { #[error("Missing denominator")] MissingDenom, + #[error("Missing amount or non-digit characters in amount")] + MissingAmount, #[error("Invalid amount: {0}")] InvalidAmount(std::num::ParseIntError), }