Merge rust-bitcoin/rust-bitcoin#3968: Add `LockTime` examples

c16eab7723 Add examples to `absolute::LockTime` (Jamil Lambert, PhD)
2d73746ad1 Improve `from_consensus` example (Jamil Lambert, PhD)
25a6742573 Add examples to `relative::LockTime` (Jamil Lambert, PhD)

Pull request description:

  To conform to API guidelines add examples to both `relative` and `absolute` `LockTime`.

  As discussed in #3967 add an example that doesn't round trip in `relative::LockTime::from_consensus`.

ACKs for top commit:
  tcharding:
    ACK c16eab7723
  apoelstra:
    ACK c16eab772375a0b8f82789a3453f7e983523fd50; successfully ran local tests

Tree-SHA512: 898db2dbcccfc54971c65bb72030505dbcfffb035aa74eb376cc1eb8d3619c205338899a58fb9f267fca192c11e7ae48fc17a2d9019c5ff4bd34bf029fa9a48f
This commit is contained in:
merge-script 2025-01-31 23:37:40 +00:00
commit bc1e3c0bfc
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
2 changed files with 79 additions and 4 deletions

View File

@ -91,12 +91,34 @@ impl LockTime {
pub const SIZE: usize = 4; // Serialized length of a u32. pub const SIZE: usize = 4; // Serialized length of a u32.
/// Constructs a new `LockTime` from a prefixed hex string. /// Constructs a new `LockTime` from a prefixed hex string.
///
/// # Examples
///
/// ```
/// # use bitcoin_primitives::absolute::LockTime;
/// let hex_str = "0x61cf9980"; // Unix timestamp for January 1, 2022
/// let lock_time = LockTime::from_hex(hex_str)?;
/// assert_eq!(lock_time.to_consensus_u32(), 0x61cf9980);
///
/// # Ok::<_, units::parse::PrefixedHexError>(())
/// ```
pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> { pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
let lock_time = parse::hex_u32_prefixed(s)?; let lock_time = parse::hex_u32_prefixed(s)?;
Ok(Self::from_consensus(lock_time)) Ok(Self::from_consensus(lock_time))
} }
/// Constructs a new `LockTime` from an unprefixed hex string. /// Constructs a new `LockTime` from an unprefixed hex string.
///
/// # Examples
///
/// ```
/// # use bitcoin_primitives::absolute::LockTime;
/// let hex_str = "61cf9980"; // Unix timestamp for January 1, 2022
/// let lock_time = LockTime::from_unprefixed_hex(hex_str)?;
/// assert_eq!(lock_time.to_consensus_u32(), 0x61cf9980);
///
/// # Ok::<_, units::parse::UnprefixedHexError>(())
/// ```
pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> { pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
let lock_time = parse::hex_u32_unprefixed(s)?; let lock_time = parse::hex_u32_unprefixed(s)?;
Ok(Self::from_consensus(lock_time)) Ok(Self::from_consensus(lock_time))

View File

@ -32,6 +32,23 @@ pub use units::locktime::relative::{Height, Time, TimeOverflowError};
/// ///
/// * [BIP 68 Relative lock-time using consensus-enforced sequence numbers](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki) /// * [BIP 68 Relative lock-time using consensus-enforced sequence numbers](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki)
/// * [BIP 112 CHECKSEQUENCEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki) /// * [BIP 112 CHECKSEQUENCEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki)
///
/// # Examples
///
/// ```
/// use bitcoin_primitives::relative::{LockTime, Height, Time};
/// let lock_by_height = LockTime::from_height(144); // 144 blocks, approx 24h.
/// assert!(lock_by_height.is_block_height());
///
/// let lock_by_time = LockTime::from_512_second_intervals(168); // 168 time intervals, approx 24h.
/// assert!(lock_by_time.is_block_time());
///
/// // Check if a lock time is satisfied by a given height or time.
/// let height = Height::from(150);
/// let time = Time::from_512_second_intervals(200);
/// assert!(lock_by_height.is_satisfied_by(height, time));
/// assert!(lock_by_time.is_satisfied_by(height, time));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LockTime { pub enum LockTime {
@ -60,10 +77,19 @@ impl LockTime {
/// ```rust /// ```rust
/// # use bitcoin_primitives::relative::LockTime; /// # use bitcoin_primitives::relative::LockTime;
/// ///
/// // `from_consensus` roundtrips with `to_consensus_u32` for small values. /// // Values with bit 22 set to 0 will be interpreted as height-based lock times.
/// let n_lock_time: u32 = 7000; /// let height: u32 = 144; // 144 blocks, approx 24h.
/// let lock_time = LockTime::from_consensus(n_lock_time).unwrap(); /// let lock_time = LockTime::from_consensus(height)?;
/// assert_eq!(lock_time.to_consensus_u32(), n_lock_time); /// assert!(lock_time.is_block_height());
/// assert_eq!(lock_time.to_consensus_u32(), height);
///
/// // Values with bit 22 set to 1 will be interpreted as time-based lock times.
/// let time: u32 = 168 | (1 << 22) ; // Bit 22 is 1 with time approx 24h.
/// let lock_time = LockTime::from_consensus(time)?;
/// assert!(lock_time.is_block_time());
/// assert_eq!(lock_time.to_consensus_u32(), time);
///
/// # Ok::<_, bitcoin_primitives::relative::DisabledLockTimeError>(())
/// ``` /// ```
pub fn from_consensus(n: u32) -> Result<Self, DisabledLockTimeError> { pub fn from_consensus(n: u32) -> Result<Self, DisabledLockTimeError> {
let sequence = crate::Sequence::from_consensus(n); let sequence = crate::Sequence::from_consensus(n);
@ -89,6 +115,18 @@ impl LockTime {
/// ///
/// This method will **not** round-trip with [`Self::to_sequence`]. See the /// This method will **not** round-trip with [`Self::to_sequence`]. See the
/// docs for [`Self::from_consensus`] for more information. /// docs for [`Self::from_consensus`] for more information.
/// # Examples
///
/// ```rust
/// # use bitcoin_primitives::{Sequence, relative::LockTime};
///
/// // Interpret a sequence number from a Bitcoin transaction input as a relative lock time
/// let sequence_number = Sequence::from_consensus(144); // 144 blocks, approx 24h.
/// let lock_time = LockTime::from_sequence(sequence_number)?;
/// assert!(lock_time.is_block_height());
///
/// # Ok::<_, bitcoin_primitives::relative::DisabledLockTimeError>(())
/// ```
#[inline] #[inline]
pub fn from_sequence(n: Sequence) -> Result<Self, DisabledLockTimeError> { pub fn from_sequence(n: Sequence) -> Result<Self, DisabledLockTimeError> {
Self::from_consensus(n.to_consensus_u32()) Self::from_consensus(n.to_consensus_u32())
@ -227,6 +265,21 @@ impl LockTime {
/// When deciding whether an instance of `<n> CHECKSEQUENCEVERIFY` will pass, this /// When deciding whether an instance of `<n> CHECKSEQUENCEVERIFY` will pass, this
/// method can be used by parsing `n` as a [`LockTime`] and calling this method /// method can be used by parsing `n` as a [`LockTime`] and calling this method
/// with the sequence number of the input which spends the script. /// with the sequence number of the input which spends the script.
///
/// # Examples
///
/// ```
/// # use bitcoin_primitives::{Sequence, relative::LockTime};
///
/// let sequence = Sequence::from_consensus(1 << 22 | 168); // Bit 22 is 1 with time approx 24h.
/// let lock_time = LockTime::from_sequence(sequence)?;
/// let input_sequence = Sequence::from_consensus(1 << 22 | 336); // Approx 48h.
/// assert!(lock_time.is_block_time());
///
/// assert!(lock_time.is_implied_by_sequence(input_sequence));
///
/// # Ok::<_, bitcoin_primitives::relative::DisabledLockTimeError>(())
/// ```
#[inline] #[inline]
pub fn is_implied_by_sequence(&self, other: Sequence) -> bool { pub fn is_implied_by_sequence(&self, other: Sequence) -> bool {
if let Ok(other) = LockTime::from_sequence(other) { if let Ok(other) = LockTime::from_sequence(other) {