From b03c24db8cf732939cc6dc92cb9c5bd9825b479b Mon Sep 17 00:00:00 2001 From: yancy Date: Thu, 18 May 2023 17:46:26 +0200 Subject: [PATCH] Add a checked version of weight mul fee_rate --- bitcoin/src/blockdata/fee_rate.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/bitcoin/src/blockdata/fee_rate.rs b/bitcoin/src/blockdata/fee_rate.rs index 100ab9e4..1a7ccded 100644 --- a/bitcoin/src/blockdata/fee_rate.rs +++ b/bitcoin/src/blockdata/fee_rate.rs @@ -79,6 +79,14 @@ impl FeeRate { /// /// Computes `self / rhs` returning `None` if `rhs == 0`. pub fn checked_div(self, rhs: u64) -> Option { self.0.checked_div(rhs).map(Self) } + + /// Checked weight multiplication. + /// + /// Computes `self * rhs` where rhs is of type Weight. `None` is returned if an overflow + /// occured. + pub fn checked_mul_by_weight(self, rhs: Weight) -> Option { + self.0.checked_mul(rhs.to_wu()).map(Amount::from_sat) + } } /// Alternative will display the unit. @@ -173,6 +181,16 @@ mod tests { assert!(fee_rate.is_none()); } + #[test] + fn checked_weight_mul_test() { + let weight = Weight::from_wu(10); + let fee: Amount = FeeRate(10).checked_mul_by_weight(weight).expect("expected Amount"); + assert_eq!(Amount::from_sat(100), fee); + + let fee = FeeRate(10).checked_mul_by_weight(Weight::MAX); + assert!(fee.is_none()); + } + #[test] fn checked_div_test() { let fee_rate = FeeRate(10).checked_div(10).expect("expected feerate in sat/kwu");