bitcoin-units 0.4.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
// SPDX-License-Identifier: CC0-1.0

//! Error types for bitcoin amounts.

use core::convert::Infallible;
use core::fmt;

use internals::error::InputString;
use internals::write_err;

use super::INPUT_STRING_LEN_LIMIT;
use crate::parse_int::{PrefixedHexError, UnprefixedHexError};

/// Error returned when parsing an amount with denomination fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError(pub(crate) ParseErrorInner);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ParseErrorInner {
    /// Invalid amount.
    Amount(ParseAmountError),
    /// Invalid denomination.
    Denomination(ParseDenominationError),
    /// The denomination was not identified.
    MissingDenomination(MissingDenominationError),
}

impl From<Infallible> for ParseError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl From<Infallible> for ParseErrorInner {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            ParseErrorInner::Amount(ref e) => write_err!(f, "invalid amount"; e),
            ParseErrorInner::Denomination(ref e) => write_err!(f, "invalid denomination"; e),
            // We consider this to not be a source because it currently doesn't contain useful info.
            ParseErrorInner::MissingDenomination(ref e) => write_err!(f, "missing denomination"; e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self.0 {
            ParseErrorInner::Amount(ref e) => Some(e),
            ParseErrorInner::Denomination(ref e) => Some(e),
            // We consider this to not be a source because it currently doesn't contain useful info.
            ParseErrorInner::MissingDenomination(ref e) => Some(e),
        }
    }
}

/// Error returned when parsing an amount fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseAmountError(pub(crate) ParseAmountErrorInner);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ParseAmountErrorInner {
    /// The amount is too big or too small.
    OutOfRange(OutOfRangeError),
    /// Amount has higher precision than supported by the type.
    TooPrecise(TooPreciseError),
    /// A digit was expected but not found.
    MissingDigits(MissingDigitsError),
    /// Input string was too large.
    InputTooLarge(InputTooLargeError),
    /// Invalid character in input.
    InvalidCharacter(InvalidCharacterError),
    /// A valid character is in an invalid position.
    BadPosition(BadPositionError),
    /// An error parsing a prefixed hex amount.
    PrefixedHex(PrefixedHexError),
    /// An error parsing an unprefixed hex amount.
    UnprefixedHex(UnprefixedHexError),
}

impl From<Infallible> for ParseAmountError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl From<Infallible> for ParseAmountErrorInner {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for ParseAmountError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ParseAmountErrorInner as E;

        match self.0 {
            E::OutOfRange(ref error) => write_err!(f, "amount out of range"; error),
            E::TooPrecise(ref error) => write_err!(f, "amount has a too high precision"; error),
            E::MissingDigits(ref error) => write_err!(f, "the input has too few digits"; error),
            E::InputTooLarge(ref error) => write_err!(f, "the input is too large"; error),
            E::InvalidCharacter(ref error) => {
                write_err!(f, "invalid character in the input"; error)
            }
            E::BadPosition(ref error) => write_err!(f, "valid character in bad position"; error),
            E::PrefixedHex(ref error) => write_err!(f, "prefixed hex is invalid"; error),
            E::UnprefixedHex(ref error) => write_err!(f, "unprefixed hex is invalid"; error),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseAmountError {
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use ParseAmountErrorInner as E;

        match self.0 {
            E::TooPrecise(ref error) => Some(error),
            E::InputTooLarge(ref error) => Some(error),
            E::OutOfRange(ref error) => Some(error),
            E::MissingDigits(ref error) => Some(error),
            E::InvalidCharacter(ref error) => Some(error),
            E::BadPosition(ref error) => Some(error),
            E::PrefixedHex(ref error) => Some(error),
            E::UnprefixedHex(ref error) => Some(error),
        }
    }
}

/// Error returned when a parsed amount is too big or too small.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct OutOfRangeError {
    pub(super) is_signed: bool,
    pub(super) is_greater_than_max: bool,
}

impl OutOfRangeError {
    /// Returns the minimum and maximum allowed values for the type that was parsed.
    ///
    /// This can be used to give a hint to the user which values are allowed.
    #[inline]
    pub fn valid_range(self) -> (i64, u64) {
        match self.is_signed {
            true => (i64::MIN, i64::MAX as u64),
            false => (0, u64::MAX),
        }
    }

