bitcoin-units 0.6.0

Basic Bitcoin numeric units such as amount
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
// SPDX-License-Identifier: CC0-1.0

//! Provides a monadic type returned by mathematical operations ([`core::ops`]).

use core::convert::Infallible;
use core::{fmt, ops};

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use NumOpResult as R;

use crate::{Amount, FeeRate, SignedAmount, Weight};

#[rustfmt::skip]                // Keep public re-exports separate.
#[doc(no_inline)]
pub use self::error::NumOpError;

/// Result of a mathematical operation on two numeric types.
///
/// In order to prevent overflow we provide a custom result type that is similar to the normal
/// [`core::result::Result`] but implements mathematical operations (e.g. [`core::ops::Add`]) so that
/// math operations can be chained ergonomically. This is very similar to how `NaN` works.
///
/// [`NumOpResult`] is a monadic type that contains [`Valid`] and [`Error`] (similar to [`Ok`] and
/// [`Err`]). It supports a subset of functions similar to [`Result`] (e.g. [`unwrap`]).
///
/// # Examples
///
/// The [`NumOpResult`] type provides protection against overflow and div-by-zero.
///
/// ### Overflow protection
///
/// ```
/// # use bitcoin_units::{amount, Amount};
/// // Example UTXO value.
/// let a1 = Amount::from_sat(1_000_000)?;
/// // And another value from some other UTXO.
/// let a2 = Amount::from_sat(765_432)?;
/// // Just an example (typically one would calculate fee using weight and fee rate).
/// let fee = Amount::from_sat(100)?;
/// // The amount we want to send.
/// let spend = Amount::from_sat(1_200_000)?;
///
/// // We can error if the change calculation overflows.
/// //
/// // For example if the `spend` value comes from the user and the `change` value is later
/// // used then overflow here could be an attack vector.
/// let _change = (a1 + a2 - spend - fee).into_result().expect("handle this error");
///
/// // Or if we control all the values and know they are sane we can just `unwrap`.
/// let _change = (a1 + a2 - spend - fee).unwrap();
/// // `NumOpResult` also implements `expect`.
/// let _change = (a1 + a2 - spend - fee).expect("we know values don't overflow");
/// # Ok::<_, amount::OutOfRangeError>(())
/// ```
///
/// ### Failure in chained operations
///
/// In some instances one may wish to differentiate one math op failure from another.
///
/// ```
/// # use bitcoin_units::{Amount, FeeRate, NumOpResult, result::NumOpError};
/// // Two amounts that will be added to calculate the max fee.
/// let a = Amount::from_sat(123).expect("valid amount");
/// let b = Amount::from_sat(467).expect("valid amount");
/// // Fee rate for transaction.
/// let fee_rate = FeeRate::from_sat_per_vb_u32(1);
///
/// // Somewhat contrived example to show addition operator chained with division.
/// let max_fee = a + b;
/// let _fee = match max_fee / fee_rate {
///     NumOpResult::Valid(fee) => fee,
///     NumOpResult::Error(e) if e.operation().is_division() => {
///         // Do something when division fails (div by zero or perhaps MIN / -1).
///         return Err(e);
///     },
///     NumOpResult::Error(e) => {
///         // And something else if the addition overflowed.
///         //
///         // This branch could be hit since `max_fee` came from some previous calculation. And if
///         // an input to that calculation was from the user then overflow could be an attack vector.
///         return Err(e);
///     }
/// };
/// # Ok::<_, NumOpError>(())
/// ```
///
/// If both operands of a binary op are already [`Error`], only the left-hand error is returned.
///
/// [`Valid`]: NumOpResult::Valid
/// [`Error`]: NumOpResult::Error
/// [`unwrap`]: NumOpResult::unwrap
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use]
pub enum NumOpResult<T> {
    /// Result of a successful mathematical operation.
    Valid(T),
    /// Result of an unsuccessful mathematical operation.
    Error(NumOpError),
}

impl<T> NumOpResult<T> {
    /// Maps a [`NumOpResult<T>`] to [`NumOpResult<U>`] by applying a function to a
    /// contained [`NumOpResult::Valid`] value, leaving a [`NumOpResult::Error`] value untouched.
    #[inline]
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> NumOpResult<U> {
        match self {
            Self::Valid(t) => NumOpResult::Valid(op(t)),
            Self::Error(e) => NumOpResult::Error(e),
        }
    }

