Skip to main content

LockTime

Enum LockTime 

Source
pub enum LockTime {
    Blocks(Height),
    Seconds(MedianTimePast),
}
Expand description

An absolute lock time value, representing either a block height or a UNIX timestamp (seconds since epoch).

Used for transaction lock time (nLockTime in Bitcoin Core and Transaction::lock_time in rust-bitcoin) and also for the argument to opcode OP_CHECKLOCKTIMEVERIFY.

§Note on ordering

Locktimes may be height- or time-based, and these metrics are incommensurate; there is no total ordering on locktimes. In order to compare locktimes, instead of using < or > we provide the LockTime::is_satisfied_by API.

For transaction, which has a locktime field, we implement a total ordering to make it easy to store transactions in sorted data structures, and use the locktime’s 32-bit integer consensus encoding to order it.

§Relevant BIPs

§Examples

use bitcoin_units::absolute::{self, LockTime as L};
// To compare absolute lock times there are various `is_satisfied_*` methods, you may also use:
let _is_satisfied = match (n, lock_time) {
    (L::Blocks(n), L::Blocks(lock_time)) => n <= lock_time,
    (L::Seconds(n), L::Seconds(lock_time)) => n <= lock_time,
    _ => panic!("handle invalid comparison error"),
};

Variants§

§

Blocks(Height)

A block height lock time value.

§Examples

use bitcoin_units::absolute;

let block: u32 = 741521;
let n = absolute::LockTime::from_height(block).expect("valid height");
assert!(n.is_block_height());
assert_eq!(n.to_consensus_u32(), block);
§

Seconds(MedianTimePast)

A UNIX timestamp lock time value.

§Examples

use bitcoin_units::absolute;

let seconds: u32 = 1653195600; // May 22nd, 5am UTC.
let n = absolute::LockTime::from_mtp(seconds).expect("valid time");
assert!(n.is_block_time());
assert_eq!(n.to_consensus_u32(), seconds);

Implementations§

Source§

impl LockTime

Source

pub const ZERO: Self

If transaction lock time is set to zero it is ignored, in other words a transaction with nLocktime==0 is able to be included immediately in any block.

Source

pub const SIZE: usize = 4

The number of bytes that the locktime contributes to the size of a transaction.

Source

pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError>

Constructs a new LockTime from a prefixed hex string.

§Errors

If the input string is not a valid hex representation of a locktime or it does not include the 0x prefix.

§Examples
let hex_str = "0x61cf9980"; // Unix timestamp for January 1, 2022
let lock_time = absolute::LockTime::from_hex(hex_str)?;
assert_eq!(lock_time.to_consensus_u32(), 0x61cf9980);
Source

pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError>

Constructs a new LockTime from an unprefixed hex string.

§Errors

If the input string is not a valid hex representation of a locktime or if it includes the 0x prefix.

§Examples
let hex_str = "61cf9980"; // Unix timestamp for January 1, 2022
let lock_time = absolute::LockTime::from_unprefixed_hex(hex_str)?;
assert_eq!(lock_time.to_consensus_u32(), 0x61cf9980);
Source

pub fn from_consensus(n: u32) -> Self

Constructs a new LockTime from an nLockTime value or the argument to OP_CHECKLOCKTIMEVERIFY.

§Examples

// `from_consensus` roundtrips as expected with `to_consensus_u32`.
let n_lock_time: u32 = 741521;
let lock_time = absolute::LockTime::from_consensus(n_lock_time);
assert_eq!(lock_time.to_consensus_u32(), n_lock_time);
Source

pub fn from_height(n: u32) -> Result<Self, ConversionError>

Constructs a new LockTime from n, expecting n to be a valid block height.

§Note

If the current block height is h and the locktime is set to h, the transaction can be included in block h+1 or later. It is possible to broadcast the transaction at block height h.

See LOCK_TIME_THRESHOLD for definition of a valid height value.

§Errors

If n does not represent a block height within the valid range for a locktime: [0, 499_999_999].

§Examples
assert!(absolute::LockTime::from_height(741521).is_ok());
assert!(absolute::LockTime::from_height(1653195600).is_err());
Source

pub fn from_mtp(n: u32) -> Result<Self, ConversionError>

Constructs a new LockTime from n, expecting n to be a median-time-past (MTP) which is in range for a locktime.

§Note

If the locktime is set to an MTP T, the transaction can be included in a block only if the MTP of last recent 11 blocks is greater than T.

It is possible to broadcast the transaction once the MTP is greater than T. See BIP-0113.

BIP-0113 Median time-past as endpoint for lock-time calculations

See LOCK_TIME_THRESHOLD for definition of a valid time value.

§Errors

If n is not in the allowable range of MTPs in a locktime: [500_000_000, 2^32 - 1].

§Examples
assert!(absolute::LockTime::from_mtp(1653195600).is_ok());
assert!(absolute::LockTime::from_mtp(741521).is_err());
Source

pub const fn is_same_unit(self, other: Self) -> bool

Returns true if both lock times use the same unit i.e., both height based or both time based.

Source

pub const fn is_block_height(self) -> bool

Returns true if this lock time value is a block height.

Source

pub const fn is_block_time(self) -> bool

Returns true if this lock time value is a block time (UNIX timestamp).

Source

pub fn is_satisfied_by(self, height: Height, mtp: MedianTimePast) -> bool

Returns true if this timelock constraint is satisfied by the respective height/time.

If self is a blockheight based lock then it is checked against height and if self is a blocktime based lock it is checked against time.

