Skip to main content

bitcoin_units/locktime/relative/
mod.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Provides type [`LockTime`] that implements the logic around `nSequence`/`OP_CHECKSEQUENCEVERIFY`.
4//!
5//! There are two types of lock time: lock-by-height and lock-by-time, distinguished by whether bit
6//! 22 of the `u32` consensus value is set. To support these we provide the [`NumberOfBlocks`] and
7//! [`NumberOf512Seconds`] types.
8
9pub mod error;
10
11use core::{convert, fmt};
12
13#[cfg(feature = "arbitrary")]
14use arbitrary::{Arbitrary, Unstructured};
15use internals::const_casts;
16
17use crate::parse_int::{self, PrefixedHexError, UnprefixedHexError};
18#[cfg(doc)]
19use crate::relative;
20use crate::{BlockHeight, BlockMtp, Sequence};
21
22#[rustfmt::skip]                // Keep public re-exports separate.
23#[doc(no_inline)]
24pub use self::error::{
25    DisabledLockTimeError, IncompatibleHeightError, IncompatibleTimeError, InvalidHeightError,
26    InvalidTimeError, IsSatisfiedByError, IsSatisfiedByHeightError, IsSatisfiedByTimeError,
27    TimeOverflowError,
28};
29
30/// A relative lock time value, representing either a block height or time (512 second intervals).
31///
32/// Used for sequence numbers (`nSequence` in Bitcoin Core and `TxIn::sequence`
33/// in `rust-bitcoin`) and also for the argument to opcode `OP_CHECKSEQUENCEVERIFY`.
34///
35/// # Note on ordering
36///
37/// Locktimes may be height- or time-based, and these metrics are incommensurate; there is no total
38/// ordering on locktimes. In order to compare locktimes, instead of using `<` or `>` we provide the
39/// [`LockTime::is_satisfied_by`] API.
40///
41/// # Relevant BIPs
42///
43/// * [BIP-0068 Relative lock-time using consensus-enforced sequence numbers](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)
44/// * [BIP-0112 CHECKSEQUENCEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki)
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum LockTime {
47    /// A block height lock time value.
48    Blocks(NumberOfBlocks),
49    /// A 512 second time interval value.
50    Time(NumberOf512Seconds),
51}
52
53impl LockTime {
54    /// A relative locktime of 0 is always valid, and is assumed valid for inputs that
55    /// are not yet confirmed.
56    pub const ZERO: Self = Self::Blocks(NumberOfBlocks::ZERO);
57
58    /// The number of bytes that the locktime contributes to the size of a transaction.
59    pub const SIZE: usize = 4; // Serialized length of a u32.
60
61    /// Constructs a new `LockTime` from an `nSequence` value or the argument to `OP_CHECKSEQUENCEVERIFY`.
62    ///
63    /// This method will **not** round-trip with [`Self::to_consensus_u32`], because relative
64    /// locktimes only use some bits of the underlying `u32` value and discard the rest. If
65    /// you want to preserve the full value, you should use the [`Sequence`] type instead.
66    ///
67    /// # Errors
68    ///
69    /// If `n`, interpreted as a [`Sequence`] number does not encode a relative lock time.
70    ///
71    /// # Examples
72    ///
73    /// ```rust
74    /// # use bitcoin_units::relative;
75    ///
76    /// // Values with bit 22 set to 0 will be interpreted as height-based lock times.
77    /// let height: u32 = 144; // 144 blocks, approx 24h.
78    /// let lock_time = relative::LockTime::from_consensus(height)?;
79    /// assert!(lock_time.is_block_height());
80    /// assert_eq!(lock_time.to_consensus_u32(), height);
81    ///
82    /// // Values with bit 22 set to 1 will be interpreted as time-based lock times.
83    /// let time: u32 = 168 | (1 << 22) ; // Bit 22 is 1 with time approx 24h.
84    /// let lock_time = relative::LockTime::from_consensus(time)?;
85    /// assert!(lock_time.is_block_time());
86    /// assert_eq!(lock_time.to_consensus_u32(), time);
87    ///
88    /// # Ok::<_, relative::error::DisabledLockTimeError>(())
89    /// ```
90    #[inline]
91    pub fn from_consensus(n: u32) -> Result<Self, DisabledLockTimeError> {
92        let sequence = crate::Sequence::from_consensus(n);
93        sequence.to_relative_lock_time().ok_or(DisabledLockTimeError(n))
94    }
95
96    /// Returns the `u32` value used to encode this locktime in an `nSequence` field or
97    /// argument to `OP_CHECKSEQUENCEVERIFY`.
98    ///
99    /// # Warning
100    ///
101    /// Locktimes are not ordered by the natural ordering on `u32`. If you want to
102    /// compare locktimes, use [`Self::is_implied_by`] or similar methods.
103    #[inline]
104    pub fn to_consensus_u32(self) -> u32 {
105        match self {
106            Self::Blocks(ref h) => u32::from(h.to_height()),
107            Self::Time(ref t) => Sequence::LOCK_TYPE_MASK | u32::from(t.to_512_second_intervals()),
108        }
109    }
110
111    /// Constructs a new `LockTime` from the sequence number of a Bitcoin input.
112    ///
113    /// This method will **not** round-trip with [`Self::to_sequence`]. See the
114    /// docs for [`Self::from_consensus`] for more information.
115    ///
116    /// # Errors
117    ///
118    /// If `n` does not encode a relative lock time.
119    ///
120    /// # Examples
121    ///
122    /// ```rust
123    /// # use bitcoin_units::{Sequence, relative};
124    ///
125    /// // Interpret a sequence number from a Bitcoin transaction input as a relative lock time
126    /// let sequence_number = Sequence::from_consensus(144); // 144 blocks, approx 24h.
127    /// let lock_time = relative::LockTime::from_sequence(sequence_number)?;
128    /// assert!(lock_time.is_block_height());
129    ///
130    /// # Ok::<_, relative::error::DisabledLockTimeError>(())
131    /// ```
132    #[inline]
133    pub fn from_sequence(n: Sequence) -> Result<Self, DisabledLockTimeError> {
134        Self::from_consensus(n.to_consensus_u32())
135    }
136
137    /// Encodes the locktime as a sequence number.
138    #[inline]
139    pub fn to_sequence(self) -> Sequence { Sequence::from_consensus(self.to_consensus_u32()) }
140
141    /// Constructs a new `LockTime` from `n`, expecting `n` to be a 16-bit count of blocks.
142    #[inline]
143    pub const fn from_height(n: u16) -> Self { Self::Blocks(NumberOfBlocks::from_height(n)) }
144
145    /// Constructs a new `LockTime` from `n`, expecting `n` to be a count of 512-second intervals.
146    ///
147    /// This function is a little awkward to use, and users may wish to instead use
148    /// [`Self::from_seconds_floor`] or [`Self::from_seconds_ceil`].
149    #[inline]
150    pub const fn from_512_second_intervals(intervals: u16) -> Self {
151        Self::Time(NumberOf512Seconds::from_512_second_intervals(intervals))
152    }
153
154    /// Constructs a new [`LockTime`] from seconds, converting the seconds into 512 second interval
155    /// with truncating division.
156    ///
157    /// # Errors
158    ///
159    /// Will return an error if the input cannot be encoded in 16 bits.
160    #[inline]
161    pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
162        match NumberOf512Seconds::from_seconds_floor(seconds) {
163            Ok(time) => Ok(Self::Time(time)),
164            Err(e) => Err(e),
165        }
166    }
167
168    /// Constructs a new [`LockTime`] from seconds, converting the seconds into 512 second interval
169    /// with ceiling division.
170    ///
171    /// # Errors
172    ///
173    /// Will return an error if the input cannot be encoded in 16 bits.
174    #[inline]
175    pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
176        match NumberOf512Seconds::from_seconds_ceil(seconds) {
177            Ok(time) => Ok(Self::Time(time)),
178            Err(e) => Err(e),
179        }
180    }
181
182    /// Returns true if both lock times use the same unit i.e., both height based or both time based.
183    #[inline]
184    pub const fn is_same_unit(self, other: Self) -> bool {
185        matches!((self, other), (Self::Blocks(_), Self::Blocks(_)) | (Self::Time(_), Self::Time(_)))
186    }
187
188    /// Returns true if this lock time value is in units of block height.
189    #[inline]
190    pub const fn is_block_height(self) -> bool { matches!(self, Self::Blocks(_)) }
191
192    /// Returns true if this lock time value is in units of time.
193    #[inline]
194    pub const fn is_block_time(self) -> bool { !self.is_block_height() }
195
196    /// Returns true if this [`relative::LockTime`] is satisfied by the given chain state.
197    ///
198    /// If this function returns true then an output with this locktime can be spent in the next
199    /// block.
200    ///
201    /// # Errors
202    ///
203    /// If `chain_tip` as not _after_ `utxo_mined_at` i.e., if you get the args mixed up.
204    #[inline]
205    pub fn is_satisfied_by(
206        self,
207        chain_tip_height: BlockHeight,
208        chain_tip_mtp: BlockMtp,
209        utxo_mined_at_height: BlockHeight,
210        utxo_mined_at_mtp: BlockMtp,
211    ) -> Result<bool, IsSatisfiedByError> {
212        match self {
213            Self::Blocks(blocks) => blocks
214                .is_satisfied_by(chain_tip_height, utxo_mined_at_height)
215                .map_err(IsSatisfiedByError::Blocks),
216            Self::Time(time) => time
217                .is_satisfied_by(chain_tip_mtp, utxo_mined_at_mtp)
218                .map_err(IsSatisfiedByError::Time),
219        }
220    }
221
222    /// Returns true if an output with this locktime can be spent in the next block.
223    ///
224    /// If this function returns true then an output with this locktime can be spent in the next
225    /// block.
226    ///
227    /// # Errors
228    ///
229    /// Returns an error if this lock is not lock-by-height.
230    #[inline]
231    pub fn is_satisfied_by_height(
232        self,
233        chain_tip: BlockHeight,
234        utxo_mined_at: BlockHeight,
235    ) -> Result<bool, IsSatisfiedByHeightError> {
236        match self {
237            Self::Blocks(blocks) => blocks
238                .is_satisfied_by(chain_tip, utxo_mined_at)
239                .map_err(IsSatisfiedByHeightError::Satisfaction),
240            Self::Time(time) =>
241                Err(IsSatisfiedByHeightError::Incompatible(IncompatibleHeightError(time))),
242        }
243    }
244
245    /// Returns true if an output with this locktime can be spent in the next block.
246    ///
247    /// If this function returns true then an output with this locktime can be spent in the next
248    /// block.
249    ///
250    /// # Errors
251    ///
252    /// Returns an error if this lock is not lock-by-time.
253    #[inline]
254    pub fn is_satisfied_by_time(
255        self,
256        chain_tip: BlockMtp,
257        utxo_mined_at: BlockMtp,
258    ) -> Result<bool, IsSatisfiedByTimeError> {
259        match self {
260            Self::Time(time) => time
261                .is_satisfied_by(chain_tip, utxo_mined_at)
262                .map_err(IsSatisfiedByTimeError::Satisfaction),
263            Self::Blocks(blocks) =>
264                Err(IsSatisfiedByTimeError::Incompatible(IncompatibleTimeError(blocks))),
265        }
266    }
267
268    /// Returns true if satisfaction of `other` lock time implies satisfaction of this
269    /// [`relative::LockTime`].
270    ///
271    /// A lock time can only be satisfied by n blocks being mined or n seconds passing. If you have
272    /// two lock times (same unit) then the larger lock time being satisfied implies (in a
273    /// mathematical sense) the smaller one being satisfied.
274    ///
275    /// This function is useful when checking sequence values against a lock, first one checks the
276    /// sequence represents a relative lock time by converting to `LockTime` then use this function
277    /// to see if satisfaction of the newly created lock time would imply satisfaction of `self`.
278    ///
279    /// Can also be used to remove the smaller value of two `OP_CHECKSEQUENCEVERIFY` operations
280    /// within one branch of the script.
281    ///
282    /// # Examples
283    ///
284    /// ```rust
285    /// # use bitcoin_units::Sequence;
286    ///
287    /// # let required_height = 100;       // 100 blocks.
288    /// # let lock = Sequence::from_height(required_height).to_relative_lock_time().expect("valid height");
289    /// # let test_sequence = Sequence::from_height(required_height + 10);
290    ///
291    /// let satisfied = match test_sequence.to_relative_lock_time() {
292    ///     None => false, // Handle non-lock-time case.
293    ///     Some(test_lock) => lock.is_implied_by(test_lock),
294    /// };
295    /// assert!(satisfied);
296    /// ```
297    #[inline]
298    pub fn is_implied_by(self, other: Self) -> bool {
299        match (self, other) {
300            (Self::Blocks(this), Self::Blocks(other)) => this <= other,
301            (Self::Time(this), Self::Time(other)) => this <= other,
302            _ => false, // Not the same units.
303        }
304    }
305
306    /// Returns true if satisfaction of the sequence number implies satisfaction of this lock time.
307    ///
308    /// When deciding whether an instance of `<n> CHECKSEQUENCEVERIFY` will pass, this
309    /// method can be used by parsing `n` as a [`LockTime`] and calling this method
310    /// with the sequence number of the input which spends the script.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// # use bitcoin_units::{Sequence, relative};
316    ///
317    /// let sequence = Sequence::from_consensus(1 << 22 | 168); // Bit 22 is 1 with time approx 24h.
318    /// let lock_time = relative::LockTime::from_sequence(sequence)?;
319    /// let input_sequence = Sequence::from_consensus(1 << 22 | 336); // Approx 48h.
320    /// assert!(lock_time.is_block_time());
321    ///
322    /// assert!(lock_time.is_implied_by_sequence(input_sequence));
323    ///
324    /// # Ok::<_, relative::error::DisabledLockTimeError>(())
325    /// ```
326    #[inline]
327    pub fn is_implied_by_sequence(self, other: Sequence) -> bool {
328        Self::from_sequence(other).is_ok_and(|other| self.is_implied_by(other))
329    }
330}
331
332impl From<NumberOfBlocks> for LockTime {
333    #[inline]
334    fn from(h: NumberOfBlocks) -> Self { Self::Blocks(h) }
335}
336
337impl From<NumberOf512Seconds> for LockTime {
338    #[inline]
339    fn from(t: NumberOf512Seconds) -> Self { Self::Time(t) }
340}
341
342impl fmt::Display for LockTime {
343    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344        if f.alternate() {
345            match *self {
346                Self::Blocks(ref h) => write!(f, "block-height {}", h),
347                Self::Time(ref t) => write!(f, "block-time {} (512 second intervals)", t),
348            }
349        } else {
350            match *self {
351                Self::Blocks(ref h) => fmt::Display::fmt(h, f),
352                Self::Time(ref t) => fmt::Display::fmt(t, f),
353            }
354        }
355    }
356}
357
358impl convert::TryFrom<Sequence> for LockTime {
359    type Error = DisabledLockTimeError;
360    #[inline]
361    fn try_from(seq: Sequence) -> Result<Self, DisabledLockTimeError> { Self::from_sequence(seq) }
362}
363
364impl From<LockTime> for Sequence {
365    #[inline]
366    fn from(lt: LockTime) -> Self { lt.to_sequence() }
367}
368
369#[cfg(feature = "serde")]
370impl serde::Serialize for LockTime {
371    #[inline]
372    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373    where
374        S: serde::Serializer,
375    {
376        self.to_consensus_u32().serialize(serializer)
377    }
378}
379
380#[cfg(feature = "serde")]
381impl<'de> serde::Deserialize<'de> for LockTime {
382    #[inline]
383    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
384    where
385        D: serde::Deserializer<'de>,
386    {
387        u32::deserialize(deserializer)
388            .and_then(|n| Self::from_consensus(n).map_err(serde::de::Error::custom))
389    }
390}
391
392/// A relative lock time lock-by-height value.
393#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
394pub struct NumberOfBlocks(u16);
395
396impl NumberOfBlocks {
397    /// Relative block height 0, can be included in any block.
398    pub const ZERO: Self = Self(0);
399
400    /// The minimum relative block height (0), can be included in any block.
401    pub const MIN: Self = Self::ZERO;
402
403    /// The maximum relative block height.
404    pub const MAX: Self = Self(u16::MAX);
405
406    /// Constructs a new [`NumberOfBlocks`] using a count of blocks.
407    #[inline]
408    pub const fn from_height(blocks: u16) -> Self { Self(blocks) }
409
410    /// Express the [`NumberOfBlocks`] as a count of blocks.
411    #[inline]
412    #[must_use]
413    pub const fn to_height(self) -> u16 { self.0 }
414
415    /// Constructs a new `NumberOfBlocks` from a prefixed hex string.
416    ///
417    /// # Errors
418    ///
419    /// If the input string is not a valid hex representation of a block count or it does not
420    /// include the `0x` prefix.
421    #[inline]
422    pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
423        let block_count = parse_int::hex_u16_prefixed(s)?;
424        Ok(Self::from_height(block_count))
425    }
426
427    /// Constructs a new `NumberOfBlocks` from an unprefixed hex string.
428    ///
429    /// # Errors
430    ///
431    /// If the input string is not a valid hex representation of a block count or if it includes
432    /// the `0x` prefix.
433    #[inline]
434    pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
435        let block_count = parse_int::hex_u16_unprefixed(s)?;
436        Ok(Self::from_height(block_count))
437    }
438
439    /// Returns true if an output locked by height can be spent in the next block.
440    ///
441    /// # Errors
442    ///
443    /// If `chain_tip` as not _after_ `utxo_mined_at` i.e., if you get the args mixed up.
444    pub fn is_satisfied_by(
445        self,
446        chain_tip: crate::BlockHeight,
447        utxo_mined_at: crate::BlockHeight,
448    ) -> Result<bool, InvalidHeightError> {
449        match chain_tip.checked_sub(utxo_mined_at) {
450            Some(diff) => {
451                if diff.to_u32() == u32::MAX {
452                    // Weird but ok none the less - protects against overflow below.
453                    return Ok(true);
454                }
455                // +1 because the next block will have height 1 higher than `chain_tip`.
456                Ok(u32::from(self.to_height()) <= diff.to_u32() + 1)
457            }
458            None => Err(InvalidHeightError { chain_tip, utxo_mined_at }),
459        }
460    }
461}
462
463crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(NumberOfBlocks);
464
465impl From<u16> for NumberOfBlocks {
466    #[inline]
467    fn from(value: u16) -> Self { Self(value) }
468}
469
470parse_int::impl_parse_str_from_int_infallible!(NumberOfBlocks, u16, from);
471
472impl fmt::Display for NumberOfBlocks {
473    #[inline]
474    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
475}
476
477/// A relative lock time lock-by-time value.
478///
479/// For BIP-0068 relative lock-by-time locks, time is measured in 512 second intervals.
480#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
481pub struct NumberOf512Seconds(u16);
482
483impl NumberOf512Seconds {
484    /// Relative block time 0, can be included in any block.
485    pub const ZERO: Self = Self(0);
486
487    /// The minimum relative block time (0), can be included in any block.
488    pub const MIN: Self = Self::ZERO;
489
490    /// The maximum relative block time (33,553,920 seconds or approx 388 days).
491    pub const MAX: Self = Self(u16::MAX);
492
493    /// Constructs a new [`NumberOf512Seconds`] using time intervals where each interval is
494    /// equivalent to 512 seconds.
495    ///
496    /// Encoding finer granularity of time for relative lock-times is not supported in Bitcoin.
497    #[inline]
498    pub const fn from_512_second_intervals(intervals: u16) -> Self { Self(intervals) }
499
500    /// Express the [`NumberOf512Seconds`] as an integer number of 512-second intervals.
501    #[inline]
502    #[must_use]
503    pub const fn to_512_second_intervals(self) -> u16 { self.0 }
504
505    /// Constructs a new [`NumberOf512Seconds`] from seconds, converting the seconds into a 512
506    /// second interval using truncating division.
507    ///
508    /// # Errors
509    ///
510    /// Will return an error if the input cannot be encoded in 16 bits.
511    #[inline]
512    #[rustfmt::skip] // moves comments to unrelated code
513    pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
514        let interval = seconds / 512;
515        if interval <= u16::MAX as u32 { // infallible cast, needed by const code
516            Ok(Self::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
517        } else {
518            Err(TimeOverflowError { seconds })
519        }
520    }
521
522    /// Constructs a new [`NumberOf512Seconds`] from seconds, converting the seconds into a 512
523    /// second interval using ceiling division.
524    ///
525    /// # Errors
526    ///
527    /// Will return an error if the input cannot be encoded in 16 bits.
528    #[inline]
529    #[rustfmt::skip] // moves comments to unrelated code
530    pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
531        if seconds <= u16::MAX as u32 * 512 {
532            let interval = seconds.div_ceil(512);
533            Ok(Self::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
534        } else {
535            Err(TimeOverflowError { seconds })
536        }
537    }
538
539    /// Represents the [`NumberOf512Seconds`] as an integer number of seconds.
540    #[inline]
541    pub const fn to_seconds(self) -> u32 { const_casts::u16_to_u32(self.0) * 512 }
542
543    /// Constructs a new `NumberOf512Seconds` from a prefixed hex string.
544    ///
545    /// # Errors
546    ///
547    /// If the input string is not a valid hex representation of a number of 512 second intervals
548    /// or it does not include the `0x` prefix.
549    #[inline]
550    pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
551        let block_count = parse_int::hex_u16_prefixed(s)?;
552        Ok(Self::from_512_second_intervals(block_count))
553    }
554
555    /// Constructs a new `NumberOf512Seconds` from an unprefixed hex string.
556    ///
557    /// # Errors
558    ///
559    /// If the input string is not a valid hex representation of a number of 512 second intervals
560    /// or if it includes the `0x` prefix.
561    #[inline]
562    pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
563        let block_count = parse_int::hex_u16_unprefixed(s)?;
564        Ok(Self::from_512_second_intervals(block_count))
565    }
566
567    /// Returns true if an output locked by time can be spent in the next block.
568    ///
569    /// # Errors
570    ///
571    /// If `chain_tip` as not _after_ `utxo_mined_at` i.e., if you get the args mixed up.
572    pub fn is_satisfied_by(
573        self,
574        chain_tip: crate::BlockMtp,
575        utxo_mined_at: crate::BlockMtp,
576    ) -> Result<bool, InvalidTimeError> {
577        chain_tip
578            .checked_sub(utxo_mined_at)
579            .ok_or(InvalidTimeError { chain_tip, utxo_mined_at })
580            .map(|diff| self.to_seconds() <= diff.to_u32())
581    }
582}
583
584crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(NumberOf512Seconds);
585
586parse_int::impl_parse_str_from_int_infallible!(NumberOf512Seconds, u16, from_512_second_intervals);
587
588impl fmt::Display for NumberOf512Seconds {
589    #[inline]
590    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
591}
592
593#[cfg(feature = "arbitrary")]
594impl<'a> Arbitrary<'a> for LockTime {
595    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
596        let choice = u.int_in_range(0..=1)?;
597
598        match choice {
599            0 => Ok(Self::Blocks(NumberOfBlocks::arbitrary(u)?)),
600            _ => Ok(Self::Time(NumberOf512Seconds::arbitrary(u)?)),
601        }
602    }
603}
604
605#[cfg(feature = "arbitrary")]
606impl<'a> Arbitrary<'a> for NumberOfBlocks {
607    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
608        let choice = u.int_in_range(0..=2)?;
609
610        match choice {
611            0 => Ok(Self::MIN),
612            1 => Ok(Self::MAX),
613            _ => Ok(Self::from_height(u16::arbitrary(u)?)),
614        }
615    }
616}
617
618#[cfg(feature = "arbitrary")]
619impl<'a> Arbitrary<'a> for NumberOf512Seconds {
620    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
621        let choice = u.int_in_range(0..=2)?;
622
623        match choice {
624            0 => Ok(Self::MIN),
625            1 => Ok(Self::MAX),
626            _ => Ok(Self::from_512_second_intervals(u16::arbitrary(u)?)),
627        }
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    #[cfg(feature = "alloc")]
634    use alloc::format;
635
636    use super::*;
637    use crate::{BlockHeight, BlockTime};
638
639    const MAXIMUM_ENCODABLE_SECONDS: u32 = u16::MAX as u32 * 512;
640
641    #[test]
642    #[cfg(feature = "alloc")]
643    fn display_and_alternate() {
644        let lock_by_height = LockTime::from_height(10);
645        let lock_by_time = LockTime::from_512_second_intervals(70);
646
647        assert_eq!(format!("{}", lock_by_height), "10");
648        assert_eq!(format!("{:#}", lock_by_height), "block-height 10");
649        assert!(!format!("{:?}", lock_by_height).is_empty());
650
651        assert_eq!(format!("{}", lock_by_time), "70");
652        assert_eq!(format!("{:#}", lock_by_time), "block-time 70 (512 second intervals)");
653        assert!(!format!("{:?}", lock_by_time).is_empty());
654    }
655
656    #[test]
657    fn from_seconds_ceil_and_floor() {
658        let time = 70 * 512 + 1;
659        let lock_by_time = LockTime::from_seconds_ceil(time).unwrap();
660        assert_eq!(lock_by_time, LockTime::from_512_second_intervals(71));
661
662        let lock_by_time = LockTime::from_seconds_floor(time).unwrap();
663        assert_eq!(lock_by_time, LockTime::from_512_second_intervals(70));
664
665        let mut max_time = 0xffff * 512;
666        assert_eq!(LockTime::from_seconds_ceil(max_time), LockTime::from_seconds_floor(max_time));
667        max_time += 512;
668        assert!(LockTime::from_seconds_ceil(max_time).is_err());
669        assert!(LockTime::from_seconds_floor(max_time).is_err());
670    }
671
672    #[test]
673    fn parses_correctly_to_height_or_time() {
674        let height1 = NumberOfBlocks::from(10);
675        let height2 = NumberOfBlocks::from(11);
676        let time1 = NumberOf512Seconds::from_512_second_intervals(70);
677        let time2 = NumberOf512Seconds::from_512_second_intervals(71);
678
679        let lock_by_height1 = LockTime::from(height1);
680        let lock_by_height2 = LockTime::from(height2);
681        let lock_by_time1 = LockTime::from(time1);
682        let lock_by_time2 = LockTime::from(time2);
683
684        assert!(lock_by_height1.is_block_height());
685        assert!(!lock_by_height1.is_block_time());
686
687        assert!(!lock_by_time1.is_block_height());
688        assert!(lock_by_time1.is_block_time());
689
690        // Test is_same_unit() logic
691        assert!(lock_by_height1.is_same_unit(lock_by_height2));
692        assert!(!lock_by_height1.is_same_unit(lock_by_time1));
693        assert!(lock_by_time1.is_same_unit(lock_by_time2));
694        assert!(!lock_by_time1.is_same_unit(lock_by_height1));
695    }
696
697    #[test]
698    fn height_correctly_implies() {
699        let height = NumberOfBlocks::from(10);
700        let lock_by_height = LockTime::from(height);
701
702        assert!(!lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(9))));
703        assert!(lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(10))));
704        assert!(lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(11))));
705    }
706
707    #[test]
708    fn time_correctly_implies() {
709        let time = NumberOf512Seconds::from_512_second_intervals(70);
710        let lock_by_time = LockTime::from(time);
711
712        assert!(!lock_by_time
713            .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(69))));
714        assert!(lock_by_time
715            .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(70))));
716        assert!(lock_by_time
717            .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(71))));
718    }
719
720    #[test]
721    fn sequence_correctly_implies() {
722        let height = NumberOfBlocks::from(10);
723        let time = NumberOf512Seconds::from_512_second_intervals(70);
724
725        let lock_by_height = LockTime::from(height);
726        let lock_by_time = LockTime::from(time);
727
728        let seq_height = Sequence::from(lock_by_height);
729        let seq_time = Sequence::from(lock_by_time);
730
731        assert!(lock_by_height.is_implied_by_sequence(seq_height));
732        assert!(!lock_by_height.is_implied_by_sequence(seq_time));
733
734        assert!(lock_by_time.is_implied_by_sequence(seq_time));
735        assert!(!lock_by_time.is_implied_by_sequence(seq_height));
736
737        let disabled_sequence = Sequence::from_consensus(1 << 31);
738        assert!(!lock_by_height.is_implied_by_sequence(disabled_sequence));
739        assert!(!lock_by_time.is_implied_by_sequence(disabled_sequence));
740    }
741
742    #[test]
743    fn incorrect_units_do_not_imply() {
744        let time = NumberOf512Seconds::from_512_second_intervals(70);
745        let height = NumberOfBlocks::from(10);
746
747        let lock_by_time = LockTime::from(time);
748        assert!(!lock_by_time.is_implied_by(LockTime::from(height)));
749    }
750
751    #[test]
752    fn consensus_round_trip() {
753        assert!(LockTime::from_consensus(1 << 31).is_err());
754        assert!(LockTime::from_consensus(1 << 30).is_ok());
755        // Relative locktimes do not care about bits 17 through 21.
756        assert_eq!(LockTime::from_consensus(65536), LockTime::from_consensus(0));
757
758        for val in [0u32, 1, 1000, 65535] {
759            let seq = Sequence::from_consensus(val);
760            let lt = LockTime::from_consensus(val).unwrap();
761            assert_eq!(lt.to_consensus_u32(), val);
762            assert_eq!(lt.to_sequence(), seq);
763            assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq);
764
765            let seq = Sequence::from_consensus(val + (1 << 22));
766            let lt = LockTime::from_consensus(val + (1 << 22)).unwrap();
767            assert_eq!(lt.to_consensus_u32(), val + (1 << 22));
768            assert_eq!(lt.to_sequence(), seq);
769            assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq);
770        }
771    }
772
773    #[test]
774    #[cfg(feature = "alloc")]
775    fn disabled_locktime_error() {
776        let disabled_sequence = Sequence::from_consensus(1 << 31);
777        let err = LockTime::try_from(disabled_sequence).unwrap_err();
778
779        assert_eq!(err.disabled_locktime_value(), 1 << 31);
780        assert!(!format!("{}", err).is_empty());
781    }
782
783    #[test]
784    #[cfg(feature = "alloc")]
785    fn incompatible_height_error() {
786        // This is an error test these values are not used in the error path.
787        let mined_at = BlockHeight::from_u32(700_000);
788        let chain_tip = BlockHeight::from_u32(800_000);
789
790        let lock_by_time = LockTime::from_512_second_intervals(70); // Arbitrary value.
791        let err = lock_by_time.is_satisfied_by_height(chain_tip, mined_at).unwrap_err();
792
793        let expected_time = NumberOf512Seconds::from_512_second_intervals(70);
794        assert_eq!(
795            err,
796            IsSatisfiedByHeightError::Incompatible(IncompatibleHeightError(expected_time))
797        );
798        assert!(!format!("{}", err).is_empty());
799    }
800
801    #[test]
802    #[cfg(feature = "alloc")]
803    fn invalid_height_error() {
804        // If chain tip precedes mined_at, should return an invalid height error
805        let mined_at = BlockHeight::from_u32(900_000);
806        let chain_tip = BlockHeight::from_u32(800_000);
807
808        let block_count = NumberOfBlocks::from_height(70); // Arbitrary value.
809        let err = block_count.is_satisfied_by(chain_tip, mined_at).unwrap_err();
810
811        assert!(matches!(err, InvalidHeightError { chain_tip: _, utxo_mined_at: _ }));
812    }
813
814    #[test]
815    #[cfg(feature = "alloc")]
816    fn incompatible_time_error() {
817        // This is an error test these values are not used in the error path.
818        let mined_at = BlockMtp::from_u32(1_234_567_890);
819        let chain_tip = BlockMtp::from_u32(1_600_000_000);
820
821        let lock_by_height = LockTime::from_height(10); // Arbitrary value.
822        let err = lock_by_height.is_satisfied_by_time(chain_tip, mined_at).unwrap_err();
823
824        let expected_height = NumberOfBlocks::from(10);
825        assert_eq!(
826            err,
827            IsSatisfiedByTimeError::Incompatible(IncompatibleTimeError(expected_height))
828        );
829        assert!(!format!("{}", err).is_empty());
830    }
831
832    #[test]
833    #[cfg(feature = "alloc")]
834    fn invalid_time_error() {
835        // If chain tip precedes mined_at, should return an invalid time error
836        let mined_at = BlockMtp::from_u32(1_734_567_890);
837        let chain_tip = BlockMtp::from_u32(1_600_000_000);
838
839        let time_interval = NumberOf512Seconds::from_512_second_intervals(10); // Arbitrary value.
840        let err = time_interval.is_satisfied_by(chain_tip, mined_at).unwrap_err();
841
842        assert!(matches!(err, InvalidTimeError { chain_tip: _, utxo_mined_at: _ }));
843    }
844
845    #[test]
846    fn test_locktime_chain_state() {
847        fn generate_timestamps(start: u32, step: u16) -> [BlockTime; 11] {
848            let mut timestamps = [BlockTime::from_u32(0); 11];
849            for (i, ts) in timestamps.iter_mut().enumerate() {
850                *ts = BlockTime::from_u32(start.saturating_sub((step * i as u16).into()));
851            }
852            timestamps
853        }
854
855        let timestamps: [BlockTime; 11] = generate_timestamps(1_600_000_000, 200);
856        let utxo_timestamps: [BlockTime; 11] = generate_timestamps(1_599_000_000, 200);
857
858        let chain_height = BlockHeight::from_u32(100);
859        let chain_mtp = BlockMtp::new(timestamps);
860        let utxo_height = BlockHeight::from_u32(80);
861        let utxo_mtp = BlockMtp::new(utxo_timestamps);
862
863        let lock1 = LockTime::Blocks(NumberOfBlocks::from(10));
864        assert!(lock1.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
865
866        let lock2 = LockTime::Blocks(NumberOfBlocks::from(21));
867        assert!(lock2.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
868
869        let lock3 = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(10));
870        assert!(lock3.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
871
872        let lock4 = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(20000));
873        assert!(!lock4.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
874
875        assert!(LockTime::ZERO
876            .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
877            .unwrap());
878        assert!(LockTime::from_512_second_intervals(0)
879            .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
880            .unwrap());
881
882        let lock6 = LockTime::from_seconds_floor(5000).unwrap();
883        assert!(lock6.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
884
885        let max_height_lock = LockTime::Blocks(NumberOfBlocks::MAX);
886        assert!(!max_height_lock
887            .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
888            .unwrap());
889
890        let max_time_lock = LockTime::Time(NumberOf512Seconds::MAX);
891        assert!(!max_time_lock
892            .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
893            .unwrap());
894
895        let max_chain_height = BlockHeight::from_u32(u32::MAX);
896        let max_chain_mtp = BlockMtp::new(generate_timestamps(u32::MAX, 100));
897        let max_utxo_height = BlockHeight::MAX;
898        let max_utxo_mtp = max_chain_mtp;
899        assert!(!max_height_lock
900            .is_satisfied_by(max_chain_height, max_chain_mtp, max_utxo_height, max_utxo_mtp)
901            .unwrap());
902        assert!(!max_time_lock
903            .is_satisfied_by(max_chain_height, max_chain_mtp, max_utxo_height, max_utxo_mtp)
904            .unwrap());
905    }
906
907    #[test]
908    fn sanity_check() {
909        assert_eq!(LockTime::from(NumberOfBlocks::MAX).to_consensus_u32(), u32::from(u16::MAX));
910        assert_eq!(
911            NumberOf512Seconds::from_512_second_intervals(100).to_512_second_intervals(),
912            100u16
913        );
914        assert_eq!(
915            LockTime::from(NumberOf512Seconds::from_512_second_intervals(100)).to_consensus_u32(),
916            4_194_404u32
917        ); // 0x400064
918        assert_eq!(NumberOf512Seconds::from_512_second_intervals(1).to_seconds(), 512);
919    }
920
921    #[test]
922    fn from_512_second_intervals_roundtrip() {
923        let intervals = 100_u16;
924        let locktime = NumberOf512Seconds::from_512_second_intervals(intervals);
925        assert_eq!(locktime.to_512_second_intervals(), intervals);
926    }
927
928    #[test]
929    fn from_seconds_ceil_success() {
930        let actual = NumberOf512Seconds::from_seconds_ceil(100).unwrap();
931        let expected = NumberOf512Seconds(1_u16);
932        assert_eq!(actual, expected);
933    }
934
935    #[test]
936    fn from_seconds_ceil_with_maximum_encodable_seconds_success() {
937        let actual = NumberOf512Seconds::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS).unwrap();
938        let expected = NumberOf512Seconds(u16::MAX);
939        assert_eq!(actual, expected);
940    }
941
942    #[test]
943    fn from_seconds_ceil_causes_time_overflow_error() {
944        let result = NumberOf512Seconds::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS + 1);
945        assert!(result.is_err());
946    }
947
948    #[test]
949    fn from_seconds_floor_success() {
950        let actual = NumberOf512Seconds::from_seconds_floor(100).unwrap();
951        let expected = NumberOf512Seconds(0_u16);
952        assert_eq!(actual, expected);
953    }
954
955    #[test]
956    fn from_seconds_floor_with_exact_interval() {
957        let actual = NumberOf512Seconds::from_seconds_floor(512).unwrap();
958        let expected = NumberOf512Seconds(1_u16);
959        assert_eq!(actual, expected);
960    }
961
962    #[test]
963    fn from_seconds_floor_with_maximum_encodable_seconds_success() {
964        let actual =
965            NumberOf512Seconds::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 511).unwrap();
966        let expected = NumberOf512Seconds(u16::MAX);
967        assert_eq!(actual, expected);
968    }
969
970    #[test]
971    fn from_seconds_floor_causes_time_overflow_error() {
972        let result = NumberOf512Seconds::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 512);
973        assert!(result.is_err());
974    }
975
976    fn generate_timestamps(start: u32, step: u16) -> [BlockTime; 11] {
977        let mut timestamps = [BlockTime::from_u32(0); 11];
978        for (i, ts) in timestamps.iter_mut().enumerate() {
979            *ts = BlockTime::from_u32(start.saturating_sub((step * i as u16).into()));
980        }
981        timestamps
982    }
983
984    #[test]
985    fn test_time_chain_state() {
986        use crate::BlockMtp;
987
988        let timestamps: [BlockTime; 11] = generate_timestamps(1_600_000_000, 200);
989        let utxo_timestamps: [BlockTime; 11] = generate_timestamps(1_599_000_000, 200);
990
991        let timestamps2: [BlockTime; 11] = generate_timestamps(1_599_995_119, 200);
992        let utxo_timestamps2: [BlockTime; 11] = generate_timestamps(1_599_990_000, 200);
993
994        let timestamps3: [BlockTime; 11] = generate_timestamps(1_600_050_000, 200);
995        let utxo_timestamps3: [BlockTime; 11] = generate_timestamps(1_599_990_000, 200);
996
997        // Test case 1: Satisfaction (current_mtp >= utxo_mtp + required_seconds)
998        // 10 intervals × 512 seconds = 5120 seconds
999        let time_lock = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(10));
1000        let chain_state1 = BlockMtp::new(timestamps);
1001        let utxo_state1 = BlockMtp::new(utxo_timestamps);
1002        assert!(time_lock.is_satisfied_by_time(chain_state1, utxo_state1).unwrap());
1003
1004        // Test case 2: Not satisfied (current_mtp < utxo_mtp + required_seconds)
1005        let chain_state2 = BlockMtp::new(timestamps2);
1006        let utxo_state2 = BlockMtp::new(utxo_timestamps2);
1007        assert!(!time_lock.is_satisfied_by_time(chain_state2, utxo_state2).unwrap());
1008
1009        // Test case 3: Test with a larger value (100 intervals = 51200 seconds)
1010        let larger_lock = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(100));
1011        let chain_state3 = BlockMtp::new(timestamps3);
1012        let utxo_state3 = BlockMtp::new(utxo_timestamps3);
1013        assert!(larger_lock.is_satisfied_by_time(chain_state3, utxo_state3).unwrap());
1014
1015        // Test case 4: Overflow handling - tests that is_satisfied_by_time handles overflow gracefully
1016        let max_time_lock = LockTime::Time(NumberOf512Seconds::MAX);
1017        let chain_state4 = BlockMtp::new(timestamps);
1018        let utxo_state4 = BlockMtp::new(utxo_timestamps);
1019        assert!(!max_time_lock.is_satisfied_by_time(chain_state4, utxo_state4).unwrap());
1020    }
1021
1022    #[test]
1023    fn test_height_chain_state() {
1024        let height_lock = LockTime::Blocks(NumberOfBlocks(10));
1025
1026        // Test case 1: Satisfaction (current_height >= utxo_height + required)
1027        let chain_state1 = BlockHeight::from_u32(89);
1028        let utxo_state1 = BlockHeight::from_u32(80);
1029        assert!(height_lock.is_satisfied_by_height(chain_state1, utxo_state1).unwrap());
1030
1031        // Test case 2: Not satisfied (current_height < utxo_height + required)
1032        let chain_state2 = BlockHeight::from_u32(88);
1033        let utxo_state2 = BlockHeight::from_u32(80);
1034        assert!(!height_lock.is_satisfied_by_height(chain_state2, utxo_state2).unwrap());
1035
1036        // Test case 3: Overflow handling - tests that is_satisfied_by_height handles overflow gracefully
1037        let max_height_lock = LockTime::Blocks(NumberOfBlocks::MAX);
1038        let chain_state3 = BlockHeight::from_u32(1000);
1039        let utxo_state3 = BlockHeight::from_u32(80);
1040        assert!(!max_height_lock.is_satisfied_by_height(chain_state3, utxo_state3).unwrap());
1041    }
1042
1043    #[test]
1044    fn test_max_height_satisfaction() {
1045        // If the difference between these two is u32::MAX, we should get Ok(true)
1046        let mined_at = BlockHeight::from_u32(u32::MIN);
1047        let chain_tip = BlockHeight::from_u32(u32::MAX);
1048
1049        let block_height = NumberOfBlocks::from(10); // Arbitrary value.
1050        assert!(block_height.is_satisfied_by(chain_tip, mined_at).unwrap());
1051    }
1052}