bitcoin-units 0.3.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
// 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;

/// 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 From<ParseAmountError> for ParseError {
    fn from(e: ParseAmountError) -> Self { Self(ParseErrorInner::Amount(e)) }
}

impl From<ParseDenominationError> for ParseError {
    fn from(e: ParseDenominationError) -> Self { Self(ParseErrorInner::Denomination(e)) }
}

impl From<OutOfRangeError> for ParseError {
    fn from(e: OutOfRangeError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

impl From<TooPreciseError> for ParseError {
    fn from(e: TooPreciseError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

impl From<MissingDigitsError> for ParseError {
    fn from(e: MissingDigitsError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

impl From<InputTooLargeError> for ParseError {
    fn from(e: InputTooLargeError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

impl From<InvalidCharacterError> for ParseError {
    fn from(e: InvalidCharacterError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

impl From<BadPositionError> for ParseError {
    fn from(e: BadPositionError) -> Self { Self(ParseErrorInner::Amount(e.into())) }
}

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(_) =>
                f.write_str("the input doesn't contain a denomination"),
        }
    }
}

#[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(_) => None,
        }
    }
}

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

impl From<TooPreciseError> for ParseAmountError {
    fn from(value: TooPreciseError) -> Self { Self(ParseAmountErrorInner::TooPrecise(value)) }
}

impl From<MissingDigitsError> for ParseAmountError {
    fn from(value: MissingDigitsError) -> Self { Self(ParseAmountErrorInner::MissingDigits(value)) }
}

impl From<InputTooLargeError> for ParseAmountError {
    fn from(value: InputTooLargeError) -> Self { Self(ParseAmountErrorInner::InputTooLarge(value)) }
}

impl From<InvalidCharacterError> for ParseAmountError {
    fn from(value: InvalidCharacterError) -> Self {
        Self(ParseAmountErrorInner::InvalidCharacter(value))
    }
}

impl From<BadPositionError> for ParseAmountError {
    fn from(value: BadPositionError) -> Self { Self(ParseAmountErrorInner::BadPosition(value)) }
}

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

#[cfg(feature = "std")]
impl std::error::Error for ParseAmountError {
    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),
        }
    }
}

/// 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.
    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.
    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.
    pub fn is_below_min(self) -> bool { !self.is_greater_than_max }

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

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

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

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

impl From<OutOfRangeError> for ParseAmountError {
    fn from(value: OutOfRangeError) -> Self { Self(ParseAmountErrorInner::OutOfRange(value)) }
}

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

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

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

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

/// 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 fmt::Display for MissingDigitsError {
    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 {}

#[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 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 {}

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

/// 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 {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Unknown(_) | Self::PossiblyConfusing(_) => None,
        }
    }
}

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

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

impl fmt::Display for UnknownDenominationError {
    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 {
    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 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 {
    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.
    pub(super) fn eof(e: encoding::UnexpectedEofError) -> Self {
        Self(AmountDecoderErrorInner::UnexpectedEof(e))
    }

    /// Constructs an out of range (`Amount::from_sat`) error.
    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(all(feature = "std", feature = "encoding"))]
impl std::error::Error for AmountDecoderError {
    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),
        }
    }
}