A ‘timelock constraint’ refers to the n from n OP_CHECKLOCKTIMEVERIFY, this constraint is satisfied if a transaction with nLockTime set to height/time is valid.

If height and mtp represent the current chain tip then a transaction with this locktime can be broadcast for inclusion in the next block.

If you do not have, or do not wish to calculate, both parameters consider using:

§Examples
// Can be implemented if block chain data is available.
fn get_height() -> absolute::Height { todo!("return the current block height") }
fn get_time() -> absolute::MedianTimePast { todo!("return the current block MTP") }

let n = absolute::LockTime::from_consensus(741521); // `n OP_CHECKLOCKTIMEVERIFY`.
if n.is_satisfied_by(get_height(), get_time()) {
    // Can create and mine a transaction that satisfies the OP_CLTV timelock constraint.
}
Source

pub fn is_satisfied_by_height( self, height: Height, ) -> Result<bool, IncompatibleHeightError>

Returns true if a transaction with this locktime can be spent in the next block.

If height is the current block height of the chain then a transaction with this locktime can be broadcast for inclusion in the next block.

§Errors

Returns an error if this lock is not lock-by-height.

Source

pub fn is_satisfied_by_time( self, mtp: MedianTimePast, ) -> Result<bool, IncompatibleTimeError>

Returns true if a transaction with this locktime can be included in the next block.

§Errors

Returns an error if this lock is not lock-by-time.

Source

pub fn is_implied_by(self, other: Self) -> bool

Returns true if satisfaction of other lock time implies satisfaction of this absolute::LockTime.

A lock time can only be satisfied by n blocks being mined or n seconds passing. If you have two lock times (same unit) then the larger lock time being satisfied implies (in a mathematical sense) the smaller one being satisfied.

This function serves multiple purposes:

  • When evaluating OP_CHECKLOCKTIMEVERIFY the argument must be less than or equal to the transactions nLockTime. If using this function to validate a script self is the argument to CLTV and other is the transaction nLockTime.

  • If you wish to check a lock time against various other locks e.g., filtering out locks which cannot be satisfied. Can also be used to remove the smaller value of two OP_CHECKLOCKTIMEVERIFY operations within one branch of the script.

§Examples
let lock_time = absolute::LockTime::from_consensus(741521);
let check = absolute::LockTime::from_consensus(741521 + 1);
assert!(lock_time.is_implied_by(check));
Source

pub fn to_consensus_u32(self) -> u32

Returns the inner u32 value. This is the value used when creating this LockTime i.e., n OP_CHECKLOCKTIMEVERIFY or nLockTime.

§Warning

Do not compare values return by this method. The whole point of the LockTime type is to assist in doing correct comparisons. Either use is_satisfied_by, is_satisfied_by_lock, or use the pattern below:

§Examples
use bitcoin_units::absolute::{self, LockTime as L};

let _is_satisfied = match (n, lock_time) {
    (L::Blocks(n), L::Blocks(lock_time)) => n <= lock_time,
    (L::Seconds(n), L::Seconds(lock_time)) => n <= lock_time,
    _ => panic!("invalid comparison"),
};

// Or, if you have Rust 1.53 or greater
// let is_satisfied = n.partial_cmp(&lock_time).expect("invalid comparison").is_le();

Trait Implementations§

Source§

impl<'a> Arbitrary<'a> for LockTime

Available on crate feature arbitrary only.
Source§

fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>

Generate an arbitrary value of Self from the given unstructured data. Read more
Source§

fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>

Generate an arbitrary value of Self from the entirety of the given unstructured data. Read more
Source§

fn size_hint(depth: usize) -> (usize, Option<usize>)

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

fn try_size_hint( depth: usize, ) -> Result<(usize, Option<usize>), MaxRecursionReached>

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

impl Clone for LockTime

Source§

fn clone(&self) -> LockTime

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for LockTime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Decodable for LockTime

Available on crate feature encoding only.
Source§

type Decoder = LockTimeDecoder

Associated decoder for the type.
Source§

fn decoder() -> Self::Decoder

Constructs a “default decoder” for the type.
Source§

impl<'de> Deserialize<'de> for LockTime

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for LockTime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Encodable for LockTime

Available on crate feature encoding only.
Source§

type Encoder<'e> = LockTimeEncoder<'e>

The encoder associated with this type. Conceptually, the encoder is like an iterator which yields byte slices.
Source§

fn encoder(&self) -> Self::Encoder<'_>

Constructs a “default encoder” for the type.
Source§

impl From<Height> for LockTime

Source§

fn from(h: Height) -> Self

Converts to this type from the input type.
Source§

impl From<MedianTimePast> for LockTime

Source§

fn from(t: MedianTimePast) -> Self

Converts to this type from the input type.
Source§

impl FromStr for LockTime

Source§

type Err = ParseIntError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for LockTime

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for LockTime

Source§

fn eq(&self, other: &LockTime) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for LockTime

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryFrom<&str> for LockTime

Source§

type Error = ParseIntError

The type returned in the event of a conversion error.
Source§

fn try_from(s: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<Box<str>> for LockTime

Available on crate feature alloc only.
Source§

type Error = ParseIntError

The type returned in the event of a conversion error.
Source§

fn try_from(s: Box<str>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<String> for LockTime

Available on crate feature alloc only.
Source§

type Error = ParseIntError

The type returned in the event of a conversion error.
Source§

fn try_from(s: String) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for LockTime

Source§

impl Eq for LockTime

Source§

impl StructuralPartialEq for LockTime

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,