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
// SPDX-License-Identifier: CC0-1.0

//! Error types for the absolute locktime module.

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

use internals::error::InputString;
#[cfg(feature = "encoding")]
use internals::write_err;

use super::{Height, MedianTimePast, LOCK_TIME_THRESHOLD};
use crate::parse_int::{ParseIntError, PrefixedHexError, UnprefixedHexError};

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

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

#[cfg(feature = "encoding")]
impl fmt::Display for LockTimeDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_err!(f, "lock time decoder error"; self.0)
    }
}

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

/// Tried to satisfy a lock-by-time lock using a height value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncompatibleHeightError {
    /// The inner value of the lock-by-time lock.
    pub(super) lock: MedianTimePast,
    /// Attempted to satisfy a lock-by-time lock with this height.
    pub(super) incompatible: Height,
}

impl IncompatibleHeightError {
    /// Returns the value of the lock-by-time lock.
    #[inline]
    pub fn lock(&self) -> MedianTimePast { self.lock }

    /// Returns the height that was erroneously used to try and satisfy a lock-by-time lock.
    #[inline]
    pub fn incompatible(&self) -> Height { self.incompatible }
}

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

impl fmt::Display for IncompatibleHeightError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "tried to satisfy a lock-by-time lock {} with height: {}",
            self.lock, self.incompatible
        )
    }
}

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

/// Tried to satisfy a lock-by-height lock using a height value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncompatibleTimeError {
    /// The inner value of the lock-by-height lock.
    pub(super) lock: Height,
    /// Attempted to satisfy a lock-by-height lock with this MTP.
    pub(super) incompatible: MedianTimePast,
}

impl IncompatibleTimeError {
    /// Returns the value of the lock-by-height lock.
    #[inline]
    pub fn lock(&self) -> Height { self.lock }

    /// Returns the MTP that was erroneously used to try and satisfy a lock-by-height lock.
    #[inline]
    pub fn incompatible(&self) -> MedianTimePast { self.incompatible }
}

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

impl fmt::Display for IncompatibleTimeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "tried to satisfy a lock-by-height lock {} with MTP: {}",
            self.lock, self.incompatible
        )
    }
}

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

/// Error returned when parsing block height fails.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParseHeightError(ParseError);

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

impl fmt::Display for ParseHeightError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.display(f, "block height", 0, LOCK_TIME_THRESHOLD - 1)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseHeightError {
    // To be consistent with `write_err` we need to **not** return source if overflow occurred
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.0.source() }
}

impl From<ParseError> for ParseHeightError {
    #[inline]
    fn from(value: ParseError) -> Self { Self(value) }
}

/// Error returned when parsing block time fails.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParseTimeError(ParseError);

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

impl fmt::Display for ParseTimeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.display(f, "block time", LOCK_TIME_THRESHOLD, u32::MAX)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseTimeError {
    // To be consistent with `write_err` we need to **not** return source if overflow occurred
    #[inline]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.0.source() }
}

impl From<ParseError> for ParseTimeError {
    #[inline]
    fn from(value: ParseError) -> Self { Self(value) }
}

/// Internal - common representation for height and time.
#[derive(Debug, Clone, Eq, PartialEq)]
pub(super) enum ParseError {
    /// Error parsing prefixed hex
    PrefixedHex(PrefixedHexError),
    /// Error parsing unprefixed hex
    UnprefixedHex(UnprefixedHexError),
    // Error parsing decimal
    ParseInt(ParseIntError),
    // unit implied by outer type
    // we use i64 to have nicer messages for negative values
    Conversion(i64),
}

impl ParseError {
    #[inline]
    pub(super) fn invalid_int<S: Into<InputString>>(
        s: S,
    ) -> impl FnOnce(core::num::ParseIntError) -> Self {
        move |source| {
            Self::ParseInt(ParseIntError { input: s.into(), bits: 32, is_signed: true, source })
        }
    }

    pub(super) fn display(
        &self,
        f: &mut fmt::Formatter<'_>,
        subject: &str,
        lower_bound: u32,
        upper_bound: u32,
    ) -> fmt::Result {
        use core::num::IntErrorKind;

        match self {
            Self::PrefixedHex(ref err) => fmt::Display::fmt(err, f),
            Self::UnprefixedHex(ref err) => fmt::Display::fmt(err, f),
            Self::ParseInt(ParseIntError { input, bits: _, is_signed: _, source })
                if *source.kind() == IntErrorKind::PosOverflow =>
            {
                // Outputs "failed to parse <input_string> as absolute Height/MedianTimePast (<subject> is above limit <upper_bound>)"
                write!(
                    f,
                    "{} ({} is above limit {})",
                    input.display_cannot_parse("absolute Height/MedianTimePast"),
                    subject,
                    upper_bound
                )
            }
            Self::ParseInt(ParseIntError { input, bits: _, is_signed: _, source })
                if *source.kind() == IntErrorKind::NegOverflow =>
            {
                // Outputs "failed to parse <input_string> as absolute Height/MedianTimePast (<subject> is below limit <lower_bound>)"
                write!(
                    f,
                    "{} ({} is below limit {})",
                    input.display_cannot_parse("absolute Height/MedianTimePast"),
                    subject,
                    lower_bound
                )
            }
            Self::ParseInt(ParseIntError { input, bits: _, is_signed: _, source: _ }) => {
                write!(
                    f,
                    "{} ({})",
                    input.display_cannot_parse("absolute Height/MedianTimePast"),
                    subject
                )
            }
            Self::Conversion(value) if *value < i64::from(lower_bound) => {
                write!(f, "{} {} is below limit {}", subject, value, lower_bound)
            }
            Self::Conversion(value) => {
                write!(f, "{} {} is above limit {}", subject, value, upper_bound)
            }
        }
    }

