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

//! Error types for the relative locktime module.

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

use internals::write_err;

use super::{NumberOf512Seconds, NumberOfBlocks};

/// Error returned when a sequence number is parsed as a lock time, but its
/// "disable" flag is set.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DisabledLockTimeError(pub(super) u32);

impl DisabledLockTimeError {
    /// Accessor for the `u32` whose "disable" flag was set, preventing
    /// it from being parsed as a relative locktime.
    #[inline]
    pub fn disabled_locktime_value(&self) -> u32 { self.0 }
}

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

impl fmt::Display for DisabledLockTimeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "lock time 0x{:08x} has disable flag set", self.0)
    }
}

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

/// Error returned when [`is_satisfied_by`] fails.
///
/// [`is_satisfied_by`]: super::LockTime::is_satisfied_by
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum IsSatisfiedByError {
    /// Error when attempting to satisfy lock by block count.
    Blocks(InvalidHeightError),
    /// Error when attempting to satisfy lock by time.
    Time(InvalidTimeError),
}

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

impl fmt::Display for IsSatisfiedByError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Blocks(ref e) => write_err!(f, "blocks"; e),
            Self::Time(ref e) => write_err!(f, "time"; e),
        }
    }
}

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

/// Error returned when [`is_satisfied_by_height`] fails.
///
/// [`is_satisfied_by_height`]: super::LockTime::is_satisfied_by_height
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IsSatisfiedByHeightError {
    /// Satisfaction of the lock height value failed.
    Satisfaction(InvalidHeightError),
    /// Tried to satisfy a lock-by-time locktime using a block height.
    Incompatible(IncompatibleHeightError),
}

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

impl fmt::Display for IsSatisfiedByHeightError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Satisfaction(ref e) => write_err!(f, "satisfaction"; e),
            Self::Incompatible(ref e) => write_err!(f, "incompatible"; e),
        }
    }
}

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

/// Error returned when [`is_satisfied_by_height`] fails with a block time.
///
/// [`is_satisfied_by_height`]: super::LockTime::is_satisfied_by_height
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncompatibleHeightError(pub(crate) NumberOf512Seconds);

impl From<Infallible> for IncompatibleHeightError {
    #[inline]
    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 locktime ({} 512-second intervals) using a block height",
            self.0
        )
    }
}

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

/// Error returned when [`is_satisfied_by_time`] fails.
///
/// [`is_satisfied_by_time`]: super::LockTime::is_satisfied_by_time
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IsSatisfiedByTimeError {
    /// Satisfaction of the lock time value failed.
    Satisfaction(InvalidTimeError),
    /// Tried to satisfy a lock-by-block-count locktime using an MTP.
    Incompatible(IncompatibleTimeError),
}

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

impl fmt::Display for IsSatisfiedByTimeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Satisfaction(ref e) => write_err!(f, "satisfaction"; e),
            Self::Incompatible(ref e) => write_err!(f, "incompatible"; e),
        }
    }
}

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

/// Error returned when [`is_satisfied_by_time`] fails with a block height.
///
/// [`is_satisfied_by_time`]: super::LockTime::is_satisfied_by_time
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncompatibleTimeError(pub(crate) NumberOfBlocks);

impl From<Infallible> for IncompatibleTimeError {
    #[inline]
    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 locktime ({} blocks) using an MTP", self.0)
    }
}

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

/// Error returned when the input time in seconds was too large to be encoded to a 16 bit 512 second interval.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeOverflowError {
    /// Time interval value in seconds that overflowed.
    // Private because we maintain an invariant that the `seconds` value does actually overflow.
    pub(crate) seconds: u32,
}

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

impl fmt::Display for TimeOverflowError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} seconds is too large to be encoded to a 16 bit 512 second interval",
            self.seconds
        )
    }
}

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

