units: rename relative::Time to MtpInterval

The name `Time` is misleading. In fact this represents an interval
between MTPs.
This commit is contained in:
Andrew Poelstra 2025-05-01 17:53:39 +00:00
parent 39b057fade
commit 1a6b8b4c7a
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
4 changed files with 88 additions and 70 deletions

View File

@ -72,8 +72,12 @@ pub mod locktime {
/// Re-export everything from the `primitives::locktime::relative` module.
pub use primitives::locktime::relative::{
DisabledLockTimeError, Height, IncompatibleHeightError, IncompatibleTimeError,
LockTime, Time, TimeOverflowError,
LockTime, MtpInterval, TimeOverflowError,
};
#[deprecated(since = "TBD", note = "use `Mtp` instead")]
#[doc(hidden)]
pub type Time = MtpInterval;
}
}

View File

@ -13,9 +13,13 @@ use crate::{relative, TxIn};
#[rustfmt::skip] // Keep public re-exports separate.
#[doc(inline)]
pub use units::locktime::relative::{Height, Time, TimeOverflowError};
pub use units::locktime::relative::{Height, MtpInterval, TimeOverflowError};
use units::mtp_height::MtpAndHeight;
#[deprecated(since = "TBD", note = "use `Mtp` instead")]
#[doc(hidden)]
pub type Time = MtpInterval;
/// A relative lock time value, representing either a block height or time (512 second intervals).
///
/// Used for sequence numbers (`nSequence` in Bitcoin Core and [`TxIn::sequence`]
@ -61,7 +65,7 @@ use units::mtp_height::MtpAndHeight;
///
/// let chain_tip = MtpAndHeight::new(current_height, timestamps);
/// let utxo_mined_at = MtpAndHeight::new(utxo_height, utxo_timestamps);
/// let locktime = relative::LockTime::Time(relative::Time::from_512_second_intervals(10));
/// let locktime = relative::LockTime::Time(relative::MtpInterval::from_512_second_intervals(10));
///
/// // Check if locktime is satisfied
/// assert!(locktime.is_satisfied_by(chain_tip, utxo_mined_at));
@ -72,7 +76,7 @@ pub enum LockTime {
/// A block height lock time value.
Blocks(Height),
/// A 512 second time interval value.
Time(Time),
Time(MtpInterval),
}
impl LockTime {
@ -164,7 +168,7 @@ impl LockTime {
/// [`Self::from_seconds_floor`] or [`Self::from_seconds_ceil`].
#[inline]
pub const fn from_512_second_intervals(intervals: u16) -> Self {
LockTime::Time(Time::from_512_second_intervals(intervals))
LockTime::Time(MtpInterval::from_512_second_intervals(intervals))
}
/// Construct a new [`LockTime`] from seconds, converting the seconds into 512 second interval
@ -175,7 +179,7 @@ impl LockTime {
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
match Time::from_seconds_floor(seconds) {
match MtpInterval::from_seconds_floor(seconds) {
Ok(time) => Ok(LockTime::Time(time)),
Err(e) => Err(e),
}
@ -189,7 +193,7 @@ impl LockTime {
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
match Time::from_seconds_ceil(seconds) {
match MtpInterval::from_seconds_ceil(seconds) {
Ok(time) => Ok(LockTime::Time(time)),
Err(e) => Err(e),
}
@ -363,7 +367,7 @@ impl LockTime {
/// assert!(lock.is_satisfied_by_time(relative::Time::from_512_second_intervals(intervals + 10)).expect("a time"));
/// ```
#[inline]
pub fn is_satisfied_by_time(self, time: Time) -> Result<bool, IncompatibleTimeError> {
pub fn is_satisfied_by_time(self, time: MtpInterval) -> Result<bool, IncompatibleTimeError> {
use LockTime as L;
match self {
@ -378,9 +382,9 @@ impl From<Height> for LockTime {
fn from(h: Height) -> Self { LockTime::Blocks(h) }
}
impl From<Time> for LockTime {
impl From<MtpInterval> for LockTime {
#[inline]
fn from(t: Time) -> Self { LockTime::Time(t) }
fn from(t: MtpInterval) -> Self { LockTime::Time(t) }
}
impl fmt::Display for LockTime {
@ -442,7 +446,7 @@ pub struct IncompatibleHeightError {
/// Attempted to satisfy a lock-by-blocktime lock with this height.
height: Height,
/// The inner time value of the lock-by-blocktime lock.
time: Time,
time: MtpInterval,
}
impl IncompatibleHeightError {
@ -450,7 +454,7 @@ impl IncompatibleHeightError {
pub fn incompatible(&self) -> Height { self.height }
/// Returns the time value of the lock-by-blocktime lock.
pub fn expected(&self) -> Time { self.time }
pub fn expected(&self) -> MtpInterval { self.time }
}
impl fmt::Display for IncompatibleHeightError {
@ -471,14 +475,14 @@ impl std::error::Error for IncompatibleHeightError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncompatibleTimeError {
/// Attempted to satisfy a lock-by-blockheight lock with this time.
time: Time,
time: MtpInterval,
/// The inner height value of the lock-by-blockheight lock.
height: Height,
}
impl IncompatibleTimeError {
/// Returns the time that was erroneously used to try and satisfy a lock-by-blockheight lock.
pub fn incompatible(&self) -> Time { self.time }
pub fn incompatible(&self) -> MtpInterval { self.time }
/// Returns the height value of the lock-by-blockheight lock.
pub fn expected(&self) -> Height { self.height }
@ -538,8 +542,8 @@ mod tests {
fn parses_correctly_to_height_or_time() {
let height1 = Height::from(10);
let height2 = Height::from(11);
let time1 = Time::from_512_second_intervals(70);
let time2 = Time::from_512_second_intervals(71);
let time1 = MtpInterval::from_512_second_intervals(70);
let time2 = MtpInterval::from_512_second_intervals(71);
let lock_by_height1 = LockTime::from(height1);
let lock_by_height2 = LockTime::from(height2);
@ -571,18 +575,24 @@ mod tests {
#[test]
fn time_correctly_implies() {
let time = Time::from_512_second_intervals(70);
let time = MtpInterval::from_512_second_intervals(70);
let lock_by_time = LockTime::from(time);
assert!(!lock_by_time.is_implied_by(LockTime::from(Time::from_512_second_intervals(69))));
assert!(lock_by_time.is_implied_by(LockTime::from(Time::from_512_second_intervals(70))));
assert!(lock_by_time.is_implied_by(LockTime::from(Time::from_512_second_intervals(71))));
assert!(
!lock_by_time.is_implied_by(LockTime::from(MtpInterval::from_512_second_intervals(69)))
);
assert!(
lock_by_time.is_implied_by(LockTime::from(MtpInterval::from_512_second_intervals(70)))
);
assert!(
lock_by_time.is_implied_by(LockTime::from(MtpInterval::from_512_second_intervals(71)))
);
}
#[test]
fn sequence_correctly_implies() {
let height = Height::from(10);
let time = Time::from_512_second_intervals(70);
let time = MtpInterval::from_512_second_intervals(70);
let lock_by_height = LockTime::from(height);
let lock_by_time = LockTime::from(time);
@ -603,7 +613,7 @@ mod tests {
#[test]
fn incorrect_units_do_not_imply() {
let time = Time::from_512_second_intervals(70);
let time = MtpInterval::from_512_second_intervals(70);
let height = Height::from(10);
let lock_by_time = LockTime::from(time);
@ -644,7 +654,7 @@ mod tests {
#[test]
fn incompatible_height_error() {
let height = Height::from(10);
let time = Time::from_512_second_intervals(70);
let time = MtpInterval::from_512_second_intervals(70);
let lock_by_time = LockTime::from(time);
let err = lock_by_time.is_satisfied_by_height(height).unwrap_err();
@ -656,7 +666,7 @@ mod tests {
#[test]
fn incompatible_time_error() {
let height = Height::from(10);
let time = Time::from_512_second_intervals(70);
let time = MtpInterval::from_512_second_intervals(70);
let lock_by_height = LockTime::from(height);
let err = lock_by_height.is_satisfied_by_time(time).unwrap_err();
@ -687,10 +697,10 @@ mod tests {
let lock2 = LockTime::Blocks(Height::from(21));
assert!(!lock2.is_satisfied_by(chain_tip, utxo_mined_at));
let lock3 = LockTime::Time(Time::from_512_second_intervals(10));
let lock3 = LockTime::Time(MtpInterval::from_512_second_intervals(10));
assert!(lock3.is_satisfied_by(chain_tip, utxo_mined_at));
let lock4 = LockTime::Time(Time::from_512_second_intervals(20000));
let lock4 = LockTime::Time(MtpInterval::from_512_second_intervals(20000));
assert!(!lock4.is_satisfied_by(chain_tip, utxo_mined_at));
assert!(LockTime::ZERO.is_satisfied_by(chain_tip, utxo_mined_at));
@ -702,7 +712,7 @@ mod tests {
let max_height_lock = LockTime::Blocks(Height::MAX);
assert!(!max_height_lock.is_satisfied_by(chain_tip, utxo_mined_at));
let max_time_lock = LockTime::Time(Time::MAX);
let max_time_lock = LockTime::Time(MtpInterval::MAX);
assert!(!max_time_lock.is_satisfied_by(chain_tip, utxo_mined_at));
let max_chain_tip =

View File

@ -187,7 +187,7 @@ impl Sequence {
/// Constructs a new [`relative::LockTime`] from this [`Sequence`] number.
#[inline]
pub fn to_relative_lock_time(self) -> Option<relative::LockTime> {
use crate::locktime::relative::{Height, LockTime, Time};
use crate::locktime::relative::{Height, LockTime, MtpInterval};
if !self.is_relative_lock_time() {
return None;
@ -196,7 +196,7 @@ impl Sequence {
let lock_value = self.low_u16();
if self.is_time_locked() {
Some(LockTime::from(Time::from_512_second_intervals(lock_value)))
Some(LockTime::from(MtpInterval::from_512_second_intervals(lock_value)))
} else {
Some(LockTime::from(Height::from(lock_value)))
}
@ -263,8 +263,8 @@ impl<'a> Arbitrary<'a> for Sequence {
3 => Ok(Sequence::ENABLE_LOCKTIME_AND_RBF),
4 => Ok(Sequence::from_consensus(relative::Height::MIN.to_consensus_u32())),
5 => Ok(Sequence::from_consensus(relative::Height::MAX.to_consensus_u32())),
6 => Ok(Sequence::from_consensus(relative::Time::MIN.to_consensus_u32())),
7 => Ok(Sequence::from_consensus(relative::Time::MAX.to_consensus_u32())),
6 => Ok(Sequence::from_consensus(relative::MtpInterval::MIN.to_consensus_u32())),
7 => Ok(Sequence::from_consensus(relative::MtpInterval::MAX.to_consensus_u32())),
_ => Ok(Sequence(u.arbitrary()?)),
}
}

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: CC0-1.0
//! Provides [`Height`] and [`Time`] types used by the `rust-bitcoin` `relative::LockTime` type.
//! Provides [`Height`] and [`MtpInterval`] types used by the `rust-bitcoin` `relative::LockTime` type.
use core::fmt;
@ -74,30 +74,34 @@ impl fmt::Display for Height {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
}
#[deprecated(since = "TBD", note = "use `Mtp` instead")]
#[doc(hidden)]
pub type Time = MtpInterval;
/// A relative lock time lock-by-blocktime value.
///
/// For BIP 68 relative lock-by-blocktime locks, time is measured in 512 second intervals.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Time(u16);
pub struct MtpInterval(u16);
impl Time {
impl MtpInterval {
/// Relative block time 0, can be included in any block.
pub const ZERO: Self = Time(0);
pub const ZERO: Self = MtpInterval(0);
/// The minimum relative block time (0), can be included in any block.
pub const MIN: Self = Time::ZERO;
pub const MIN: Self = MtpInterval::ZERO;
/// The maximum relative block time (33,554,432 seconds or approx 388 days).
pub const MAX: Self = Time(u16::MAX);
pub const MAX: Self = MtpInterval(u16::MAX);
/// Constructs a new [`Time`] using time intervals where each interval is equivalent to 512 seconds.
/// Constructs a new [`MtpInterval`] using time intervals where each interval is equivalent to 512 seconds.
///
/// Encoding finer granularity of time for relative lock-times is not supported in Bitcoin.
#[inline]
pub const fn from_512_second_intervals(intervals: u16) -> Self { Time(intervals) }
pub const fn from_512_second_intervals(intervals: u16) -> Self { MtpInterval(intervals) }
/// Constructs a new [`Time`] from seconds, converting the seconds into 512 second interval with
/// Constructs a new [`MtpInterval`] from seconds, converting the seconds into 512 second interval with
/// truncating division.
///
/// # Errors
@ -108,13 +112,13 @@ impl Time {
pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
let interval = seconds / 512;
if interval <= u16::MAX as u32 { // infallible cast, needed by const code
Ok(Time::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
Ok(MtpInterval::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
} else {
Err(TimeOverflowError { seconds })
}
}
/// Constructs a new [`Time`] from seconds, converting the seconds into 512 second intervals with
/// Constructs a new [`MtpInterval`] from seconds, converting the seconds into 512 second intervals with
/// ceiling division.
///
/// # Errors
@ -125,7 +129,7 @@ impl Time {
pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
if seconds <= u16::MAX as u32 * 512 {
let interval = (seconds + 511) / 512;
Ok(Time::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
Ok(MtpInterval::from_512_second_intervals(interval as u16)) // Cast checked above, needed by const code.
} else {
Err(TimeOverflowError { seconds })
}
@ -165,16 +169,16 @@ impl Time {
}
}
crate::impl_parse_str_from_int_infallible!(Time, u16, from_512_second_intervals);
crate::impl_parse_str_from_int_infallible!(MtpInterval, u16, from_512_second_intervals);
impl fmt::Display for Time {
impl fmt::Display for MtpInterval {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
}
/// Error returned when the input time in seconds was too large to be encoded to a 16 bit 512 second interval.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeOverflowError {
/// Time value in seconds that overflowed.
/// Time interval value in seconds that overflowed.
// Private because we maintain an invariant that the `seconds` value does actually overflow.
pub(crate) seconds: u32,
}
@ -218,14 +222,14 @@ impl<'a> Arbitrary<'a> for Height {
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Time {
impl<'a> Arbitrary<'a> for MtpInterval {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let choice = u.int_in_range(0..=2)?;
match choice {
0 => Ok(Time::MIN),
1 => Ok(Time::MAX),
_ => Ok(Time::from_512_second_intervals(u16::arbitrary(u)?)),
0 => Ok(MtpInterval::MIN),
1 => Ok(MtpInterval::MAX),
_ => Ok(MtpInterval::from_512_second_intervals(u16::arbitrary(u)?)),
}
}
}
@ -243,54 +247,54 @@ mod tests {
#[test]
fn sanity_check() {
assert_eq!(Height::MAX.to_consensus_u32(), u32::from(u16::MAX));
assert_eq!(Time::from_512_second_intervals(100).value(), 100u16);
assert_eq!(Time::from_512_second_intervals(100).to_consensus_u32(), 4_194_404u32); // 0x400064
assert_eq!(MtpInterval::from_512_second_intervals(100).value(), 100u16);
assert_eq!(MtpInterval::from_512_second_intervals(100).to_consensus_u32(), 4_194_404u32); // 0x400064
}
#[test]
fn from_seconds_ceil_success() {
let actual = Time::from_seconds_ceil(100).unwrap();
let expected = Time(1_u16);
let actual = MtpInterval::from_seconds_ceil(100).unwrap();
let expected = MtpInterval(1_u16);
assert_eq!(actual, expected);
}
#[test]
fn from_seconds_ceil_with_maximum_encodable_seconds_success() {
let actual = Time::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS).unwrap();
let expected = Time(u16::MAX);
let actual = MtpInterval::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS).unwrap();
let expected = MtpInterval(u16::MAX);
assert_eq!(actual, expected);
}
#[test]
fn from_seconds_ceil_causes_time_overflow_error() {
let result = Time::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS + 1);
let result = MtpInterval::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS + 1);
assert!(result.is_err());
}
#[test]
fn from_seconds_floor_success() {
let actual = Time::from_seconds_floor(100).unwrap();
let expected = Time(0_u16);
let actual = MtpInterval::from_seconds_floor(100).unwrap();
let expected = MtpInterval(0_u16);
assert_eq!(actual, expected);
}
#[test]
fn from_seconds_floor_with_exact_interval() {
let actual = Time::from_seconds_floor(512).unwrap();
let expected = Time(1_u16);
let actual = MtpInterval::from_seconds_floor(512).unwrap();
let expected = MtpInterval(1_u16);
assert_eq!(actual, expected);
}
#[test]
fn from_seconds_floor_with_maximum_encodable_seconds_success() {
let actual = Time::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 511).unwrap();
let expected = Time(u16::MAX);
let actual = MtpInterval::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 511).unwrap();
let expected = MtpInterval(u16::MAX);
assert_eq!(actual, expected);
}
#[test]
fn from_seconds_floor_causes_time_overflow_error() {
let result = Time::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 512);
let result = MtpInterval::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 512);
assert!(result.is_err());
}
@ -305,9 +309,9 @@ mod tests {
#[test]
#[cfg(feature = "serde")]
pub fn encode_decode_time() {
serde_round_trip!(Time::ZERO);
serde_round_trip!(Time::MIN);
serde_round_trip!(Time::MAX);
serde_round_trip!(MtpInterval::ZERO);
serde_round_trip!(MtpInterval::MIN);
serde_round_trip!(MtpInterval::MAX);
}
fn generate_timestamps(start: u32, step: u16) -> [BlockTime; 11] {
@ -331,7 +335,7 @@ mod tests {
// Test case 1: Satisfaction (current_mtp >= utxo_mtp + required_seconds)
// 10 intervals × 512 seconds = 5120 seconds
let time_lock = Time::from_512_second_intervals(10);
let time_lock = MtpInterval::from_512_second_intervals(10);
let chain_state1 = MtpAndHeight::new(BlockHeight::from_u32(100), timestamps);
let utxo_state1 = MtpAndHeight::new(BlockHeight::from_u32(80), utxo_timestamps);
assert!(time_lock.is_satisfied_by(chain_state1, utxo_state1));
@ -342,13 +346,13 @@ mod tests {
assert!(!time_lock.is_satisfied_by(chain_state2, utxo_state2));
// Test case 3: Test with a larger value (100 intervals = 51200 seconds)
let larger_lock = Time::from_512_second_intervals(100);
let larger_lock = MtpInterval::from_512_second_intervals(100);
let chain_state3 = MtpAndHeight::new(BlockHeight::from_u32(100), timestamps3);
let utxo_state3 = MtpAndHeight::new(BlockHeight::from_u32(80), utxo_timestamps3);
assert!(larger_lock.is_satisfied_by(chain_state3, utxo_state3));
// Test case 4: Overflow handling - tests that is_satisfied_by handles overflow gracefully
let max_time_lock = Time::MAX;
let max_time_lock = MtpInterval::MAX;
let chain_state4 = MtpAndHeight::new(BlockHeight::from_u32(100), timestamps);
let utxo_state4 = MtpAndHeight::new(BlockHeight::from_u32(80), utxo_timestamps);
assert!(!max_time_lock.is_satisfied_by(chain_state4, utxo_state4));