    /// Returns the contained valid numeric type, consuming `self`.
    ///
    /// # Panics
    ///
    /// Panics with `msg` if the numeric result is an [`Error`].
    ///
    /// [`Error`]: NumOpResult::Error
    #[inline]
    #[track_caller]
    pub fn expect(self, msg: &str) -> T {
        match self {
            Self::Valid(x) => x,
            Self::Error(_) => panic!("{}", msg),
        }
    }

    /// Returns the contained valid numeric type, consuming `self`.
    ///
    /// # Panics
    ///
    /// Panics if the numeric result is an [`Error`].
    ///
    /// [`Error`]: NumOpResult::Error
    #[inline]
    #[track_caller]
    pub fn unwrap(self) -> T {
        match self {
            Self::Valid(x) => x,
            Self::Error(e) => panic!("tried to unwrap an invalid numeric result: {:?}", e),
        }
    }

    /// Returns the contained [`Valid`] value or a provided default.
    ///
    /// Arguments passed to [`unwrap_or`] are eagerly evaluated; if you are passing the result of a
    /// function call, it is recommended to use [`unwrap_or_else`], which is lazily evaluated.
    ///
    /// [`Valid`]: NumOpResult::Valid
    /// [`unwrap_or`]: NumOpResult::unwrap_or
    /// [`unwrap_or_else`]: NumOpResult::unwrap_or_else
    #[inline]
    pub fn unwrap_or(self, default: T) -> T {
        match self {
            Self::Valid(x) => x,
            Self::Error(_) => default,
        }
    }

    /// Returns the contained [`Valid`] value or computes it from a closure.
    ///
    /// [`Valid`]: NumOpResult::Valid
    #[inline]
    pub fn unwrap_or_else<F>(self, f: F) -> T
    where
        F: FnOnce() -> T,
    {
        match self {
            Self::Valid(x) => x,
            Self::Error(_) => f(),
        }
    }

    /// Converts this [`NumOpResult`] to an [`Option<T>`].
    #[inline]
    pub fn ok(self) -> Option<T> {
        match self {
            Self::Valid(x) => Some(x),
            Self::Error(_) => None,
        }
    }

    /// Converts this [`NumOpResult`] to a [`Result<T, NumOpError>`].
    #[inline]
    #[allow(clippy::missing_errors_doc)]
    pub fn into_result(self) -> Result<T, NumOpError> {
        match self {
            Self::Valid(x) => Ok(x),
            Self::Error(e) => Err(e),
        }
    }

    /// Converts a [`Result<T, NumOpError>`] to a [`NumOpResult`].
    #[inline]
    pub fn from_result(result: Result<T, NumOpError>) -> Self {
        match result {
            Ok(x) => Self::Valid(x),
            Err(e) => Self::Error(e),
        }
    }

    /// Calls `op` if the numeric result is [`Valid`], otherwise returns the [`Error`] value of
    /// `self`.
    ///
    /// [`Valid`]: NumOpResult::Valid
    /// [`Error`]: NumOpResult::Error
    #[inline]
    pub fn and_then<F>(self, op: F) -> Self
    where
        F: FnOnce(T) -> Self,
    {
        match self {
            Self::Valid(x) => op(x),
            Self::Error(e) => Self::Error(e),
        }
    }

    /// Returns `true` if the numeric result is valid.
    #[inline]
    pub fn is_valid(&self) -> bool {
        match self {
            Self::Valid(_) => true,
            Self::Error(_) => false,
        }
    }

    /// Returns `true` if the numeric result is invalid.
    #[inline]
    pub fn is_error(&self) -> bool { !self.is_valid() }
}

impl<T: fmt::Debug> NumOpResult<T> {
    /// Returns the contained error, consuming `self`.
    ///
    /// # Panics
    ///
    /// Panics if the numeric result is valid.
    #[inline]
    #[track_caller]
    pub fn unwrap_err(self) -> NumOpError {
        match self {
            Self::Error(e) => e,
            Self::Valid(a) => panic!("tried to unwrap a valid numeric result: {:?}", a),
        }
    }
}

