Merge rust-bitcoin/rust-bitcoin#7128: units: use checked subtraction/addition assignment for NumOpResult
What changed, and why it matters
This commit fixes a bug in the rust-bitcoin library's 'units' crate where the += and -= operators on a special result type (NumOpResult) could silently wrap around on overflow in release builds, instead of reporting an error as documented. The patch replaces the wrapping behavior with checked arithmetic for several numeric types including fee rates, weights, block intervals, and raw integers. It is a defensive fix that prevents incorrect values from being treated as valid.
Upgrade to a version of rust-bitcoin containing this commit if your code uses NumOpResult with += or -= on the affected types. Review any code that previously relied on the wrapping behavior, as this is a breaking change that now returns Error on overflow. Run the new unit tests to confirm the fix.
Security signals we found
Integer overflow silently wrapping while result remains marked Valid
Violation of documented overflow-prevention contract on NumOpResult
Potential for incorrect fee-rate/weight/block-interval calculations downstream
Fix uses checked_add/checked_sub and propagates MathErrorKind::Overflow
Breaking API change: generic impl replaced with concrete type implementations
Evidence from the diff
NumOpResult
Changed components
units/src/result.rsunits/src/amount/ops.rsunits/src/internal_macros.rsNumOpResult<T>FeeRateWeightBlockHeightIntervalBlockMtpIntervalAmountSignedAmountu64i64Inspect captured patch +147 / −117
### units/src/amount/ops.rs
@@ -8,10 +8,7 @@ use core::ops;
use NumOpResult as R;
use super::{Amount, SignedAmount};
-use crate::internal_macros::{
- impl_add_assign_for_results, impl_div_assign, impl_mul_assign, impl_rem_assign,
- impl_sub_assign_for_results,
-};
+use crate::internal_macros::{impl_div_assign, impl_mul_assign, impl_rem_assign};
use crate::result::{MathErrorKind, MathOp, NumOpResult, OptionExt};
impl From<Amount> for NumOpResult<Amount> {
@@ -253,11 +250,6 @@ impl_rem_assign!(SignedAmount, NonZeroI64);
impl_rem_assign!(NumOpResult<Amount>, NonZeroU64);
impl_rem_assign!(NumOpResult<SignedAmount>, NonZeroI64);
-impl_add_assign_for_results!(Amount);
-impl_add_assign_for_results!(SignedAmount);
-impl_sub_assign_for_results!(Amount);
-impl_sub_assign_for_results!(SignedAmount);
-
impl ops::Neg for Amount {
type Output = SignedAmount;
### units/src/internal_macros.rs
@@ -98,74 +98,6 @@ macro_rules! impl_add_assign {
}
pub(crate) use impl_add_assign;
-/// Implement `ops::AddAssign` for `$ty` and `NumOpResult<$ty>` on `NumOpResult<$ty>`
-///
-/// This implements the same logic as the generic [`NumOpResult`] implementation in result.rs,
-/// but works for types that can't implement `AddAssign` on themselves (e.g. [`Amount`],
-/// [`SignedAmount`])
-///
-/// [`NumOpResult`]: crate::NumOpResult
-/// [`Amount`]: crate::Amount
-/// [`SignedAmount`]: crate::SignedAmount
-macro_rules! impl_add_assign_for_results {
- ($ty:ident) => {
- impl ops::AddAssign<$ty> for NumOpResult<$ty> {
- #[inline]
- fn add_assign(&mut self, rhs: $ty) {
- if let Self::Valid(ref lhs) = self {
- *self = lhs + rhs
- }
- }
- }
-
- impl ops::AddAssign<Self> for NumOpResult<$ty> {
- #[inline]
- fn add_assign(&mut self, rhs: Self) {
- match (&self, rhs) {
- (Self::Valid(_), Self::Valid(rhs)) => *self += rhs,
- (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
- (Self::Error(_), _) => (), // If the lhs is an error, preserve it
- }
- }
- }
- };
-}
-pub(crate) use impl_add_assign_for_results;
-
-/// Implement `ops::SubAssign` for `$ty` and `NumOpResult<$ty>` on `NumOpResult<$ty>`
-///
-/// This implements the same logic as the generic [`NumOpResult`] implementation in result.rs,
-/// but works for types that can't implement `SubAssign` on themselves (e.g. [`Amount`],
-/// [`SignedAmount`])
-///
-/// [`NumOpResult`]: crate::NumOpResult
-/// [`Amount`]: crate::Amount
-/// [`SignedAmount`]: crate::SignedAmount
-macro_rules! impl_sub_assign_for_results {
- ($ty:ident) => {
- impl ops::SubAssign<$ty> for NumOpResult<$ty> {
- #[inline]
- fn sub_assign(&mut self, rhs: $ty) {
- if let Self::Valid(ref lhs) = self {
- *self = lhs - rhs
- }
- }
- }
-
- impl ops::SubAssign<Self> for NumOpResult<$ty> {
- #[inline]
- fn sub_assign(&mut self, rhs: Self) {
- match (&self, rhs) {
- (Self::Valid(_), Self::Valid(rhs)) => *self -= rhs,
- (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
- (Self::Error(_), _) => (), // If the lhs is an error, preserve it
- }
- }
- }
- };
-}
-pub(crate) use impl_sub_assign_for_results;
-
/// Implement `ops::SubAssign` for `$ty` and `&$ty`.
macro_rules! impl_sub_assign {
($ty:ident) => {
### units/src/result.rs
@@ -9,7 +9,7 @@ use core::{fmt, ops};
use arbitrary::{Arbitrary, Unstructured};
use NumOpResult as R;
-use crate::{Amount, FeeRate, SignedAmount, Weight};
+use crate::{Amount, BlockHeightInterval, BlockMtpInterval, FeeRate, SignedAmount, Weight};
#[rustfmt::skip] // Keep public re-exports separate.
#[doc(no_inline)]
@@ -302,52 +302,72 @@ crate::internal_macros::impl_op_for_references! {
}
}
-// Implement AddAssign on NumOpResults for all wrapped types that already implement AddAssign on themselves
-impl<T: ops::AddAssign> ops::AddAssign<T> for NumOpResult<T> {
- #[inline]
- #[track_caller]
- fn add_assign(&mut self, rhs: T) {
- if let Self::Valid(ref mut lhs) = self {
- *lhs += rhs;
+// Generates checked addition and subtraction assignments for wrapped numeric types.
+macro_rules! impl_checked_assign {
+ ($ty:ty, $is_negative:expr) => {
+ impl ops::AddAssign<$ty> for NumOpResult<$ty> {
+ #[inline]
+ #[track_caller]
+ fn add_assign(&mut self, rhs: $ty) {
+ if let Self::Valid(lhs) = *self {
+ let rhs_is_negative = ($is_negative)(rhs);
+ *self = lhs.checked_add(rhs).valid_or_error(MathErrorKind::Overflow {
+ op: MathOp::Add,
+ is_negative: rhs_is_negative,
+ });
+ }
+ }
}
- }
-}
-impl<T: ops::AddAssign + Copy> ops::AddAssign<Self> for NumOpResult<T> {
- #[inline]
- #[track_caller]
- fn add_assign(&mut self, rhs: Self) {
- match (&self, rhs) {
- (Self::Valid(_), Self::Valid(rhs)) => *self += rhs,
- (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
- (Self::Error(_), _) => (), // If the lhs is an error, preserve it
+ impl ops::AddAssign<Self> for NumOpResult<$ty> {
+ #[inline]
+ #[track_caller]
+ fn add_assign(&mut self, rhs: Self) {
+ match (&self, rhs) {
+ (Self::Valid(_), Self::Valid(rhs)) => *self += rhs,
+ (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
+ (Self::Error(_), _) => (), // If the lhs is an error, preserve it
+ }
+ }
}
- }
-}
-// Implement SubAssign on NumOpResults for all wrapped types that already implement SubAssign on themselves
-impl<T: ops::SubAssign> ops::SubAssign<T> for NumOpResult<T> {
- #[inline]
- #[track_caller]
- fn sub_assign(&mut self, rhs: T) {
- if let Self::Valid(ref mut lhs) = self {
- *lhs -= rhs;
+ impl ops::SubAssign<$ty> for NumOpResult<$ty> {
+ #[inline]
+ #[track_caller]
+ fn sub_assign(&mut self, rhs: $ty) {
+ if let Self::Valid(lhs) = *self {
+ let rhs_is_negative = ($is_negative)(rhs);
+ *self = lhs.checked_sub(rhs).valid_or_error(MathErrorKind::Overflow {
+ op: MathOp::Sub,
+ is_negative: !rhs_is_negative,
+ });
+ }
+ }
}
- }
-}
-impl<T: ops::SubAssign + Copy> ops::SubAssign<Self> for NumOpResult<T> {
- #[inline]
- #[track_caller]
- fn sub_assign(&mut self, rhs: Self) {
- match (&self, rhs) {
- (Self::Valid(_), Self::Valid(rhs)) => *self -= rhs,
- (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
- (Self::Error(_), _) => (), // If the lhs is an error, preserve it
+ impl ops::SubAssign<Self> for NumOpResult<$ty> {
+ #[inline]
+ #[track_caller]
+ fn sub_assign(&mut self, rhs: Self) {
+ match (&self, rhs) {
+ (Self::Valid(_), Self::Valid(rhs)) => *self -= rhs,
+ (Self::Valid(_), Self::Error(err)) => *self = Self::Error(err),
+ (Self::Error(_), _) => (), // If the lhs is an error, preserve it
+ }
+ }
}
- }
+ };
}
+impl_checked_assign!(Amount, |_| false);
+impl_checked_assign!(SignedAmount, SignedAmount::is_negative);
+impl_checked_assign!(FeeRate, |_| false);
+impl_checked_assign!(Weight, |_| false);
+impl_checked_assign!(BlockHeightInterval, |_| false);
+impl_checked_assign!(BlockMtpInterval, |_| false);
+impl_checked_assign!(u64, |_| false);
+impl_checked_assign!(i64, i64::is_negative);
+
pub(crate) trait OptionExt<T> {
fn valid_or_error(self, kind: MathErrorKind) -> NumOpResult<T>;
}
@@ -367,7 +387,16 @@ macro_rules! impl_opt_ext {
)*
}
}
-impl_opt_ext!(Amount, SignedAmount, u64, i64, FeeRate, Weight);
+impl_opt_ext!(
+ Amount,
+ SignedAmount,
+ u64,
+ i64,
+ FeeRate,
+ Weight,
+ BlockHeightInterval,
+ BlockMtpInterval
+);
/// The math operation that caused the error.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
@@ -552,7 +581,7 @@ mod tests {
use std::error::Error;
use crate::result::{MathErrorKind, MathOp, NumOpError, NumOpResult};
- use crate::{Amount, FeeRate, Weight};
+ use crate::{Amount, BlockHeightInterval, BlockMtpInterval, FeeRate, Weight};
#[test]
fn mathop_predicates() {
@@ -773,4 +802,81 @@ mod tests {
assert!(combined.unwrap_err().operation().is_division());
}
+
+ #[test]
+ fn sub_assign_overflow() {
+ let one = FeeRate::from_sat_per_mvb(1);
+ let two = FeeRate::from_sat_per_mvb(2);
+ let overflow =
+ NumOpError::while_doing(MathErrorKind::Overflow { op: MathOp::Sub, is_negative: true });
+
+ let mut result = NumOpResult::Valid(one);
+ result -= two;
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(one);
+ result -= NumOpResult::Valid(two);
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(0_u64);
+ result -= 1_u64;
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(BlockHeightInterval::ZERO);
+ result -= BlockHeightInterval::from_u32(1);
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(BlockMtpInterval::ZERO);
+ result -= NumOpResult::Valid(BlockMtpInterval::from_u32(1));
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(i64::MAX);
+ result -= -1_i64;
+ assert_eq!(
+ result,
+ NumOpResult::Error(NumOpError::while_doing(MathErrorKind::Overflow {
+ op: MathOp::Sub,
+ is_negative: false,
+ }))
+ );
+ }
+
+ #[test]
+ fn add_assign_overflow() {
+ let one = FeeRate::from_sat_per_mvb(1);
+ let overflow = NumOpError::while_doing(MathErrorKind::Overflow {
+ op: MathOp::Add,
+ is_negative: false,
+ });
+
+ let mut result = NumOpResult::Valid(FeeRate::MAX);
+ result += one;
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(FeeRate::MAX);
+ result += NumOpResult::Valid(one);
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(Weight::MAX);
+ result += Weight::from_wu(1);
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(BlockHeightInterval::MAX);
+ result += NumOpResult::Valid(BlockHeightInterval::from_u32(1));
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(BlockMtpInterval::MAX);
+ result += BlockMtpInterval::from_u32(1);
+ assert_eq!(result, NumOpResult::Error(overflow));
+
+ let mut result = NumOpResult::Valid(i64::MIN);
+ result += -1_i64;
+ assert_eq!(
+ result,
+ NumOpResult::Error(NumOpError::while_doing(MathErrorKind::Overflow {
+ op: MathOp::Add,
+ is_negative: true,
+ }))
+ );
+ }
}Why this scored 62/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.