Skip to main content

bitcoin_units/
sequence.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin transaction input sequence number.
4//!
5//! The sequence field is used for:
6//! - Indicating whether absolute lock-time (specified in `lock_time` field of `Transaction`) is enabled.
7//! - Indicating and encoding [BIP-0068] relative lock-times.
8//! - Indicating whether a transaction opts-in to [BIP-0125] replace-by-fee.
9//!
10//! Note that transactions spending an output with `OP_CHECKLOCKTIMEVERIFY` MUST NOT use
11//! `Sequence::MAX` for the corresponding input. [BIP-0065]
12//!
13//! [BIP-0065]: <https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki>
14//! [BIP-0068]: <https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki>
15//! [BIP-0125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>
16
17use core::fmt;
18
19#[cfg(feature = "arbitrary")]
20use arbitrary::{Arbitrary, Unstructured};
21#[cfg(feature = "serde")]
22use serde::{Deserialize, Serialize};
23
24use crate::locktime::relative::error::TimeOverflowError;
25use crate::locktime::relative::{self, NumberOf512Seconds};
26use crate::parse_int::{self, PrefixedHexError, UnprefixedHexError};
27
28#[rustfmt::skip]                // Keep public re-exports separate.
29#[cfg(feature = "encoding")]
30#[doc(no_inline)]
31pub use self::error::SequenceDecoderError;
32
33/// Bitcoin transaction input sequence number.
34#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
36pub struct Sequence(pub u32);
37
38impl Sequence {
39    /// The maximum allowable sequence number.
40    ///
41    /// The sequence number that disables replace-by-fee, absolute lock time and relative lock time.
42    pub const MAX: Self = Self(0xFFFF_FFFF);
43
44    /// Zero value sequence.
45    ///
46    /// This sequence number enables replace-by-fee and absolute lock time.
47    pub const ZERO: Self = Self(0);
48
49    /// The sequence number that disables replace-by-fee, absolute lock time and relative lock time.
50    pub const FINAL: Self = Self::MAX;
51
52    /// The sequence number that enables absolute lock time but disables replace-by-fee
53    /// and relative lock time.
54    pub const ENABLE_LOCKTIME_NO_RBF: Self = Self::MIN_NO_RBF;
55
56    /// The maximum sequence number that enables replace-by-fee and absolute lock time but
57    /// disables relative lock time.
58    ///
59    /// This sequence number has no meaning other than to enable RBF and the absolute locktime.
60    pub const ENABLE_LOCKTIME_AND_RBF: Self = Self(0xFFFF_FFFD);
61
62    /// The number of bytes that a sequence number contributes to the size of a transaction.
63    pub const SIZE: usize = 4; // Serialized length of a u32.
64
65    /// The lowest sequence number that does not opt-in for replace-by-fee.
66    ///
67    /// A transaction is considered to have opted in to replacement of itself
68    /// if any of its inputs have a `Sequence` number less than this value
69    /// (Explicit Signalling [BIP-0125]).
70    ///
71    /// [BIP-0125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>
72    const MIN_NO_RBF: Self = Self(0xFFFF_FFFE);
73
74    /// BIP-0068 relative lock time disable flag mask.
75    const LOCK_TIME_DISABLE_FLAG_MASK: u32 = 0x8000_0000;
76
77    /// BIP-0068 relative lock time type flag mask.
78    pub(super) const LOCK_TYPE_MASK: u32 = 0x0040_0000;
79
80    /// Returns `true` if the sequence number enables absolute lock-time (`Transaction::lock_time`).
81    #[inline]
82    pub fn enables_absolute_lock_time(self) -> bool { self != Self::MAX }
83
84    /// Returns `true` if the sequence number indicates that the transaction is finalized.
85    ///
86    /// Instead of this method please consider using `!enables_absolute_lock_time` because it
87    /// is equivalent and improves readability for those not steeped in Bitcoin folklore.
88    ///
89    /// # Historical note
90    ///
91    /// The term 'final' is an archaic Bitcoin term, it may have come about because the sequence
92    /// number in the original Bitcoin code was intended to be incremented in order to replace a
93    /// transaction, so once the sequence number got to `u32::MAX` it could no longer be increased,
94    /// hence it was 'final'.
95    ///
96    ///
97    /// Some other references to the term:
98    /// - `CTxIn::SEQUENCE_FINAL` in the Bitcoin Core code.
99    /// - [BIP-0112]: "BIP-0068 prevents a non-final transaction from being selected for inclusion in a
100    ///   block until the corresponding input has reached the specified age"
101    ///
102    /// [BIP-0112]: <https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki>
103    #[inline]
104    pub fn is_final(self) -> bool { !self.enables_absolute_lock_time() }
105
106    /// Returns true if the transaction opted-in to BIP-0125 replace-by-fee.
107    ///
108    /// Replace by fee is signaled by the sequence being less than 0xfffffffe which is checked by
109    /// this method. Note, this is the highest "non-final" value (see [`Sequence::is_final`]).
110    #[inline]
111    pub fn is_rbf(self) -> bool { self < Self::MIN_NO_RBF }
112
113    /// Returns `true` if the sequence has a relative lock-time.
114    #[inline]
115    pub fn is_relative_lock_time(self) -> bool { self.0 & Self::LOCK_TIME_DISABLE_FLAG_MASK == 0 }
116
117    /// Returns `true` if the sequence number encodes a block based relative lock-time.
118    #[inline]
119    pub fn is_height_locked(self) -> bool {
120        self.is_relative_lock_time() && (self.0 & Self::LOCK_TYPE_MASK == 0)
121    }
122
123    /// Returns `true` if the sequence number encodes a time interval based relative lock-time.
124    #[inline]
125    pub fn is_time_locked(self) -> bool {
126        self.is_relative_lock_time() && (self.0 & Self::LOCK_TYPE_MASK > 0)
127    }
128
129    /// Constructs a new `Sequence` from a prefixed hex string.
130    ///
131    /// # Errors
132    ///
133    /// If the input string is not a valid hex representation of a locktime or it does not include
134    /// the `0x` prefix.
135    #[inline]
136    pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
137        let lock_time = parse_int::hex_u32_prefixed(s)?;
138        Ok(Self::from_consensus(lock_time))
139    }
140
141    /// Constructs a new `Sequence` from an unprefixed hex string.
142    ///
143    /// # Errors
144    ///
145    /// If the input string is not a valid hex representation of a locktime or if it includes the
146    /// `0x` prefix.
147    #[inline]
148    pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
149        let lock_time = parse_int::hex_u32_unprefixed(s)?;
150        Ok(Self::from_consensus(lock_time))
151    }
152
153    /// Constructs a new relative lock-time using block height.
154    #[inline]
155    pub fn from_height(height: u16) -> Self { Self(u32::from(height)) }
156
157    /// Constructs a new relative lock-time using time intervals where each interval is equivalent
158    /// to 512 seconds.
159    ///
160    /// Encoding finer granularity of time for relative lock-times is not supported in Bitcoin
161    #[inline]
162    pub fn from_512_second_intervals(intervals: u16) -> Self {
163        Self(u32::from(intervals) | Self::LOCK_TYPE_MASK)
164    }
165
166    /// Constructs a new relative lock-time from seconds, converting the seconds into 512 second
167    /// interval with floor division.
168    ///
169    /// Will return an error if the input cannot be encoded in 16 bits.
170    ///
171    /// # Errors
172    ///
173    /// Will return an error if `seconds` cannot be encoded in 16 bits. See
174    /// [`NumberOf512Seconds::from_seconds_floor`].
175    #[inline]
176    pub fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
177        let intervals = NumberOf512Seconds::from_seconds_floor(seconds)?;
178        Ok(Self::from_512_second_intervals(intervals.to_512_second_intervals()))
179    }
180
181    /// Constructs a new relative lock-time from seconds, converting the seconds into 512 second
182    /// interval with ceiling division.
183    ///
184    /// Will return an error if the input cannot be encoded in 16 bits.
185    ///
186    /// # Errors
187    ///
188    /// Will return an error if `seconds` cannot be encoded in 16 bits. See
189    /// [`NumberOf512Seconds::from_seconds_ceil`].
190    #[inline]
191    pub fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
192        let intervals = NumberOf512Seconds::from_seconds_ceil(seconds)?;
193        Ok(Self::from_512_second_intervals(intervals.to_512_second_intervals()))
194    }
195
196    /// Constructs a new sequence from a u32 value.
197    #[inline]
198    pub fn from_consensus(n: u32) -> Self { Self(n) }
199
200    /// Returns the inner 32bit integer value of Sequence.
201    #[inline]
202    pub const fn to_consensus_u32(self) -> u32 { self.0 }
203
204    /// Constructs a new [`relative::LockTime`] from this [`Sequence`] number.
205    #[inline]
206    pub fn to_relative_lock_time(self) -> Option<relative::LockTime> {
207        use crate::locktime::relative::{LockTime, NumberOfBlocks};
208
209        if !self.is_relative_lock_time() {
210            return None;
211        }
212
213        let lock_value = self.low_u16();
214
215        if self.is_time_locked() {
216            Some(LockTime::from(NumberOf512Seconds::from_512_second_intervals(lock_value)))
217        } else {
218            Some(LockTime::from(NumberOfBlocks::from(lock_value)))
219        }
220    }
221
222    /// Returns the low 16 bits from sequence number.
223    ///
224    /// BIP-0068 only uses the low 16 bits for relative lock value.
225    #[inline]
226    const fn low_u16(self) -> u16 { self.0 as u16 }
227}
228
229crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(Sequence);
230
231impl Default for Sequence {
232    /// The default value of sequence is 0xffffffff.
233    #[inline]
234    fn default() -> Self { Self::MAX }
235}
236
237impl From<Sequence> for u32 {
238    #[inline]
239    fn from(sequence: Sequence) -> Self { sequence.0 }
240}
241
242impl fmt::Display for Sequence {
243    #[inline]
244    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
245}
246
247impl fmt::Debug for Sequence {
248    #[inline]
249    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250        // 10 because its 8 digits + 2 for the '0x'
251        write!(f, "Sequence({:#010x})", self.0)
252    }
253}
254
255parse_int::impl_parse_str_from_int_infallible!(Sequence, u32, from_consensus);
256
257#[cfg(feature = "encoding")]
258impl encoding::Encode for Sequence {
259    type Encoder<'e> = SequenceEncoder<'e>;
260    #[inline]
261    fn encoder(&self) -> Self::Encoder<'_> {
262        SequenceEncoder::new(encoding::ArrayEncoder::without_length_prefix(
263            self.to_consensus_u32().to_le_bytes(),
264        ))
265    }
266}
267
268#[cfg(feature = "encoding")]
269impl encoding::Decode for Sequence {
270    type Decoder = SequenceDecoder;
271}
272
273#[cfg(feature = "encoding")]
274encoding::encoder_newtype_exact! {
275    /// The encoder for the [`Sequence`] type.
276    #[derive(Debug, Clone)]
277    pub struct SequenceEncoder<'e>(encoding::ArrayEncoder<4>);
278}
279
280#[cfg(feature = "encoding")]
281crate::decoder_newtype! {
282    /// The decoder for the [`Sequence`] type.
283    #[derive(Debug, Clone)]
284    pub struct SequenceDecoder(encoding::ArrayDecoder<4>);
285
286    /// Constructs a new [`Sequence`] decoder.
287    pub const fn new() -> Self { Self(encoding::ArrayDecoder::new()) }
288
289    fn end(result: Result<[u8; 4], encoding::UnexpectedEofError>) -> Result<Sequence, SequenceDecoderError> {
290        let value = result.map_err(SequenceDecoderError)?;
291        let n = u32::from_le_bytes(value);
292        Ok(Sequence::from_consensus(n))
293    }
294}
295
296/// Error types for input sequence numbers.
297pub mod error {
298    #[cfg(feature = "encoding")]
299    use core::convert::Infallible;
300    #[cfg(feature = "encoding")]
301    use core::fmt;
302
303    #[cfg(feature = "encoding")]
304    use internals::write_err;
305
306    /// An error consensus decoding an `Sequence`.
307    #[cfg(feature = "encoding")]
308    #[derive(Debug, Clone, PartialEq, Eq)]
309    pub struct SequenceDecoderError(pub(super) encoding::UnexpectedEofError);
310
311    #[cfg(feature = "encoding")]
312    impl From<Infallible> for SequenceDecoderError {
313        fn from(never: Infallible) -> Self { match never {} }
314    }
315
316    #[cfg(feature = "encoding")]
317    impl fmt::Display for SequenceDecoderError {
318        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
319            write_err!(f, "sequence decoder error"; self.0)
320        }
321    }
322
323    #[cfg(feature = "encoding")]
324    #[cfg(feature = "std")]
325    impl std::error::Error for SequenceDecoderError {
326        #[inline]
327        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
328    }
329}
330
331#[cfg(feature = "arbitrary")]
332#[cfg(feature = "alloc")]
333impl<'a> Arbitrary<'a> for Sequence {
334    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
335        // Equally weight the cases of meaningful sequence numbers
336        let choice = u.int_in_range(0..=8)?;
337        match choice {
338            0 => Ok(Self::MAX),
339            1 => Ok(Self::ZERO),
340            2 => Ok(Self::MIN_NO_RBF),
341            3 => Ok(Self::ENABLE_LOCKTIME_AND_RBF),
342            4 => Ok(Self::from_consensus(u32::from(relative::NumberOfBlocks::MIN.to_height()))),
343            5 => Ok(Self::from_consensus(u32::from(relative::NumberOfBlocks::MAX.to_height()))),
344            6 => Ok(Self::from_consensus(
345                Self::LOCK_TYPE_MASK
346                    | u32::from(relative::NumberOf512Seconds::MIN.to_512_second_intervals()),
347            )),
348            7 => Ok(Self::from_consensus(
349                Self::LOCK_TYPE_MASK
350                    | u32::from(relative::NumberOf512Seconds::MAX.to_512_second_intervals()),
351            )),
352            _ => Ok(Self(u.arbitrary()?)),
353        }
354    }
355}
356
357#[cfg(feature = "arbitrary")]
358#[cfg(not(feature = "alloc"))]
359impl<'a> Arbitrary<'a> for Sequence {
360    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
361        // Equally weight the cases of meaningful sequence numbers
362        let choice = u.int_in_range(0..=4)?;
363        match choice {
364            0 => Ok(Sequence::MAX),
365            1 => Ok(Sequence::ZERO),
366            2 => Ok(Sequence::MIN_NO_RBF),
367            3 => Ok(Sequence::ENABLE_LOCKTIME_AND_RBF),
368            _ => Ok(Sequence(u.arbitrary()?)),
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    #[cfg(feature = "alloc")]
376    use alloc::format;
377    #[cfg(feature = "alloc")]
378    #[cfg(feature = "encoding")]
379    use alloc::string::ToString;
380    #[cfg(feature = "encoding")]
381    #[cfg(feature = "std")]
382    use std::error::Error;
383
384    #[cfg(feature = "alloc")]
385    #[cfg(feature = "encoding")]
386    use encoding::UnexpectedEofError;
387    #[cfg(feature = "encoding")]
388    use encoding::{Decode as _, Decoder as _};
389
390    use super::*;
391
392    const MAXIMUM_ENCODABLE_SECONDS: u32 = u16::MAX as u32 * 512;
393
394    #[test]
395    fn from_seconds_floor_success() {
396        let expected = Sequence::from_hex("0x0040ffff").unwrap();
397        let actual = Sequence::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 511).unwrap();
398        assert_eq!(actual, expected);
399    }
400
401    #[test]
402    fn from_seconds_floor_causes_overflow_error() {
403        assert!(Sequence::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 512).is_err());
404    }
405
406    #[test]
407    fn from_seconds_ceil_success() {
408        let expected = Sequence::from_hex("0x0040ffff").unwrap();
409        let actual = Sequence::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS - 511).unwrap();
410        assert_eq!(actual, expected);
411    }
412
413    #[test]
414    fn from_seconds_ceil_causes_overflow_error() {
415        assert!(Sequence::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS + 1).is_err());
416    }
417
418    #[test]
419    fn sequence_number() {
420        let seq_final = Sequence::from_consensus(0xFFFF_FFFF);
421        let seq_non_rbf = Sequence::from_consensus(0xFFFF_FFFE);
422        let block_time_lock = Sequence::from_consensus(0xFFFF);
423        let unit_time_lock = Sequence::from_consensus(0x40_FFFF);
424        let lock_time_disabled = Sequence::from_consensus(0x8000_0000);
425
426        assert!(seq_final.is_final());
427        assert!(!seq_final.is_rbf());
428        assert!(!seq_final.is_relative_lock_time());
429        assert!(!seq_non_rbf.is_rbf());
430        assert!(block_time_lock.is_relative_lock_time());
431        assert!(block_time_lock.is_height_locked());
432        assert!(block_time_lock.is_rbf());
433        assert!(unit_time_lock.is_relative_lock_time());
434        assert!(unit_time_lock.is_time_locked());
435        assert!(unit_time_lock.is_rbf());
436        assert!(!lock_time_disabled.is_relative_lock_time());
437    }
438
439    #[test]
440    fn sequence_from_hex_lower() {
441        let sequence = Sequence::from_hex("0xffffffff").unwrap();
442        assert_eq!(sequence, Sequence::MAX);
443    }
444
445    #[test]
446    fn sequence_from_hex_upper() {
447        let sequence = Sequence::from_hex("0XFFFFFFFF").unwrap();
448        assert_eq!(sequence, Sequence::MAX);
449    }
450
451    #[test]
452    fn sequence_from_unprefixed_hex_lower() {
453        let sequence = Sequence::from_unprefixed_hex("ffffffff").unwrap();
454        assert_eq!(sequence, Sequence::MAX);
455    }
456
457    #[test]
458    fn sequence_from_unprefixed_hex_upper() {
459        let sequence = Sequence::from_unprefixed_hex("FFFFFFFF").unwrap();
460        assert_eq!(sequence, Sequence::MAX);
461    }
462
463    #[test]
464    fn sequence_from_str_hex_invalid_hex_should_err() {
465        let hex = "0xzb93";
466        let result = Sequence::from_hex(hex);
467        assert!(result.is_err());
468    }
469
470    #[test]
471    fn sequence_properties() {
472        let seq_max = Sequence(0xFFFF_FFFF);
473        let seq_no_rbf = Sequence(0xFFFF_FFFE);
474        let seq_rbf = Sequence(0xFFFF_FFFD);
475
476        assert!(seq_max.is_final());
477        assert!(!seq_no_rbf.is_final());
478
479        assert!(seq_no_rbf.enables_absolute_lock_time());
480        assert!(!seq_max.enables_absolute_lock_time());
481
482        assert!(seq_rbf.is_rbf());
483        assert!(!seq_no_rbf.is_rbf());
484
485        let seq_relative = Sequence(0x7FFF_FFFF);
486        assert!(seq_relative.is_relative_lock_time());
487        assert!(!seq_max.is_relative_lock_time());
488
489        let seq_height_locked = Sequence(0x0039_9999);
490        let seq_time_locked = Sequence(0x0040_0000);
491        assert!(seq_height_locked.is_height_locked());
492        assert!(seq_time_locked.is_time_locked());
493        assert!(!seq_time_locked.is_height_locked());
494        assert!(!seq_height_locked.is_time_locked());
495    }
496
497    #[test]
498    #[cfg(feature = "alloc")]
499    fn sequence_formatting() {
500        let sequence = Sequence(0x7FFF_FFFF);
501        assert_eq!(format!("{:x}", sequence), "7fffffff");
502        assert_eq!(format!("{:X}", sequence), "7FFFFFFF");
503
504        // Test From<Sequence> for u32
505        let sequence_u32: u32 = sequence.into();
506        assert_eq!(sequence_u32, 0x7FFF_FFFF);
507    }
508
509    #[test]
510    #[cfg(feature = "alloc")]
511    fn sequence_display() {
512        use alloc::string::ToString;
513
514        let sequence = Sequence(0x7FFF_FFFF);
515        let want: u32 = 0x7FFF_FFFF;
516        assert_eq!(format!("{}", sequence), want.to_string());
517    }
518
519    #[test]
520    #[cfg(feature = "alloc")]
521    fn sequence_unprefixed_hex_roundtrip() {
522        let sequence = Sequence(0x7FFF_FFFF);
523
524        let hex_str = format!("{:x}", sequence);
525        assert_eq!(hex_str, "7fffffff");
526
527        let roundtrip = Sequence::from_unprefixed_hex(&hex_str).unwrap();
528        assert_eq!(sequence, roundtrip);
529    }
530
531    #[test]
532    fn sequence_from_height() {
533        // Check near the boundaries
534        assert_eq!(Sequence::from_height(0), Sequence(0));
535        assert_eq!(Sequence::from_height(1), Sequence(1));
536        assert_eq!(Sequence::from_height(0x7FFF), Sequence(0x7FFF));
537        assert_eq!(Sequence::from_height(0xFFFF), Sequence(0xFFFF));
538
539        // Check steps throughout the whole range
540        let step = 512;
541        for v in (0..=u16::MAX).step_by(step) {
542            assert_eq!(Sequence::from_height(v), Sequence(v.into()));
543        }
544    }
545
546    #[test]
547    #[cfg(feature = "alloc")]
548    #[cfg(feature = "encoding")]
549    fn sequence_decoding_error() {
550        let bytes = [0xff, 0xff, 0xff]; // 3 bytes is an EOF error
551
552        let mut decoder = SequenceDecoder::default();
553        assert!(decoder.push_bytes(&mut bytes.as_slice()).unwrap().needs_more());
554
555        let error = decoder.end().unwrap_err();
556        assert!(matches!(error, SequenceDecoderError(UnexpectedEofError { .. })));
557    }
558
559    #[test]
560    #[cfg(feature = "alloc")]
561    fn decoder_error_display_is_non_empty() {
562        #[cfg(feature = "encoding")]
563        {
564            // SequenceDecoderError
565            let mut decoder = Sequence::decoder();
566            let _ = decoder.push_bytes(&mut [0u8; 3].as_slice());
567            let e = decoder.end().unwrap_err();
568            assert!(!e.to_string().is_empty());
569            #[cfg(feature = "std")]
570            assert!(e.source().is_some());
571        }
572    }
573}