// Implement Add/Sub on NumOpResults for all wrapped types that already implement Add/Sub on themselves
crate::internal_macros::impl_op_for_references! {
    impl<T> ops::Add<NumOpResult<T>> for NumOpResult<T>
    where
        (T: Copy + ops::Add<Output = NumOpResult<T>>)
    {
        type Output = NumOpResult<T>;

        fn add(self, rhs: Self) -> Self::Output {
            match (self, rhs) {
                (R::Valid(lhs), R::Valid(rhs)) => lhs + rhs,
                (R::Error(e), _) => R::Error(e),
                (_, R::Error(e)) => R::Error(e),
            }
        }
    }

    impl<T> ops::Add<T> for NumOpResult<T>
    where
        (T: Copy + ops::Add<NumOpResult<T>, Output = NumOpResult<T>>)
    {
        type Output = NumOpResult<T>;

        fn add(self, rhs: T) -> Self::Output { rhs + self }
    }

    impl<T> ops::Sub<NumOpResult<T>> for NumOpResult<T>
    where
        (T: Copy + ops::Sub<Output = NumOpResult<T>>)
    {
        type Output = NumOpResult<T>;

        fn sub(self, rhs: Self) -> Self::Output {
            match (self, rhs) {
                (R::Valid(lhs), R::Valid(rhs)) => lhs - rhs,
                (R::Error(e), _) => R::Error(e),
                (_, R::Error(e)) => R::Error(e),
            }
        }
    }

    impl<T> ops::Sub<T> for NumOpResult<T>
    where
        (T: Copy + ops::Sub<Output = NumOpResult<T>>)
    {
        type Output = NumOpResult<T>;

        fn sub(self, rhs: T) -> Self::Output {
            match self {
                R::Valid(amount) => amount - rhs,
                R::Error(_) => self,
            }
        }
    }
}

// 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;
        }
    }
}

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
        }
    }
}

// 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<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
        }
    }
}

pub(crate) trait OptionExt<T> {
    fn valid_or_error(self, kind: MathErrorKind) -> NumOpResult<T>;
}

macro_rules! impl_opt_ext {
    ($($ty:ident),* $(,)?) => {
        $(
            impl OptionExt<$ty> for Option<$ty> {
                #[inline]
                fn valid_or_error(self, kind: MathErrorKind) -> NumOpResult<$ty> {
                    match self {
                        Some(amount) => R::Valid(amount),
                        None => R::Error(NumOpError::while_doing(kind)),
                    }
                }
            }
        )*
    }
}
impl_opt_ext!(Amount, SignedAmount, u64, i64, FeeRate, Weight);

/// The math operation that caused the error.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MathOp {
    /// Addition failed ([`core::ops::Add`] resulted in an invalid value).
    Add,
    /// Subtraction failed ([`core::ops::Sub`] resulted in an invalid value).
    Sub,
    /// Multiplication failed ([`core::ops::Mul`] resulted in an invalid value).
    Mul,
    /// Division failed ([`core::ops::Div`] attempted div-by-zero).
    Div,
    /// Calculating the remainder failed ([`core::ops::Rem`] attempted div-by-zero).
    Rem,
    /// Negation failed ([`core::ops::Neg`] resulted in an invalid value).
    Neg,
    /// Stops users from casting this enum to an integer.
    // May get removed if one day Rust supports disabling casts natively.
    #[doc(hidden)]
    _DoNotUse(Infallible),
}

impl MathOp {
    /// Returns `true` if this operation error'ed due to addition.
    #[inline]
    pub fn is_addition(self) -> bool { self == Self::Add }

    /// Returns `true` if this operation error'ed due to subtraction.
    #[inline]
    pub fn is_subtraction(self) -> bool { self == Self::Sub }

    /// Returns `true` if this operation error'ed due to multiplication.
    #[inline]
    pub fn is_multiplication(self) -> bool { self == Self::Mul }

    /// Returns `true` if this operation error'ed due to division.
    #[inline]
    pub fn is_division(self) -> bool { self == Self::Div }

    /// Returns `true` if this operation error'ed due to remainder.
    #[inline]
    pub fn is_remainder(self) -> bool { self == Self::Rem }

    /// Returns `true` if this operation error'ed due to negation.
    #[inline]
    pub fn is_negation(self) -> bool { self == Self::Neg }
}

impl fmt::Display for MathOp {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Add => write!(f, "add"),
            Self::Sub => write!(f, "sub"),
            Self::Mul => write!(f, "mul"),
            Self::Div => write!(f, "div"),
            Self::Rem => write!(f, "rem"),
            Self::Neg => write!(f, "neg"),
            Self::_DoNotUse(infallible) => match infallible {},
        }
    }
}

/// The kind of error that happened during a mathematical operation failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MathErrorKind {
    // The result overflowed.
    Overflow {
        op: MathOp,
        is_negative: bool,
    },
    /// A division by zero was performed.
    DivByZero,
    /// A remainder by zero was performed.
    RemByZero,
}

/// Error types for mathematical operations.
pub mod error {
    use core::convert::Infallible;
    use core::fmt;

    use super::{MathErrorKind, MathOp};

    /// Error returned when a mathematical operation fails.
    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct NumOpError(pub(crate) MathErrorKind);