    // To be consistent with `write_err` we need to **not** return source if overflow occurred
    #[inline]
    #[cfg(feature = "std")]
    pub(super) fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use core::num::IntErrorKind;

        match self {
            Self::PrefixedHex(ref err) => Some(err),
            Self::UnprefixedHex(ref err) => Some(err),
            Self::ParseInt(ParseIntError { source, .. })
                if *source.kind() == IntErrorKind::PosOverflow =>
                None,
            Self::ParseInt(ParseIntError { source, .. })
                if *source.kind() == IntErrorKind::NegOverflow =>
                None,
            Self::ParseInt(ParseIntError { source, .. }) => Some(source),
            Self::Conversion(_) => None,
        }
    }
}

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

impl From<ConversionError> for ParseError {
    #[inline]
    fn from(value: ConversionError) -> Self { Self::Conversion(value.input.into()) }
}

impl From<PrefixedHexError> for ParseError {
    #[inline]
    fn from(value: PrefixedHexError) -> Self { Self::PrefixedHex(value) }
}

impl From<UnprefixedHexError> for ParseError {
    #[inline]
    fn from(value: UnprefixedHexError) -> Self { Self::UnprefixedHex(value) }
}

/// Error returned when converting a `u32` to a lock time variant fails.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConversionError {
    /// The expected timelock unit, height (blocks) or time (seconds).
    unit: LockTimeUnit,
    /// The invalid input value.
    input: u32,
}

impl ConversionError {
    /// Constructs a new `ConversionError` from an invalid `n` when expecting a height value.
    #[inline]
    pub(super) const fn invalid_height(n: u32) -> Self {
        Self { unit: LockTimeUnit::Blocks, input: n }
    }

    /// Constructs a new `ConversionError` from an invalid `n` when expecting a time value.
    #[inline]
    pub(super) const fn invalid_time(n: u32) -> Self {
        Self { unit: LockTimeUnit::Seconds, input: n }
    }
}

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

impl fmt::Display for ConversionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid lock time value {}, {}", self.input, self.unit)
    }
}

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

/// Describes the two types of locking, lock-by-height and lock-by-time.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum LockTimeUnit {
    /// Lock by blockheight.
    Blocks,
    /// Lock by blocktime.
    Seconds,
}

impl fmt::Display for LockTimeUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Blocks =>
                write!(f, "expected lock-by-height (must be < {})", LOCK_TIME_THRESHOLD),
            Self::Seconds =>
                write!(f, "expected lock-by-time (must be >= {})", LOCK_TIME_THRESHOLD),
        }
    }
}

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

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

    #[cfg(feature = "alloc")]
    use super::LockTimeUnit;
    #[cfg(feature = "alloc")]
    use crate::{
        locktime::absolute::{Height, LockTime, MedianTimePast},
        BlockHeight,
    };

    #[test]
    #[cfg(feature = "alloc")]
    fn locktime_unit_display() {
        let blocks = LockTimeUnit::Blocks;
        let seconds = LockTimeUnit::Seconds;

        assert_eq!(format!("{}", blocks), "expected lock-by-height (must be < 500000000)");
        assert_eq!(format!("{}", seconds), "expected lock-by-time (must be >= 500000000)");
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn error_display_is_non_empty() {
        // ConversionError - converting BlockHeight to absolute::Height
        let too_big = BlockHeight::from_u32(u32::MAX);
        let e = Height::try_from(too_big).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // IncompatibleHeightError - satisfy time lock with height
        let time_lock = LockTime::from_mtp(MedianTimePast::MIN.to_u32()).unwrap();
        let e = time_lock.is_satisfied_by_height(Height::MIN).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // IncompatibleTimeError - satisfy height lock with time
        let height_lock = LockTime::from_height(Height::MIN.to_u32()).unwrap();
        let e = height_lock.is_satisfied_by_time(MedianTimePast::MIN).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // ParseHeightError - parse invalid height
        let e = Height::from_str("invalid").unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        // ParseTimeError - parse invalid time
        let e = MedianTimePast::from_str("invalid").unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        #[cfg(feature = "encoding")]
        {
            // LockTimeDecoderError
            let mut decoder = LockTime::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());
        }
    }
}