    /// Returns true if the input value was larger than the maximum allowed value.
    #[inline]
    pub fn is_above_max(self) -> bool { self.is_greater_than_max }

    /// Returns true if the input value was smaller than the minimum allowed value.
    #[inline]
    pub fn is_below_min(self) -> bool { !self.is_greater_than_max }

    #[cfg(test)]
    #[inline]
    pub(crate) fn too_big(is_signed: bool) -> Self { Self { is_signed, is_greater_than_max: true } }

    #[cfg(test)]
    #[inline]
    pub(crate) fn too_small() -> Self {
        Self {
            // implied - negative() is used for the other
            is_signed: true,
            is_greater_than_max: false,
        }
    }

    #[inline]
    pub(crate) fn negative() -> Self {
        Self {
            // implied - too_small() is used for the other
            is_signed: false,
            is_greater_than_max: false,
        }
    }
}

impl From<Infallible> for OutOfRangeError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for OutOfRangeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.is_greater_than_max {
            write!(f, "the amount is greater than {}", self.valid_range().1)
        } else {
            write!(f, "the amount is less than {}", self.valid_range().0)
        }
    }
}

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

/// Error returned when the input string has higher precision than satoshis.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct TooPreciseError {
    pub(super) position: usize,
}

impl From<Infallible> for TooPreciseError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for TooPreciseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.position {
            0 => f.write_str("the amount is less than 1 satoshi but it's not zero"),
            pos => write!(
                f,
                "the digits starting from position {} represent a sub-satoshi amount",
                pos
            ),
        }
    }
}

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

/// Error returned when the input string is too large.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InputTooLargeError {
    pub(super) len: usize,
}

impl From<Infallible> for InputTooLargeError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for InputTooLargeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.len - INPUT_STRING_LEN_LIMIT {
            1 => write!(
                f,
                "the input is one character longer than the maximum allowed length ({})",
                INPUT_STRING_LEN_LIMIT
            ),
            n => write!(
                f,
                "the input is {} characters longer than the maximum allowed length ({})",
                n, INPUT_STRING_LEN_LIMIT
            ),
        }
    }
}

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

/// Error returned when digits were expected in the input but there were none.
///
/// In particular, this is currently returned when the string is empty or only contains the minus sign.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MissingDigitsError {
    pub(super) kind: MissingDigitsKind,
}

impl From<Infallible> for MissingDigitsError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for MissingDigitsError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            MissingDigitsKind::Empty => f.write_str("the input is empty"),
            MissingDigitsKind::OnlyMinusSign =>
                f.write_str("there are no digits following the minus (-) sign"),
        }
    }
}

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

#[derive(Debug, Clone, Eq, PartialEq)]
pub(super) enum MissingDigitsKind {
    Empty,
    OnlyMinusSign,
}

/// Error returned when the input contains an invalid character.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidCharacterError {
    pub(super) invalid_char: char,
    pub(super) position: usize,
}

impl From<Infallible> for InvalidCharacterError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for InvalidCharacterError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.invalid_char {
            '.' => f.write_str("there is more than one decimal separator (dot) in the input"),
            '-' => f.write_str("there is more than one minus sign (-) in the input"),
            c => write!(
                f,
                "the character '{}' at position {} is not a valid digit",
                c, self.position
            ),
        }
    }
}

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

/// Error returned when a valid character (e.g. '_') is in an invalid/bad position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BadPositionError {
    pub(super) char: char,
    pub(super) position: usize,
}

impl From<Infallible> for BadPositionError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for BadPositionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.char {
            '_' => match self.position {
                0 => f.write_str("the input amount is prefixed with an underscore (_)"),
                // Position 1 can only occur when the amount begins with a minus (-), since an underscore
                // at position 0 will cause an error with position 0, and this error marks the position of
                // the second underscore.
                1 => f.write_str("the input amount is prefixed with an underscore (_)"),
                _ => f.write_str("there are consecutive underscores (_) in the input"),
            },
            c => write!(f, "The character '{}' is at a bad position: {}", c, self.position),
        }
    }
}

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

/// An error during amount parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseDenominationError {
    /// The denomination was unknown.
    Unknown(UnknownDenominationError),
    /// The denomination has multiple possible interpretations.
    PossiblyConfusing(PossiblyConfusingDenominationError),
}