    impl NumOpError {
        /// Constructs a [`NumOpError`] caused by `kind`.
        #[inline]
        pub(crate) const fn while_doing(kind: MathErrorKind) -> Self { Self(kind) }

        /// Returns the [`MathOp`] that caused this error.
        #[inline]
        pub fn operation(self) -> MathOp {
            match self.0 {
                MathErrorKind::DivByZero => MathOp::Div,
                MathErrorKind::RemByZero => MathOp::Rem,
                MathErrorKind::Overflow { op, is_negative: _ } => op,
            }
        }
    }

    impl From<Infallible> for NumOpError {
        #[inline]
        fn from(never: Infallible) -> Self { match never {} }
    }

    impl fmt::Display for NumOpError {
        #[inline]
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self.0 {
                MathErrorKind::Overflow { op, is_negative: false } =>
                    write!(f, "failed to {}: the result would be too large", op),
                MathErrorKind::Overflow { op, is_negative: true } =>
                    write!(f, "failed to {}: the result would be too small", op),
                MathErrorKind::DivByZero => write!(f, "division by zero"),
                MathErrorKind::RemByZero =>
                    write!(f, "attempt to compute the remainder of division by zero"),
            }
        }
    }

    #[cfg(feature = "std")]
    impl std::error::Error for NumOpError {
        #[inline]
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            let Self(_) = self;
            None
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<'a, T: Arbitrary<'a>> Arbitrary<'a> for NumOpResult<T> {
    #[inline]
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        match bool::arbitrary(u)? {
            true => Ok(Self::Valid(T::arbitrary(u)?)),
            false => Ok(Self::Error(NumOpError(MathErrorKind::arbitrary(u)?))),
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for MathOp {
    #[inline]
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let choice = u.int_in_range(0..=5)?;
        match choice {
            0 => Ok(Self::Add),
            1 => Ok(Self::Sub),
            2 => Ok(Self::Mul),
            3 => Ok(Self::Div),
            4 => Ok(Self::Rem),
            _ => Ok(Self::Neg),
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for MathErrorKind {
    #[inline]
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let choice = u.int_in_range(0..=2)?;
        match choice {
            0 => Ok(Self::Overflow { op: MathOp::arbitrary(u)?, is_negative: bool::arbitrary(u)? }),
            1 => Ok(Self::RemByZero),
            _ => Ok(Self::DivByZero),
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "alloc")]
    use alloc::string::ToString;
    #[cfg(feature = "std")]
    use std::error::Error;

    use crate::result::{MathErrorKind, MathOp, NumOpError, NumOpResult};
    use crate::{Amount, FeeRate, Weight};

    #[test]
    fn mathop_predicates() {
        assert!(MathOp::Add.is_addition());
        assert!(!MathOp::Sub.is_addition());

        assert!(MathOp::Sub.is_subtraction());
        assert!(!MathOp::Add.is_subtraction());

        assert!(MathOp::Mul.is_multiplication());
        assert!(!MathOp::Div.is_multiplication());

        assert!(MathOp::Neg.is_negation());
        assert!(!MathOp::Add.is_negation());

        assert!(MathOp::Div.is_division());
        assert!(!MathOp::Rem.is_division());

        assert!(MathOp::Rem.is_remainder());
        assert!(!MathOp::Div.is_remainder());
    }

    #[test]
    fn mathop_map() {
        // op is evaluated for valid results
        let res = NumOpResult::Valid(Amount::from_sat_u32(100));
        let new_value = res.map(|val| (val / FeeRate::from_sat_per_kwu_u32(10)).unwrap());
        assert_eq!(new_value, NumOpResult::Valid(Weight::from_wu(10_000)));

        // op is not evaluated for error results
        let res = NumOpResult::<Weight>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }));
        let res_err = res.map(|_| {
            panic!("map should not evaluate for wrapped error values");
        });
        assert_eq!(res_err, res);
    }

    #[test]
    fn mathop_expect() {
        let amounts = [
            Amount::from_sat_u32(0),
            Amount::from_sat_u32(10_000_000),
            Amount::from_sat_u32(u32::MAX),
        ];
        for amount in amounts {
            assert_eq!(
                NumOpResult::Valid(amount).expect("unreachable"),
                NumOpResult::Valid(amount).unwrap(),
            );
            assert_eq!(NumOpResult::Valid(amount).expect("unreachable"), amount);
        }
    }

    #[test]
    #[should_panic(expected = "test error message")]
    fn mathop_expect_panics_on_error() {
        NumOpResult::<Amount>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }))
        .expect("test error message");
    }

    #[test]
    fn mathop_unwrap() {
        let amounts = [
            Amount::from_sat_u32(0),
            Amount::from_sat_u32(10_000_000),
            Amount::from_sat_u32(u32::MAX),
        ];
        for amount in amounts {
            assert_eq!(NumOpResult::Valid(amount).unwrap(), amount);
        }
        let weights = [Weight::from_wu(0), Weight::from_wu(16_384_000), Weight::from_wu(u64::MAX)];
        for weight in weights {
            assert_eq!(NumOpResult::Valid(weight).unwrap(), weight);
        }
    }

    #[test]
    #[should_panic(expected = "")]
    fn mathop_unwrap_panics_on_err() {
        NumOpResult::<Amount>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }))
        .unwrap();
    }

    #[test]
    fn mathop_unwrap_err() {
        let errs = [
            NumOpError::while_doing(MathErrorKind::Overflow {
                op: MathOp::Add,
                is_negative: false,
            }),
            NumOpError::while_doing(MathErrorKind::Overflow { op: MathOp::Sub, is_negative: true }),
            NumOpError::while_doing(MathErrorKind::Overflow {
                op: MathOp::Mul,
                is_negative: false,
            }),
            NumOpError::while_doing(MathErrorKind::DivByZero),
            NumOpError::while_doing(MathErrorKind::Overflow {
                op: MathOp::Neg,
                is_negative: false,
            }),
            NumOpError::while_doing(MathErrorKind::RemByZero),
        ];
        for err in errs {
            assert_eq!(NumOpResult::<Amount>::Error(err).unwrap_err(), err);
        }
    }

    #[test]
    #[should_panic(expected = "")]
    fn mathop_unwrap_err_panics_on_valid() {
        let value = Amount::from_sat_u32(150);
        NumOpResult::<Amount>::Valid(value).unwrap_err();
    }

    #[test]
    fn mathop_unwrap_or() {
        let base_amount = Amount::from_sat_u32(100);

        // default is returned for error results
        let res = NumOpResult::<Amount>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }));
        let res_default = res.unwrap_or(base_amount);
        assert_eq!(res_default, base_amount);

        // wrapped value is returned for valid results
        let res = NumOpResult::Valid(base_amount);
        let new_amount = res.unwrap_or(Amount::from_sat_u32(50));
        assert_eq!(new_amount, base_amount);
    }

    #[test]
    fn mathop_unwrap_or_else() {
        let base_amount = Amount::from_sat_u32(100);

        // op is evaluated for error results
        let res = NumOpResult::<Amount>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }));
        let res_default = res.unwrap_or_else(|| base_amount);
        assert_eq!(res_default, base_amount);

        // op is not evaluated for valid results
        let res = NumOpResult::<Amount>::Valid(base_amount);
        let new_amount = res.unwrap_or_else(|| {
            panic!("unwrap_or_else should not evaluate for wrapped valid values");
        });
        assert_eq!(new_amount, base_amount);
    }

    #[test]
    fn mathop_ok() {
        let amt = Amount::from_sat_u32(150);
        assert_eq!(NumOpResult::Valid(amt).ok(), Some(amt));

        let err = NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        });
        assert_eq!(NumOpResult::<Amount>::Error(err).ok(), None);
    }

    #[test]
    fn mathop_and_then() {
        // op is evaluated for valid results
        let res = NumOpResult::Valid(Amount::from_sat_u32(100));
        let new_value = res.and_then(|val| val + Amount::from_sat_u32(50));
        assert_eq!(new_value, NumOpResult::Valid(Amount::from_sat_u32(150)));

        // op is not evaluated for error results
        let res = NumOpResult::<Amount>::Error(NumOpError::while_doing(MathErrorKind::Overflow {
            op: MathOp::Add,
            is_negative: false,
        }));
        let res_err = res.and_then(|_| {
            panic!("and_then should not evaluate for wrapped error values");
        });
        assert_eq!(res_err, res);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn error_display_is_non_empty() {
        // NumOpError - math operation error
        let e = (Amount::MAX + Amount::MAX).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());
    }

    #[test]
    fn add_preserves_division_by_zero_error() {
        let division_by_zero = Amount::from_sat_u32(1) / 0_u64;
        let valid = NumOpResult::Valid(Amount::ZERO);

        let combined = division_by_zero + valid;

        assert!(combined.unwrap_err().operation().is_division());
    }

    #[test]
    fn sub_preserves_division_by_zero_error() {
        let division_by_zero = Amount::from_sat_u32(1) / 0_u64;
        let valid = NumOpResult::Valid(Amount::ZERO);

        let combined = valid - division_by_zero;

        assert!(combined.unwrap_err().operation().is_division());
    }
}