/// Error returned when [`is_satisfied_by`] is incorrectly called.
///
/// [`is_satisfied_by`]: super::NumberOfBlocks::is_satisfied_by
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidHeightError {
    /// The `chain_tip` argument.
    pub(crate) chain_tip: crate::BlockHeight,
    /// The `utxo_mined_at` argument.
    pub(crate) utxo_mined_at: crate::BlockHeight,
}

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

impl fmt::Display for InvalidHeightError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "is_satisfied_by arguments invalid (probably the wrong way around) chain_tip: {} utxo_mined_at: {}", self.chain_tip, self.utxo_mined_at
        )
    }
}

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

/// Error returned when [`is_satisfied_by`] is incorrectly called.
///
/// [`is_satisfied_by`]: super::NumberOf512Seconds::is_satisfied_by
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidTimeError {
    /// The `chain_tip` argument.
    pub(crate) chain_tip: crate::BlockMtp,
    /// The `utxo_mined_at` argument.
    pub(crate) utxo_mined_at: crate::BlockMtp,
}

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

impl fmt::Display for InvalidTimeError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "is_satisfied_by arguments invalid (probably the wrong way around) chain_tip: {} utxo_mined_at: {}", self.chain_tip, self.utxo_mined_at
        )
    }
}

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

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

    #[cfg(feature = "alloc")]
    use crate::{
        locktime::relative::{LockTime, NumberOf512Seconds, NumberOfBlocks},
        BlockHeight, BlockMtp, BlockMtpInterval, Sequence,
    };

    #[test]
    #[cfg(feature = "alloc")]
    fn error_display_is_non_empty() {
        // DisabledLockTimeError - parse disabled lock time
        let disabled = Sequence::MAX; // Sequence with disable flag set
        let e = LockTime::from_sequence(disabled).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // TimeOverflowError - time too large for relative locktime
        let too_big = BlockMtpInterval::MAX;
        let e = too_big.to_relative_mtp_interval_floor().unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // InvalidHeightError - is_satisfied_by with invalid args
        let blocks = NumberOfBlocks::from_count(10);
        let e = blocks
            .is_satisfied_by(BlockHeight::from_u32(5), Some(BlockHeight::from_u32(10)))
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // InvalidTimeError - is_satisfied_by with invalid args
        let time = NumberOf512Seconds::from_512_second_intervals(10);
        let e =
            time.is_satisfied_by(BlockMtp::from_u32(5), Some(BlockMtp::from_u32(10))).unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_none());

        // IsSatisfiedBy*Error
        let time_lock = LockTime::from_512_second_intervals(10);
        let height_lock = LockTime::from_block_count(10);

        // IsSatisfiedByError - wraps InvalidHeightError or InvalidTimeError
        // Error when chain_tip < utxo_mined_at (args wrong way around)
        // blocks type
        let e = height_lock
            .is_satisfied_by(
                BlockHeight::from_u32(5),
                BlockMtp::ZERO,
                Some(BlockHeight::from_u32(10)),
                Some(BlockMtp::ZERO),
            )
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // time type
        let e = time_lock
            .is_satisfied_by(
                BlockHeight::ZERO,
                BlockMtp::from_u32(5),
                Some(BlockHeight::ZERO),
                Some(BlockMtp::from_u32(10)),
            )
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        // IsSatisfiedByHeightError
        // Incompatible type
        let e = time_lock
            .is_satisfied_by_height(BlockHeight::from_u32(5), Some(BlockHeight::from_u32(10)))
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // Satisfaction type
        let e = height_lock
            .is_satisfied_by_height(BlockHeight::from_u32(5), Some(BlockHeight::from_u32(10)))
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());

        // IsSatisfiedByTimeError
        // Incompatible type
        let e = height_lock
            .is_satisfied_by_time(BlockMtp::from_u32(5), Some(BlockMtp::from_u32(10)))
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
        // Satisfaction type
        let e = time_lock
            .is_satisfied_by_time(BlockMtp::from_u32(5), Some(BlockMtp::from_u32(10)))
            .unwrap_err();
        assert!(!e.to_string().is_empty());
        #[cfg(feature = "std")]
        assert!(e.source().is_some());
    }
}