diff --git a/examples/ecdsa-psbt.rs b/examples/ecdsa-psbt.rs index 70b1399e..5c595e11 100644 --- a/examples/ecdsa-psbt.rs +++ b/examples/ecdsa-psbt.rs @@ -34,6 +34,7 @@ use std::str::FromStr; use bitcoin::consensus::encode; use bitcoin::hashes::hex::{self, FromHex}; +use bitcoin::locktime::absolute; use bitcoin::secp256k1::{Secp256k1, Signing, Verification}; use bitcoin::util::amount::ParseAmountError; use bitcoin::util::bip32::{ @@ -42,7 +43,7 @@ use bitcoin::util::bip32::{ }; use bitcoin::util::psbt::{self, Input, Psbt, PsbtSighashType}; use bitcoin::{ - address, Address, Amount, Network, OutPoint, PackedLockTime, PrivateKey, PublicKey, Script, + address, Address, Amount, Network, OutPoint, PrivateKey, PublicKey, Script, Sequence, Transaction, TxIn, TxOut, Txid, Witness, }; @@ -206,7 +207,7 @@ impl WatchOnly { let tx = Transaction { version: 2, - lock_time: PackedLockTime::ZERO, + lock_time: absolute::PackedLockTime::ZERO, input: vec![TxIn { previous_output: OutPoint { txid: Txid::from_hex(INPUT_UTXO_TXID)?, diff --git a/src/blockdata/constants.rs b/src/blockdata/constants.rs index ba01eb06..27de8845 100644 --- a/src/blockdata/constants.rs +++ b/src/blockdata/constants.rs @@ -16,7 +16,7 @@ use crate::hashes::hex::{self, HexIterator}; use crate::hashes::{Hash, sha256d}; use crate::blockdata::opcodes; use crate::blockdata::script; -use crate::blockdata::locktime::PackedLockTime; +use crate::blockdata::locktime::absolute; use crate::blockdata::transaction::{OutPoint, Transaction, TxOut, TxIn, Sequence}; use crate::blockdata::block::{Block, BlockHeader}; use crate::blockdata::witness::Witness; @@ -72,7 +72,7 @@ fn bitcoin_genesis_tx() -> Transaction { // Base let mut ret = Transaction { version: 1, - lock_time: PackedLockTime::ZERO, + lock_time: absolute::PackedLockTime::ZERO, input: vec![], output: vec![], }; @@ -200,7 +200,7 @@ mod test { use crate::hashes::hex::{ToHex, FromHex}; use crate::network::constants::Network; use crate::consensus::encode::serialize; - use crate::blockdata::locktime::PackedLockTime; + use crate::blockdata::locktime::absolute; #[test] fn bitcoin_genesis_first_transaction() { @@ -218,7 +218,7 @@ mod test { assert_eq!(serialize(&gen.output[0].script_pubkey), Vec::from_hex("434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac").unwrap()); assert_eq!(gen.output[0].value, 50 * COIN_VALUE); - assert_eq!(gen.lock_time, PackedLockTime::ZERO); + assert_eq!(gen.lock_time, absolute::PackedLockTime::ZERO); assert_eq!(gen.wtxid().to_hex(), "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"); } diff --git a/src/blockdata/locktime.rs b/src/blockdata/locktime/absolute.rs similarity index 96% rename from src/blockdata/locktime.rs rename to src/blockdata/locktime/absolute.rs index 3c03548d..aaece729 100644 --- a/src/blockdata/locktime.rs +++ b/src/blockdata/locktime/absolute.rs @@ -47,7 +47,8 @@ pub const LOCK_TIME_THRESHOLD: u32 = 500_000_000; /// /// # Examples /// ``` -/// # use bitcoin::{Amount, PackedLockTime, LockTime}; +/// # use bitcoin::Amount; +/// # use bitcoin::absolute::{PackedLockTime, LockTime}; /// #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] /// struct S { /// lock_time: PackedLockTime, @@ -140,7 +141,8 @@ impl fmt::UpperHex for PackedLockTime { } } -/// A lock time value, representing either a block height or a UNIX timestamp (seconds since epoch). +/// 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 [`crate::Transaction::lock_time`] /// in this library) and also for the argument to opcode 'OP_CHECKLOCKTIMEVERIFY`. @@ -152,10 +154,10 @@ impl fmt::UpperHex for PackedLockTime { /// /// # Examples /// ``` -/// # use bitcoin::{LockTime, LockTime::*}; +/// # use bitcoin::absolute::{LockTime, LockTime::*}; /// # let n = LockTime::from_consensus(100); // n OP_CHECKLOCKTIMEVERIFY /// # let lock_time = LockTime::from_consensus(100); // nLockTime -/// // To compare lock times there are various `is_satisfied_*` methods, you may also use: +/// // To compare absolute lock times there are various `is_satisfied_*` methods, you may also use: /// let is_satisfied = match (n, lock_time) { /// (Blocks(n), Blocks(lock_time)) => n <= lock_time, /// (Seconds(n), Seconds(lock_time)) => n <= lock_time, @@ -171,7 +173,7 @@ pub enum LockTime { /// /// # Examples /// ```rust - /// use bitcoin::LockTime; + /// use bitcoin::absolute::LockTime; /// /// let block: u32 = 741521; /// let n = LockTime::from_height(block).expect("valid height"); @@ -183,7 +185,7 @@ pub enum LockTime { /// /// # Examples /// ```rust - /// use bitcoin::LockTime; + /// use bitcoin::absolute::LockTime; /// /// let seconds: u32 = 1653195600; // May 22nd, 5am UTC. /// let n = LockTime::from_time(seconds).expect("valid time"); @@ -203,7 +205,7 @@ impl LockTime { /// # Examples /// /// ```rust - /// # use bitcoin::LockTime; + /// # use bitcoin::absolute::LockTime; /// # let n = LockTime::from_consensus(741521); // n OP_CHECKLOCKTIMEVERIFY /// /// // `from_consensus` roundtrips as expected with `to_consensus_u32`. @@ -225,7 +227,7 @@ impl LockTime { /// /// # Examples /// ```rust - /// # use bitcoin::LockTime; + /// # use bitcoin::absolute::LockTime; /// assert!(LockTime::from_height(741521).is_ok()); /// assert!(LockTime::from_height(1653195600).is_err()); /// ``` @@ -241,7 +243,7 @@ impl LockTime { /// /// # Examples /// ```rust - /// # use bitcoin::LockTime; + /// # use bitcoin::absolute::LockTime; /// assert!(LockTime::from_time(1653195600).is_ok()); /// assert!(LockTime::from_time(741521).is_err()); /// ``` @@ -283,7 +285,7 @@ impl LockTime { /// /// # Examples /// ```no_run - /// # use bitcoin::locktime::{LockTime, Height, Time}; + /// # use bitcoin::absolute::{LockTime, Height, Time}; /// // Can be implemented if block chain data is available. /// fn get_height() -> Height { todo!("return the current block height") } /// fn get_time() -> Time { todo!("return the current block time") } @@ -314,7 +316,7 @@ impl LockTime { /// # Examples /// /// ```rust - /// # use bitcoin::{LockTime, LockTime::*}; + /// # use bitcoin::absolute::{LockTime, LockTime::*}; /// # let n = LockTime::from_consensus(100); // n OP_CHECKLOCKTIMEVERIFY /// # let lock_time = LockTime::from_consensus(100); // nLockTime /// @@ -410,7 +412,7 @@ impl Height { /// /// # Examples /// ```rust - /// use bitcoin::locktime::Height; + /// use bitcoin::locktime::absolute::Height; /// /// let h: u32 = 741521; /// let height = Height::from_consensus(h).expect("invalid height value"); @@ -429,7 +431,7 @@ impl Height { /// /// # Examples /// ```rust - /// use bitcoin::LockTime; + /// use bitcoin::absolute::LockTime; /// /// let n_lock_time: u32 = 741521; /// let lock_time = LockTime::from_consensus(n_lock_time); @@ -493,7 +495,7 @@ impl Time { /// /// # Examples /// ```rust - /// use bitcoin::locktime::Time; + /// use bitcoin::locktime::absolute::Time; /// /// let t: u32 = 1653195600; // May 22nd, 5am UTC. /// let time = Time::from_consensus(t).expect("invalid time value"); @@ -512,7 +514,7 @@ impl Time { /// /// # Examples /// ```rust - /// use bitcoin::LockTime; + /// use bitcoin::absolute::LockTime; /// /// let n_lock_time: u32 = 1653195600; // May 22nd, 5am UTC. /// let lock_time = LockTime::from_consensus(n_lock_time); diff --git a/src/blockdata/locktime/mod.rs b/src/blockdata/locktime/mod.rs new file mode 100644 index 00000000..5100d702 --- /dev/null +++ b/src/blockdata/locktime/mod.rs @@ -0,0 +1,8 @@ +// Rust Bitcoin Library - Written by the rust-bitcoin developers. +// SPDX-License-Identifier: CC0-1.0 + +//! Provides absolute and relative locktimes. +//! + +pub mod absolute; +pub mod relative; diff --git a/src/blockdata/locktime/relative.rs b/src/blockdata/locktime/relative.rs new file mode 100644 index 00000000..7502c969 --- /dev/null +++ b/src/blockdata/locktime/relative.rs @@ -0,0 +1,289 @@ +// Rust Bitcoin Library - Written by the rust-bitcoin developers. +// SPDX-License-Identifier: CC0-1.0 + +//! Provides type [`LockTime`] that implements the logic around nSequence/OP_CHECKSEQUENCEVERIFY. +//! +//! There are two types of lock time: lock-by-blockheight and lock-by-blocktime, distinguished by +//! whether bit 22 of the `u32` consensus value is set. +//! + +use core::fmt; +use core::convert::TryFrom; + +#[cfg(docsrs)] +use crate::relative; + +/// A relative lock time value, representing either a block height or time (512 second intervals). +/// +/// The `relative::LockTime` type does not have any constructors, this is by design, please use +/// `Sequence::to_relative_lock_time` to create a relative lock time. +/// +/// ### Relevant BIPs +/// +/// * [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) +#[allow(clippy::derive_ord_xor_partial_ord)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))] +pub enum LockTime { + /// A block height lock time value. + Blocks(Height), + /// A 512 second time interval value. + Time(Time), +} + +impl LockTime { + /// Returns true if this [`relative::LockTime`] is satisfied by either height or time. + /// + /// # Examples + /// + /// ```rust + /// # use bitcoin::Sequence; + /// # use bitcoin::locktime::relative::{LockTime, Height, Time}; + /// + /// # let height = 100; // 100 blocks. + /// # let intervals = 70; // Approx 10 hours. + /// # let current_height = || Height::from(height + 10); + /// # let current_time = || Time::from_512_second_intervals(intervals + 10); + /// # let lock = Sequence::from_height(height).to_relative_lock_time().expect("valid height"); + /// + /// // Users that have chain data can get the current height and time to check against a lock. + /// let height_and_time = (current_time(), current_height()); // tuple order does not matter. + /// assert!(lock.is_satisfied_by(current_height(), current_time())); + /// ``` + pub fn is_satisfied_by(&self, h: Height, t: Time) -> bool { + if let Ok(true) = self.is_satisfied_by_height(h) { + true + } else if let Ok(true) = self.is_satisfied_by_time(t) { + true + } else { + false + } + } + + /// Returns true if this [`relative::LockTime`] is satisfied by `other` lock. + /// + /// This function is useful when checking sequence values against a lock, first one checks the + /// sequence represents a relative lock time by converting to `LockTime` then use this function + /// to see if [`LockTime`] is satisfied by the newly created lock. + /// + /// # Examples + /// + /// ```rust + /// # use bitcoin::Sequence; + /// # use bitcoin::locktime::relative::{LockTime, Height, Time}; + /// + /// # let height = 100; // 100 blocks. + /// # let lock = Sequence::from_height(height).to_relative_lock_time().expect("valid height"); + /// # let test_sequence = Sequence::from_height(height + 10); + /// + /// let satisfied = match test_sequence.to_relative_lock_time() { + /// None => false, // Handle non-lock-time case. + /// Some(test_lock) => lock.is_satisfied_by_lock(test_lock), + /// }; + /// assert!(satisfied); + /// ``` + pub fn is_satisfied_by_lock(&self, other: LockTime) -> bool { + use LockTime::*; + + match (*self, other) { + (Blocks(n), Blocks(m)) => n.value() <= m.value(), + (Time(n), Time(m)) => n.value() <= m.value(), + _ => false, // Not the same units. + } + } + + /// Returns true if this [`relative::LockTime`] is satisfied by [`Height`]. + /// + /// # Errors + /// + /// Returns an error if this lock is not lock-by-height. + /// + /// # Examples + /// + /// ```rust + /// # use bitcoin::Sequence; + /// # use bitcoin::locktime::relative::{LockTime, Height, Time}; + /// + /// let height: u16 = 100; + /// let lock = Sequence::from_height(height).to_relative_lock_time().expect("valid height"); + /// assert!(lock.is_satisfied_by_height(Height::from(height+1)).expect("a height")); + /// ``` + #[inline] + pub fn is_satisfied_by_height(&self, h: Height) -> Result { + use LockTime::*; + + match *self { + Blocks(ref height) => Ok(height.value() <= h.value()), + Time(ref time) => Err(Error::IncompatibleTime(*self, *time)), + } + } + + /// Returns true if this [`relative::LockTime`] is satisfied by [`Time`]. + /// + /// # Errors + /// + /// Returns an error if this lock is not lock-by-time. + /// + /// # Examples + /// + /// ```rust + /// # use bitcoin::Sequence; + /// # use bitcoin::locktime::relative::{LockTime, Height, Time}; + /// + /// let intervals: u16 = 70; // approx 10 hours; + /// let lock = Sequence::from_512_second_intervals(intervals).to_relative_lock_time().expect("valid time"); + /// assert!(lock.is_satisfied_by_time(Time::from_512_second_intervals(intervals + 10)).expect("a time")); + /// ``` + #[inline] + pub fn is_satisfied_by_time(&self, t: Time) -> Result { + use LockTime::*; + + match *self { + Time(ref time) => Ok(time.value() <= t.value()), + Blocks(ref height) => Err(Error::IncompatibleHeight(*self, *height)), + } + } +} + +impl From for LockTime { + #[inline] + fn from(h: Height) -> Self { + LockTime::Blocks(h) + } +} + +impl From