From 0ed26915f6d1000f1fd48214a5da639306b13edf Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Thu, 7 Mar 2024 17:22:13 +0000 Subject: [PATCH] relative locktime: add conversions to/from sequence --- bitcoin/src/blockdata/locktime/relative.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/bitcoin/src/blockdata/locktime/relative.rs b/bitcoin/src/blockdata/locktime/relative.rs index f8e9f7b7..0c047ab0 100644 --- a/bitcoin/src/blockdata/locktime/relative.rs +++ b/bitcoin/src/blockdata/locktime/relative.rs @@ -13,6 +13,7 @@ use mutagen::mutate; #[cfg(doc)] use crate::relative; +use crate::Sequence; #[rustfmt::skip] // Keep public re-exports separate. #[doc(inline)] @@ -86,6 +87,19 @@ impl LockTime { } } + /// Constructs a `LockTime` from the sequence number of a Bitcoin input. + /// + /// This method will **not** round-trip with [`Self::to_sequence`]. See the + /// docs for [`Self::from_consensus`] for more information. + #[inline] + pub fn from_sequence(n: Sequence) -> Result { + Self::from_consensus(n.to_consensus_u32()) + } + + /// Encodes the locktime as a sequence number. + #[inline] + pub fn to_sequence(&self) -> Sequence { Sequence::from_consensus(self.to_consensus_u32()) } + /// Constructs a `LockTime` from `n`, expecting `n` to be a 16-bit count of blocks. #[inline] pub const fn from_height(n: u16) -> Self { LockTime::Blocks(Height::from_height(n)) } @@ -426,11 +440,17 @@ mod tests { assert_eq!(LockTime::from_consensus(65536), LockTime::from_consensus(0)); for val in [0u32, 1, 1000, 65535] { + let seq = Sequence::from_consensus(val); let lt = LockTime::from_consensus(val).unwrap(); assert_eq!(lt.to_consensus_u32(), val); + assert_eq!(lt.to_sequence(), seq); + assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq); + let seq = Sequence::from_consensus(val + (1 << 22)); let lt = LockTime::from_consensus(val + (1 << 22)).unwrap(); assert_eq!(lt.to_consensus_u32(), val + (1 << 22)); + assert_eq!(lt.to_sequence(), seq); + assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq); } } }