impl From<Infallible> for ParseDenominationError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for ParseDenominationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Unknown(ref e) => write_err!(f, "denomination parse error"; e),
            Self::PossiblyConfusing(ref e) => write_err!(f, "denomination parse error"; e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseDenominationError {
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Unknown(ref e) => Some(e),
            Self::PossiblyConfusing(ref e) => Some(e),
        }
    }
}

/// Error returned when the denomination is empty.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MissingDenominationError;

impl From<Infallible> for MissingDenominationError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for MissingDenominationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "the input does not contain a denomination")
    }
}

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

/// Error returned when parsing an unknown denomination.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnknownDenominationError(pub(super) InputString);

impl From<Infallible> for UnknownDenominationError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for UnknownDenominationError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.unknown_variant("bitcoin denomination", f)
    }
}

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

/// Error returned when parsing a possibly confusing denomination.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PossiblyConfusingDenominationError(pub(super) InputString);

impl From<Infallible> for PossiblyConfusingDenominationError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for PossiblyConfusingDenominationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: possibly confusing denomination - we intentionally do not support 'M' and 'P' so as to not confuse mega/milli and peta/pico", self.0.display_cannot_parse("bitcoin denomination"))
    }
}

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

/// An error consensus decoding an `Amount`.
#[cfg(feature = "encoding")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AmountDecoderError(pub(super) AmountDecoderErrorInner);

#[cfg(feature = "encoding")]
impl AmountDecoderError {
    /// Constructs an EOF error.
    #[inline]
    pub(super) fn eof(e: encoding::UnexpectedEofError) -> Self {
        Self(AmountDecoderErrorInner::UnexpectedEof(e))
    }

    /// Constructs an out of range (`Amount::from_sat`) error.
    #[inline]
    pub(super) fn out_of_range(e: OutOfRangeError) -> Self {
        Self(AmountDecoderErrorInner::OutOfRange(e))
    }
}

#[cfg(feature = "encoding")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum AmountDecoderErrorInner {
    /// Not enough bytes given to decoder.
    UnexpectedEof(encoding::UnexpectedEofError),
    /// Decoded amount is too big.
    OutOfRange(OutOfRangeError),
}

#[cfg(feature = "encoding")]
impl From<Infallible> for AmountDecoderError {
    fn from(never: Infallible) -> Self { match never {} }
}

#[cfg(feature = "encoding")]
impl fmt::Display for AmountDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use AmountDecoderErrorInner as E;

        match self.0 {
            E::UnexpectedEof(ref e) => write_err!(f, "decode error"; e),
            E::OutOfRange(ref e) => write_err!(f, "decode error"; e),
        }
    }
}

#[cfg(feature = "encoding")]
#[cfg(feature = "std")]
impl std::error::Error for AmountDecoderError {
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use AmountDecoderErrorInner as E;

