taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

amount.rs (17677B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2024, 2025, 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 //! Type for the Taler Amount <https://docs.taler.net/core/api-common.html#tsref-type-Amount>
     18 
     19 use std::{
     20     fmt::{Debug, Display},
     21     num::ParseIntError,
     22     str::FromStr,
     23 };
     24 
     25 use compact_str::format_compact;
     26 
     27 use super::utils::InlineStr;
     28 use crate::signature::Buf;
     29 
     30 /** Number of characters we use to represent currency names */
     31 // We use the same value than the exchange -1 because we use a byte for the len instead of 0 termination
     32 pub const CURRENCY_LEN: usize = 11;
     33 
     34 /** Maximum legal value for an amount, based on IEEE double */
     35 pub const MAX_VALUE: u64 = 2 << 51;
     36 
     37 /** The number of digits in a fraction part of an amount */
     38 pub const FRAC_BASE_NB_DIGITS: u8 = 8;
     39 
     40 /** The fraction part of an amount represents which fraction of the value */
     41 pub const FRAC_BASE: u32 = 10u32.pow(FRAC_BASE_NB_DIGITS as u32);
     42 
     43 const CENT_FRACTION: u32 = 10u32.pow((FRAC_BASE_NB_DIGITS - 2) as u32);
     44 
     45 #[derive(
     46     Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay,
     47 )]
     48 /// Inlined ISO 4217 currency string
     49 pub struct Currency(InlineStr<CURRENCY_LEN>);
     50 
     51 impl AsRef<str> for Currency {
     52     fn as_ref(&self) -> &str {
     53         self.0.as_ref()
     54     }
     55 }
     56 
     57 #[derive(Debug, thiserror::Error)]
     58 pub enum CurrencyErrorKind {
     59     #[error("contains illegal characters (only A-Z allowed)")]
     60     Invalid,
     61     #[error("too long (max {CURRENCY_LEN} chars)")]
     62     Big,
     63     #[error("is empty")]
     64     Empty,
     65 }
     66 
     67 #[derive(Debug, thiserror::Error)]
     68 #[error("currency code name '{currency}' {kind}")]
     69 pub struct ParseCurrencyError {
     70     currency: String,
     71     pub kind: CurrencyErrorKind,
     72 }
     73 
     74 impl Currency {
     75     pub const TEST: Self = Self::const_parse("TEST");
     76     pub const KUDOS: Self = Self::const_parse("KUDOS");
     77     pub const EUR: Self = Self::const_parse("EUR");
     78     pub const CHF: Self = Self::const_parse("CHF");
     79     pub const HUF: Self = Self::const_parse("HUF");
     80     pub const USD: Self = Self::const_parse("USD");
     81     pub const GBP: Self = Self::const_parse("GBP");
     82     pub const AUD: Self = Self::const_parse("AUD");
     83 
     84     pub const fn const_parse(s: &str) -> Currency {
     85         let bytes = s.as_bytes();
     86         let len = bytes.len();
     87 
     88         if bytes.is_empty() {
     89             panic!("empty")
     90         } else if len > CURRENCY_LEN {
     91             panic!("too big")
     92         }
     93         let mut i = 0;
     94         while i < bytes.len() {
     95             if !bytes[i].is_ascii_uppercase() {
     96                 panic!("invalid")
     97             }
     98             i += 1;
     99         }
    100         Self(InlineStr::copy_from_slice(bytes))
    101     }
    102 }
    103 
    104 impl FromStr for Currency {
    105     type Err = ParseCurrencyError;
    106 
    107     fn from_str(s: &str) -> Result<Self, Self::Err> {
    108         let bytes = s.as_bytes();
    109         let len = bytes.len();
    110         if bytes.is_empty() {
    111             Err(CurrencyErrorKind::Empty)
    112         } else if len > CURRENCY_LEN {
    113             Err(CurrencyErrorKind::Big)
    114         } else if !bytes.iter().all(|c| c.is_ascii_uppercase()) {
    115             Err(CurrencyErrorKind::Invalid)
    116         } else {
    117             Ok(Self(InlineStr::copy_from_slice(bytes)))
    118         }
    119         .map_err(|kind| ParseCurrencyError {
    120             currency: s.to_owned(),
    121             kind,
    122         })
    123     }
    124 }
    125 
    126 impl Debug for Currency {
    127     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    128         Debug::fmt(&self.as_ref(), f)
    129     }
    130 }
    131 
    132 impl Display for Currency {
    133     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    134         Display::fmt(&self.as_ref(), f)
    135     }
    136 }
    137 
    138 #[derive(sqlx::Type)]
    139 #[sqlx(type_name = "taler_amount")]
    140 struct PgTalerAmount {
    141     pub val: i64,
    142     pub frac: i32,
    143 }
    144 
    145 #[derive(
    146     Clone,
    147     Copy,
    148     PartialEq,
    149     Eq,
    150     PartialOrd,
    151     Ord,
    152     serde_with::DeserializeFromStr,
    153     serde_with::SerializeDisplay,
    154 )]
    155 pub struct Decimal {
    156     /** Integer part */
    157     pub val: u64,
    158     /** Factional part, multiple of FRAC_BASE */
    159     pub frac: u32,
    160 }
    161 
    162 impl Decimal {
    163     pub const fn new(val: u64, frac: u32) -> Self {
    164         Self { val, frac }
    165     }
    166 
    167     pub const ZERO: Self = Self::new(0, 0);
    168     pub const MAX: Self = Self::new(MAX_VALUE, FRAC_BASE - 1);
    169 
    170     const fn normalize(mut self) -> Option<Self> {
    171         let Some(val) = self.val.checked_add((self.frac / FRAC_BASE) as u64) else {
    172             return None;
    173         };
    174         self.val = val;
    175         self.frac %= FRAC_BASE;
    176         if self.val > MAX_VALUE {
    177             return None;
    178         }
    179         Some(self)
    180     }
    181 
    182     pub fn try_add(mut self, rhs: &Self) -> Option<Self> {
    183         self.val = self.val.checked_add(rhs.val)?;
    184         self.frac = self
    185             .frac
    186             .checked_add(rhs.frac)
    187             .expect("amount fraction overflow should never happen with normalized amounts");
    188         self.normalize()
    189     }
    190 
    191     pub fn try_sub(mut self, rhs: &Self) -> Option<Self> {
    192         if rhs.frac > self.frac {
    193             self.val = self.val.checked_sub(1)?;
    194             self.frac += FRAC_BASE;
    195         }
    196         self.val = self.val.checked_sub(rhs.val)?;
    197         self.frac = self.frac.checked_sub(rhs.frac)?;
    198         self.normalize()
    199     }
    200 
    201     pub const fn to_amount(self, currency: &Currency) -> Amount {
    202         Amount::new_decimal(currency, self)
    203     }
    204 }
    205 
    206 #[derive(Debug, thiserror::Error)]
    207 pub enum DecimalErrKind {
    208     #[error("value overflow (must be <= {MAX_VALUE})")]
    209     Overflow,
    210     #[error("invalid value ({0})")]
    211     InvalidValue(ParseIntError),
    212     #[error("invalid fraction ({0})")]
    213     InvalidFraction(ParseIntError),
    214     #[error("fraction overflow (max {FRAC_BASE_NB_DIGITS} digits)")]
    215     FractionOverflow,
    216 }
    217 
    218 #[derive(Debug, thiserror::Error)]
    219 #[error("decimal '{decimal}' {kind}")]
    220 pub struct ParseDecimalErr {
    221     decimal: String,
    222     pub kind: DecimalErrKind,
    223 }
    224 
    225 impl FromStr for Decimal {
    226     type Err = ParseDecimalErr;
    227 
    228     fn from_str(s: &str) -> Result<Self, Self::Err> {
    229         let (value, fraction) = match s.split_once('.') {
    230             Some((v, f)) => (v, Some(f)),
    231             None => (s, None),
    232         };
    233 
    234         // TODO use try block when stable
    235         (|| {
    236             let value_str = if value.starts_with('+') { "+" } else { value };
    237             let value: u64 = value_str.parse().map_err(DecimalErrKind::InvalidValue)?;
    238             if value > MAX_VALUE {
    239                 return Err(DecimalErrKind::Overflow);
    240             }
    241 
    242             let fraction: u32 = match fraction {
    243                 None => 0,
    244                 Some(f) => {
    245                     if f.len() > FRAC_BASE_NB_DIGITS as usize {
    246                         return Err(DecimalErrKind::FractionOverflow);
    247                     }
    248                     // Reject leading '+' (which would also skew f.len()) and empty fraction after '.'
    249                     let frac_str = if f.starts_with('+') { "+" } else { f };
    250                     frac_str
    251                         .parse::<u32>()
    252                         .map_err(DecimalErrKind::InvalidFraction)?
    253                         * 10u32.pow(FRAC_BASE_NB_DIGITS as u32 - f.len() as u32)
    254                 }
    255             };
    256             Ok(Self {
    257                 val: value,
    258                 frac: fraction,
    259             })
    260         })()
    261         .map_err(|kind| ParseDecimalErr {
    262             decimal: s.to_owned(),
    263             kind,
    264         })
    265     }
    266 }
    267 
    268 impl Display for Decimal {
    269     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    270         if self.frac == 0 {
    271             f.write_fmt(format_args!("{}", self.val))
    272         } else {
    273             let num = format_compact!("{:08}", self.frac);
    274             f.write_fmt(format_args!("{}.{}", self.val, num.trim_end_matches('0')))
    275         }
    276     }
    277 }
    278 
    279 impl Debug for Decimal {
    280     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    281         Display::fmt(&self, f)
    282     }
    283 }
    284 
    285 impl sqlx::Type<sqlx::Postgres> for Decimal {
    286     fn type_info() -> sqlx::postgres::PgTypeInfo {
    287         PgTalerAmount::type_info()
    288     }
    289 }
    290 
    291 impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Decimal {
    292     fn encode_by_ref(
    293         &self,
    294         buf: &mut sqlx::postgres::PgArgumentBuffer,
    295     ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
    296         PgTalerAmount {
    297             val: self.val as i64,
    298             frac: self.frac as i32,
    299         }
    300         .encode_by_ref(buf)
    301     }
    302 }
    303 
    304 impl<'r> sqlx::Decode<'r, sqlx::Postgres> for Decimal {
    305     fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
    306         let pg = PgTalerAmount::decode(value)?;
    307         Ok(Self {
    308             val: pg.val as u64,
    309             frac: pg.frac as u32,
    310         })
    311     }
    312 }
    313 
    314 #[track_caller]
    315 pub fn decimal(decimal: impl AsRef<str>) -> Decimal {
    316     decimal.as_ref().parse().expect("Invalid decimal constant")
    317 }
    318 
    319 /// <https://docs.taler.net/core/api-common.html#tsref-type-Amount>
    320 #[derive(
    321     Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay,
    322 )]
    323 pub struct Amount {
    324     pub currency: Currency,
    325     pub val: u64,
    326     pub frac: u32,
    327 }
    328 
    329 impl Amount {
    330     pub const fn new_decimal(currency: &Currency, decimal: Decimal) -> Self {
    331         Self {
    332             currency: *currency,
    333             val: decimal.val,
    334             frac: decimal.frac,
    335         }
    336     }
    337 
    338     pub const fn new(currency: &Currency, val: u64, frac: u32) -> Self {
    339         Self::new_decimal(currency, Decimal { val, frac })
    340     }
    341 
    342     pub const fn max(currency: &Currency) -> Self {
    343         Self::new_decimal(currency, Decimal::MAX)
    344     }
    345 
    346     pub const fn zero(currency: &Currency) -> Self {
    347         Self::new_decimal(currency, Decimal::ZERO)
    348     }
    349 
    350     pub fn is_zero(&self) -> bool {
    351         self.decimal() == Decimal::ZERO
    352     }
    353 
    354     /* Check is amount has fractional amount < 0.01 */
    355     pub const fn is_sub_cent(&self) -> bool {
    356         !self.frac.is_multiple_of(CENT_FRACTION)
    357     }
    358 
    359     pub const fn decimal(&self) -> Decimal {
    360         Decimal {
    361             val: self.val,
    362             frac: self.frac,
    363         }
    364     }
    365 
    366     pub fn normalize(self) -> Option<Self> {
    367         let decimal = self.decimal().normalize()?;
    368         Some((self.currency, decimal).into())
    369     }
    370 
    371     pub fn try_add(self, rhs: &Self) -> Option<Self> {
    372         if self.currency != rhs.currency {
    373             return None;
    374         }
    375         let decimal = self.decimal().try_add(&rhs.decimal())?;
    376         Some((self.currency, decimal).into())
    377     }
    378 
    379     pub fn try_sub(self, rhs: &Self) -> Option<Self> {
    380         if self.currency != rhs.currency {
    381             return None;
    382         }
    383         let decimal = self.decimal().try_sub(&rhs.decimal())?;
    384         Some((self.currency, decimal).into())
    385     }
    386 
    387     /** Encode amount for signature */
    388     pub fn signature_bytes(self) -> [u8; 24] {
    389         Buf::new()
    390             .put_u64(self.val)
    391             .put_u32(self.frac)
    392             .put(&self.currency.0)
    393             .finish()
    394     }
    395 }
    396 
    397 impl From<(Currency, Decimal)> for Amount {
    398     fn from((currency, decimal): (Currency, Decimal)) -> Self {
    399         Self::new_decimal(&currency, decimal)
    400     }
    401 }
    402 
    403 #[track_caller]
    404 pub fn amount(amount: impl AsRef<str>) -> Amount {
    405     amount.as_ref().parse().expect("Invalid amount constant")
    406 }
    407 
    408 #[derive(Debug, thiserror::Error)]
    409 pub enum AmountErrKind {
    410     #[error("invalid format")]
    411     Format,
    412     #[error("currency {0}")]
    413     Currency(#[from] CurrencyErrorKind),
    414     #[error(transparent)]
    415     Decimal(#[from] DecimalErrKind),
    416 }
    417 
    418 #[derive(Debug, thiserror::Error)]
    419 #[error("amount '{amount}' {kind}")]
    420 pub struct ParseAmountErr {
    421     amount: String,
    422     pub kind: AmountErrKind,
    423 }
    424 
    425 impl FromStr for Amount {
    426     type Err = ParseAmountErr;
    427 
    428     fn from_str(s: &str) -> Result<Self, Self::Err> {
    429         // TODO use try block when stable
    430         (|| {
    431             let (currency, amount) = s.trim().split_once(':').ok_or(AmountErrKind::Format)?;
    432             let currency = currency.parse().map_err(|e: ParseCurrencyError| e.kind)?;
    433             let decimal = amount.parse().map_err(|e: ParseDecimalErr| e.kind)?;
    434             Ok((currency, decimal).into())
    435         })()
    436         .map_err(|kind| ParseAmountErr {
    437             amount: s.to_owned(),
    438             kind,
    439         })
    440     }
    441 }
    442 
    443 impl Display for Amount {
    444     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    445         f.write_fmt(format_args!("{}:{}", self.currency, self.decimal()))
    446     }
    447 }
    448 
    449 impl Debug for Amount {
    450     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    451         Display::fmt(&self, f)
    452     }
    453 }
    454 
    455 impl sqlx::Type<sqlx::Postgres> for Amount {
    456     fn type_info() -> sqlx::postgres::PgTypeInfo {
    457         PgTalerAmount::type_info()
    458     }
    459 }
    460 
    461 impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Amount {
    462     fn encode_by_ref(
    463         &self,
    464         buf: &mut sqlx::postgres::PgArgumentBuffer,
    465     ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
    466         self.decimal().encode_by_ref(buf)
    467     }
    468 }
    469 
    470 #[test]
    471 fn constants() {
    472     assert_eq!(format!("{}", Amount::zero(&Currency::KUDOS)), "KUDOS:0");
    473     assert_eq!(
    474         format!("{}", Amount::max(&Currency::KUDOS)),
    475         "KUDOS:4503599627370496.99999999"
    476     );
    477 }
    478 
    479 #[test]
    480 fn test_amount_parse() {
    481     const TALER_AMOUNT_FRAC_BASE: u32 = 100000000;
    482     // https://git.taler.net/exchange.git/tree/src/util/test_amount.c
    483 
    484     const INVALID_AMOUNTS: [&str; 6] = [
    485         "EUR:4a",                                                                     // non-numeric,
    486         "EUR:4.4a",                                                                   // non-numeric
    487         "EUR:4.a4",                                                                   // non-numeric
    488         ":4.a4",                                                                      // no currency
    489         "EUR:4.123456789", // precision to high
    490         "EUR:1234567890123456789012345678901234567890123456789012345678901234567890", // value to big
    491     ];
    492 
    493     for str in INVALID_AMOUNTS {
    494         let amount = Amount::from_str(str);
    495         assert!(amount.is_err(), "invalid {str} got {amount:?}");
    496     }
    497 
    498     let eur: Currency = Currency::EUR;
    499     let local: Currency = Currency::CHF;
    500     let valid_amounts: Vec<(&str, &str, Amount)> = vec![
    501         ("EUR:4", "EUR:4", Amount::new(&eur, 4, 0)), // without fraction
    502         (
    503             "EUR:0.02",
    504             "EUR:0.02",
    505             Amount::new(&eur, 0, TALER_AMOUNT_FRAC_BASE / 100 * 2),
    506         ), // leading zero fraction
    507         (
    508             " EUR:4.12",
    509             "EUR:4.12",
    510             Amount::new(&eur, 4, TALER_AMOUNT_FRAC_BASE / 100 * 12),
    511         ), // leading space and fraction
    512         (
    513             " CHF:4444.1000",
    514             "CHF:4444.1",
    515             Amount::new(&local, 4444, TALER_AMOUNT_FRAC_BASE / 10),
    516         ), // local currency
    517     ];
    518     for (raw, expected, goal) in valid_amounts {
    519         let amount = Amount::from_str(raw);
    520         assert!(amount.is_ok(), "Valid {} got {:?}", raw, amount);
    521         assert_eq!(
    522             *amount.as_ref().unwrap(),
    523             goal,
    524             "Expected {:?} got {:?} for {}",
    525             goal,
    526             amount,
    527             raw
    528         );
    529         let amount = amount.unwrap();
    530         let str = amount.to_string();
    531         assert_eq!(str, expected);
    532         assert_eq!(amount, Amount::from_str(&str).unwrap(), "{str}");
    533     }
    534 
    535     for invalid in ["EUR:1.+5", "EUR:+1", "EUR:4.", "EUR:.5", "EUR:1.-5"] {
    536         assert!(
    537             Amount::from_str(invalid).is_err(),
    538             "Expected invalid amount for {invalid}"
    539         );
    540     }
    541 }
    542 
    543 #[test]
    544 fn test_amount_add() {
    545     let eur: Currency = Currency::EUR;
    546     assert_eq!(
    547         Amount::max(&eur).try_add(&Amount::zero(&eur)),
    548         Some(Amount::max(&eur))
    549     );
    550     assert_eq!(
    551         Amount::zero(&eur).try_add(&Amount::zero(&eur)),
    552         Some(Amount::zero(&eur))
    553     );
    554     assert_eq!(
    555         amount("EUR:6.41").try_add(&amount("EUR:4.69")),
    556         Some(amount("EUR:11.1"))
    557     );
    558     assert_eq!(
    559         amount(format!("EUR:{MAX_VALUE}")).try_add(&amount("EUR:0.99999999")),
    560         Some(Amount::max(&eur))
    561     );
    562 
    563     assert_eq!(
    564         amount(format!("EUR:{}", MAX_VALUE - 5)).try_add(&amount("EUR:6")),
    565         None
    566     );
    567     assert_eq!(
    568         Amount::new(&eur, u64::MAX, 0).try_add(&amount("EUR:1")),
    569         None
    570     );
    571     assert_eq!(
    572         amount(format!("EUR:{}.{}", MAX_VALUE - 5, FRAC_BASE - 1))
    573             .try_add(&amount("EUR:5.00000002")),
    574         None
    575     );
    576 }
    577 
    578 #[test]
    579 fn test_amount_normalize() {
    580     let eur: Currency = "EUR".parse().unwrap();
    581     assert_eq!(
    582         Amount::new(&eur, 4, 2 * FRAC_BASE).normalize(),
    583         Some(amount("EUR:6"))
    584     );
    585     assert_eq!(
    586         Amount::new(&eur, 4, 2 * FRAC_BASE + 1).normalize(),
    587         Some(amount("EUR:6.00000001"))
    588     );
    589     assert_eq!(
    590         Amount::new(&eur, MAX_VALUE, FRAC_BASE - 1).normalize(),
    591         Some(Amount::new(&eur, MAX_VALUE, FRAC_BASE - 1))
    592     );
    593     assert_eq!(Amount::new(&eur, u64::MAX, FRAC_BASE).normalize(), None);
    594     assert_eq!(Amount::new(&eur, MAX_VALUE, FRAC_BASE).normalize(), None);
    595 
    596     for amount in [Amount::max(&eur), Amount::zero(&eur)] {
    597         assert_eq!(amount.normalize(), Some(amount))
    598     }
    599 }