        match self.0 {
            E::UnexpectedEof(ref e) => Some(e),
            E::OutOfRange(ref e) => Some(e),
        }
    }
}

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

    #[cfg(feature = "encoding")]
    use encoding::{Decode as _, Decoder as _};

    #[cfg(feature = "alloc")]
    use super::{ParseAmountError, ParseAmountErrorInner, ParseErrorInner};
    #[cfg(feature = "alloc")]
    use crate::amount::{Amount, Denomination, ParseDenominationError, ParseError};

    #[test]
    #[cfg(feature = "alloc")]
    #[allow(clippy::too_many_lines)] // Test could be refactored ...
    fn error_display_is_non_empty() {
        // A helper macro to break out a ParseAmountErrorInner type and assert display down the chain.
        macro_rules! assert_amount_err {
            ($e:expr, $enum_arm:ident, $err_msg:expr) => {
                assert!(!$e.to_string().is_empty());
                let ParseError(ParseErrorInner::Amount(err)) = $e else { panic!($err_msg) };
                assert!(!err.to_string().is_empty());
                #[cfg(feature = "std")]
                assert!(err.source().is_some());

                let ParseAmountError(ParseAmountErrorInner::$enum_arm(err)) = err else {
                    panic!($err_msg)
                };
                assert!(!err.to_string().is_empty());
                // The inner-most types have no source
                #[cfg(feature = "std")]
                assert!(err.source().is_none());
            };
        }

        // InputTooLargeError
        // one char too long
        let long_input = alloc::format!("{} BTC", "1".repeat(51));
        let e = Amount::from_str(&long_input).unwrap_err();
        assert_amount_err!(e, InputTooLarge, "error should be InputTooLargeError");
        // n chars too long
        let long_input = alloc::format!("{} BTC", "1".repeat(52));
        let e = Amount::from_str(&long_input).unwrap_err();
        assert_amount_err!(e, InputTooLarge, "error should be InputTooLargeError");

        // InvalidCharacterError
        // invalid character in amount string
        let e = Amount::from_str("12x34 BTC").unwrap_err();
        assert_amount_err!(e, InvalidCharacter, "error should be InvalidCharacterError");
        // too many decimal points
        let e = Amount::from_str("12.3.4 BTC").unwrap_err();
        assert_amount_err!(e, InvalidCharacter, "error should be InvalidCharacterError");
        // too many minus signs
        let e = Amount::from_str("--1234 BTC").unwrap_err();
        assert_amount_err!(e, InvalidCharacter, "error should be InvalidCharacterError");

        // MissingDigitsError
        // no numeric value
        let e = Amount::from_str("BTC").unwrap_err();
        assert_amount_err!(e, MissingDigits, "error should be MissingDigitsError");
        // Only a minus sign
        let e = Amount::from_str("- BTC").unwrap_err();
        assert_amount_err!(e, MissingDigits, "error should be MissingDigitsError");

        // OutOfRangeError
        // amount too large
        let e = Amount::from_str("21000001 BTC").unwrap_err();
        assert_amount_err!(e, OutOfRange, "error should be OutOfRangeError");
        // less than 0
        let e = Amount::from_str("-10 BTC").unwrap_err();
        assert_amount_err!(e, OutOfRange, "error should be OutOfRangeError");

        // TooPreciseError - sub-satoshi precision
        let e = Amount::from_str("0.000000001 BTC").unwrap_err();
        assert_amount_err!(e, TooPrecise, "error should be TooPreciseError");

        // BadPositionError
        // underscore in bad position
        let e = Amount::from_str("_123 BTC").unwrap_err();
        assert_amount_err!(e, BadPosition, "error should be BadPositionError");
        // underscore in bad position (negative)
        let e = Amount::from_str("-_123 BTC").unwrap_err();
        assert_amount_err!(e, BadPosition, "error should be BadPositionError");
        // consecutive underscores
        let e = Amount::from_str("1__23 BTC").unwrap_err();
        assert_amount_err!(e, BadPosition, "error should be BadPositionError");

        // ParseAmountError - parent type for the errors above
        let e = Amount::from_str_in("invalid", Denomination::Bitcoin).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        // UnknownDenominationError - amount with unknown denomination string
        let e = Denomination::from_str("XYZ").unwrap_err();
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        let ParseDenominationError::Unknown(e) = e else {
            panic!("error should be UnknownDenominationError")
        };
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // PossiblyConfusingDenominationError - confusing denomination like "MBTC"
        let e = Denomination::from_str("MBTC").unwrap_err();
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        let ParseDenominationError::PossiblyConfusing(e) = e else {
            panic!("error should be PossiblyConfusingDenominationError")
        };
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // ParseDenominationError - parent error for the above *DenominationError types
        // Unknown type
        let e = Denomination::from_str("UNKNOWN").unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // Possibly confusing type
        let e = Denomination::from_str("MBTC").unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        // ParseError - parent type for all of the above
        // Amount type
        let e = "invalid BTC".parse::<Amount>().unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // bad denomination type
        let e = "123 GBTC".parse::<Amount>().unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // missing denomination type
        let e = "123".parse::<Amount>().unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        #[cfg(feature = "encoding")]
        {
            // AmountDecoderError
            // EOF type
            let mut decoder = Amount::decoder();
            let _ = decoder.push_bytes(&mut [0u8; 3].as_slice());
            let e = decoder.end().unwrap_err();
            assert!(!e.to_string().is_empty());
            #[cfg(feature = "std")]
            assert!(e.source().is_some());

            // Out of range type
            let mut decoder = Amount::decoder();
            let _ =
                decoder.push_bytes(&mut (21_000_001 * 100_000_000_u64).to_le_bytes().as_slice());
            let e = decoder.end().unwrap_err();
            assert!(!e.to_string().is_empty());
            #[cfg(feature = "std")]
            assert!(e.source().is_some());
        }
    }
}