1pub mod error;
10
11use core::{convert, fmt};
12
13#[cfg(feature = "arbitrary")]
14use arbitrary::{Arbitrary, Unstructured};
15use internals::const_casts;
16
17use crate::parse_int::{self, PrefixedHexError, UnprefixedHexError};
18#[cfg(doc)]
19use crate::relative;
20use crate::{BlockHeight, BlockMtp, Sequence};
21
22#[rustfmt::skip] #[doc(no_inline)]
24pub use self::error::{
25 DisabledLockTimeError, IncompatibleHeightError, IncompatibleTimeError, InvalidHeightError,
26 InvalidTimeError, IsSatisfiedByError, IsSatisfiedByHeightError, IsSatisfiedByTimeError,
27 TimeOverflowError,
28};
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum LockTime {
47 Blocks(NumberOfBlocks),
49 Time(NumberOf512Seconds),
51}
52
53impl LockTime {
54 pub const ZERO: Self = Self::Blocks(NumberOfBlocks::ZERO);
57
58 pub const SIZE: usize = 4; #[inline]
91 pub fn from_consensus(n: u32) -> Result<Self, DisabledLockTimeError> {
92 let sequence = crate::Sequence::from_consensus(n);
93 sequence.to_relative_lock_time().ok_or(DisabledLockTimeError(n))
94 }
95
96 #[inline]
104 pub fn to_consensus_u32(self) -> u32 {
105 match self {
106 Self::Blocks(ref h) => u32::from(h.to_height()),
107 Self::Time(ref t) => Sequence::LOCK_TYPE_MASK | u32::from(t.to_512_second_intervals()),
108 }
109 }
110
111 #[inline]
133 pub fn from_sequence(n: Sequence) -> Result<Self, DisabledLockTimeError> {
134 Self::from_consensus(n.to_consensus_u32())
135 }
136
137 #[inline]
139 pub fn to_sequence(self) -> Sequence { Sequence::from_consensus(self.to_consensus_u32()) }
140
141 #[inline]
143 pub const fn from_height(n: u16) -> Self { Self::Blocks(NumberOfBlocks::from_height(n)) }
144
145 #[inline]
150 pub const fn from_512_second_intervals(intervals: u16) -> Self {
151 Self::Time(NumberOf512Seconds::from_512_second_intervals(intervals))
152 }
153
154 #[inline]
161 pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
162 match NumberOf512Seconds::from_seconds_floor(seconds) {
163 Ok(time) => Ok(Self::Time(time)),
164 Err(e) => Err(e),
165 }
166 }
167
168 #[inline]
175 pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
176 match NumberOf512Seconds::from_seconds_ceil(seconds) {
177 Ok(time) => Ok(Self::Time(time)),
178 Err(e) => Err(e),
179 }
180 }
181
182 #[inline]
184 pub const fn is_same_unit(self, other: Self) -> bool {
185 matches!((self, other), (Self::Blocks(_), Self::Blocks(_)) | (Self::Time(_), Self::Time(_)))
186 }
187
188 #[inline]
190 pub const fn is_block_height(self) -> bool { matches!(self, Self::Blocks(_)) }
191
192 #[inline]
194 pub const fn is_block_time(self) -> bool { !self.is_block_height() }
195
196 #[inline]
205 pub fn is_satisfied_by(
206 self,
207 chain_tip_height: BlockHeight,
208 chain_tip_mtp: BlockMtp,
209 utxo_mined_at_height: BlockHeight,
210 utxo_mined_at_mtp: BlockMtp,
211 ) -> Result<bool, IsSatisfiedByError> {
212 match self {
213 Self::Blocks(blocks) => blocks
214 .is_satisfied_by(chain_tip_height, utxo_mined_at_height)
215 .map_err(IsSatisfiedByError::Blocks),
216 Self::Time(time) => time
217 .is_satisfied_by(chain_tip_mtp, utxo_mined_at_mtp)
218 .map_err(IsSatisfiedByError::Time),
219 }
220 }
221
222 #[inline]
231 pub fn is_satisfied_by_height(
232 self,
233 chain_tip: BlockHeight,
234 utxo_mined_at: BlockHeight,
235 ) -> Result<bool, IsSatisfiedByHeightError> {
236 match self {
237 Self::Blocks(blocks) => blocks
238 .is_satisfied_by(chain_tip, utxo_mined_at)
239 .map_err(IsSatisfiedByHeightError::Satisfaction),
240 Self::Time(time) =>
241 Err(IsSatisfiedByHeightError::Incompatible(IncompatibleHeightError(time))),
242 }
243 }
244
245 #[inline]
254 pub fn is_satisfied_by_time(
255 self,
256 chain_tip: BlockMtp,
257 utxo_mined_at: BlockMtp,
258 ) -> Result<bool, IsSatisfiedByTimeError> {
259 match self {
260 Self::Time(time) => time
261 .is_satisfied_by(chain_tip, utxo_mined_at)
262 .map_err(IsSatisfiedByTimeError::Satisfaction),
263 Self::Blocks(blocks) =>
264 Err(IsSatisfiedByTimeError::Incompatible(IncompatibleTimeError(blocks))),
265 }
266 }
267
268 #[inline]
298 pub fn is_implied_by(self, other: Self) -> bool {
299 match (self, other) {
300 (Self::Blocks(this), Self::Blocks(other)) => this <= other,
301 (Self::Time(this), Self::Time(other)) => this <= other,
302 _ => false, }
304 }
305
306 #[inline]
327 pub fn is_implied_by_sequence(self, other: Sequence) -> bool {
328 Self::from_sequence(other).is_ok_and(|other| self.is_implied_by(other))
329 }
330}
331
332impl From<NumberOfBlocks> for LockTime {
333 #[inline]
334 fn from(h: NumberOfBlocks) -> Self { Self::Blocks(h) }
335}
336
337impl From<NumberOf512Seconds> for LockTime {
338 #[inline]
339 fn from(t: NumberOf512Seconds) -> Self { Self::Time(t) }
340}
341
342impl fmt::Display for LockTime {
343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344 if f.alternate() {
345 match *self {
346 Self::Blocks(ref h) => write!(f, "block-height {}", h),
347 Self::Time(ref t) => write!(f, "block-time {} (512 second intervals)", t),
348 }
349 } else {
350 match *self {
351 Self::Blocks(ref h) => fmt::Display::fmt(h, f),
352 Self::Time(ref t) => fmt::Display::fmt(t, f),
353 }
354 }
355 }
356}
357
358impl convert::TryFrom<Sequence> for LockTime {
359 type Error = DisabledLockTimeError;
360 #[inline]
361 fn try_from(seq: Sequence) -> Result<Self, DisabledLockTimeError> { Self::from_sequence(seq) }
362}
363
364impl From<LockTime> for Sequence {
365 #[inline]
366 fn from(lt: LockTime) -> Self { lt.to_sequence() }
367}
368
369#[cfg(feature = "serde")]
370impl serde::Serialize for LockTime {
371 #[inline]
372 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373 where
374 S: serde::Serializer,
375 {
376 self.to_consensus_u32().serialize(serializer)
377 }
378}
379
380#[cfg(feature = "serde")]
381impl<'de> serde::Deserialize<'de> for LockTime {
382 #[inline]
383 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
384 where
385 D: serde::Deserializer<'de>,
386 {
387 u32::deserialize(deserializer)
388 .and_then(|n| Self::from_consensus(n).map_err(serde::de::Error::custom))
389 }
390}
391
392#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
394pub struct NumberOfBlocks(u16);
395
396impl NumberOfBlocks {
397 pub const ZERO: Self = Self(0);
399
400 pub const MIN: Self = Self::ZERO;
402
403 pub const MAX: Self = Self(u16::MAX);
405
406 #[inline]
408 pub const fn from_height(blocks: u16) -> Self { Self(blocks) }
409
410 #[inline]
412 #[must_use]
413 pub const fn to_height(self) -> u16 { self.0 }
414
415 #[inline]
422 pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
423 let block_count = parse_int::hex_u16_prefixed(s)?;
424 Ok(Self::from_height(block_count))
425 }
426
427 #[inline]
434 pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
435 let block_count = parse_int::hex_u16_unprefixed(s)?;
436 Ok(Self::from_height(block_count))
437 }
438
439 pub fn is_satisfied_by(
445 self,
446 chain_tip: crate::BlockHeight,
447 utxo_mined_at: crate::BlockHeight,
448 ) -> Result<bool, InvalidHeightError> {
449 match chain_tip.checked_sub(utxo_mined_at) {
450 Some(diff) => {
451 if diff.to_u32() == u32::MAX {
452 return Ok(true);
454 }
455 Ok(u32::from(self.to_height()) <= diff.to_u32() + 1)
457 }
458 None => Err(InvalidHeightError { chain_tip, utxo_mined_at }),
459 }
460 }
461}
462
463crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(NumberOfBlocks);
464
465impl From<u16> for NumberOfBlocks {
466 #[inline]
467 fn from(value: u16) -> Self { Self(value) }
468}
469
470parse_int::impl_parse_str_from_int_infallible!(NumberOfBlocks, u16, from);
471
472impl fmt::Display for NumberOfBlocks {
473 #[inline]
474 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
475}
476
477#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
481pub struct NumberOf512Seconds(u16);
482
483impl NumberOf512Seconds {
484 pub const ZERO: Self = Self(0);
486
487 pub const MIN: Self = Self::ZERO;
489
490 pub const MAX: Self = Self(u16::MAX);
492
493 #[inline]
498 pub const fn from_512_second_intervals(intervals: u16) -> Self { Self(intervals) }
499
500 #[inline]
502 #[must_use]
503 pub const fn to_512_second_intervals(self) -> u16 { self.0 }
504
505 #[inline]
512 #[rustfmt::skip] pub const fn from_seconds_floor(seconds: u32) -> Result<Self, TimeOverflowError> {
514 let interval = seconds / 512;
515 if interval <= u16::MAX as u32 { Ok(Self::from_512_second_intervals(interval as u16)) } else {
518 Err(TimeOverflowError { seconds })
519 }
520 }
521
522 #[inline]
529 #[rustfmt::skip] pub const fn from_seconds_ceil(seconds: u32) -> Result<Self, TimeOverflowError> {
531 if seconds <= u16::MAX as u32 * 512 {
532 let interval = seconds.div_ceil(512);
533 Ok(Self::from_512_second_intervals(interval as u16)) } else {
535 Err(TimeOverflowError { seconds })
536 }
537 }
538
539 #[inline]
541 pub const fn to_seconds(self) -> u32 { const_casts::u16_to_u32(self.0) * 512 }
542
543 #[inline]
550 pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
551 let block_count = parse_int::hex_u16_prefixed(s)?;
552 Ok(Self::from_512_second_intervals(block_count))
553 }
554
555 #[inline]
562 pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
563 let block_count = parse_int::hex_u16_unprefixed(s)?;
564 Ok(Self::from_512_second_intervals(block_count))
565 }
566
567 pub fn is_satisfied_by(
573 self,
574 chain_tip: crate::BlockMtp,
575 utxo_mined_at: crate::BlockMtp,
576 ) -> Result<bool, InvalidTimeError> {
577 chain_tip
578 .checked_sub(utxo_mined_at)
579 .ok_or(InvalidTimeError { chain_tip, utxo_mined_at })
580 .map(|diff| self.to_seconds() <= diff.to_u32())
581 }
582}
583
584crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(NumberOf512Seconds);
585
586parse_int::impl_parse_str_from_int_infallible!(NumberOf512Seconds, u16, from_512_second_intervals);
587
588impl fmt::Display for NumberOf512Seconds {
589 #[inline]
590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
591}
592
593#[cfg(feature = "arbitrary")]
594impl<'a> Arbitrary<'a> for LockTime {
595 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
596 let choice = u.int_in_range(0..=1)?;
597
598 match choice {
599 0 => Ok(Self::Blocks(NumberOfBlocks::arbitrary(u)?)),
600 _ => Ok(Self::Time(NumberOf512Seconds::arbitrary(u)?)),
601 }
602 }
603}
604
605#[cfg(feature = "arbitrary")]
606impl<'a> Arbitrary<'a> for NumberOfBlocks {
607 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
608 let choice = u.int_in_range(0..=2)?;
609
610 match choice {
611 0 => Ok(Self::MIN),
612 1 => Ok(Self::MAX),
613 _ => Ok(Self::from_height(u16::arbitrary(u)?)),
614 }
615 }
616}
617
618#[cfg(feature = "arbitrary")]
619impl<'a> Arbitrary<'a> for NumberOf512Seconds {
620 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
621 let choice = u.int_in_range(0..=2)?;
622
623 match choice {
624 0 => Ok(Self::MIN),
625 1 => Ok(Self::MAX),
626 _ => Ok(Self::from_512_second_intervals(u16::arbitrary(u)?)),
627 }
628 }
629}
630
631#[cfg(test)]
632mod tests {
633 #[cfg(feature = "alloc")]
634 use alloc::format;
635
636 use super::*;
637 use crate::{BlockHeight, BlockTime};
638
639 const MAXIMUM_ENCODABLE_SECONDS: u32 = u16::MAX as u32 * 512;
640
641 #[test]
642 #[cfg(feature = "alloc")]
643 fn display_and_alternate() {
644 let lock_by_height = LockTime::from_height(10);
645 let lock_by_time = LockTime::from_512_second_intervals(70);
646
647 assert_eq!(format!("{}", lock_by_height), "10");
648 assert_eq!(format!("{:#}", lock_by_height), "block-height 10");
649 assert!(!format!("{:?}", lock_by_height).is_empty());
650
651 assert_eq!(format!("{}", lock_by_time), "70");
652 assert_eq!(format!("{:#}", lock_by_time), "block-time 70 (512 second intervals)");
653 assert!(!format!("{:?}", lock_by_time).is_empty());
654 }
655
656 #[test]
657 fn from_seconds_ceil_and_floor() {
658 let time = 70 * 512 + 1;
659 let lock_by_time = LockTime::from_seconds_ceil(time).unwrap();
660 assert_eq!(lock_by_time, LockTime::from_512_second_intervals(71));
661
662 let lock_by_time = LockTime::from_seconds_floor(time).unwrap();
663 assert_eq!(lock_by_time, LockTime::from_512_second_intervals(70));
664
665 let mut max_time = 0xffff * 512;
666 assert_eq!(LockTime::from_seconds_ceil(max_time), LockTime::from_seconds_floor(max_time));
667 max_time += 512;
668 assert!(LockTime::from_seconds_ceil(max_time).is_err());
669 assert!(LockTime::from_seconds_floor(max_time).is_err());
670 }
671
672 #[test]
673 fn parses_correctly_to_height_or_time() {
674 let height1 = NumberOfBlocks::from(10);
675 let height2 = NumberOfBlocks::from(11);
676 let time1 = NumberOf512Seconds::from_512_second_intervals(70);
677 let time2 = NumberOf512Seconds::from_512_second_intervals(71);
678
679 let lock_by_height1 = LockTime::from(height1);
680 let lock_by_height2 = LockTime::from(height2);
681 let lock_by_time1 = LockTime::from(time1);
682 let lock_by_time2 = LockTime::from(time2);
683
684 assert!(lock_by_height1.is_block_height());
685 assert!(!lock_by_height1.is_block_time());
686
687 assert!(!lock_by_time1.is_block_height());
688 assert!(lock_by_time1.is_block_time());
689
690 assert!(lock_by_height1.is_same_unit(lock_by_height2));
692 assert!(!lock_by_height1.is_same_unit(lock_by_time1));
693 assert!(lock_by_time1.is_same_unit(lock_by_time2));
694 assert!(!lock_by_time1.is_same_unit(lock_by_height1));
695 }
696
697 #[test]
698 fn height_correctly_implies() {
699 let height = NumberOfBlocks::from(10);
700 let lock_by_height = LockTime::from(height);
701
702 assert!(!lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(9))));
703 assert!(lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(10))));
704 assert!(lock_by_height.is_implied_by(LockTime::from(NumberOfBlocks::from(11))));
705 }
706
707 #[test]
708 fn time_correctly_implies() {
709 let time = NumberOf512Seconds::from_512_second_intervals(70);
710 let lock_by_time = LockTime::from(time);
711
712 assert!(!lock_by_time
713 .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(69))));
714 assert!(lock_by_time
715 .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(70))));
716 assert!(lock_by_time
717 .is_implied_by(LockTime::from(NumberOf512Seconds::from_512_second_intervals(71))));
718 }
719
720 #[test]
721 fn sequence_correctly_implies() {
722 let height = NumberOfBlocks::from(10);
723 let time = NumberOf512Seconds::from_512_second_intervals(70);
724
725 let lock_by_height = LockTime::from(height);
726 let lock_by_time = LockTime::from(time);
727
728 let seq_height = Sequence::from(lock_by_height);
729 let seq_time = Sequence::from(lock_by_time);
730
731 assert!(lock_by_height.is_implied_by_sequence(seq_height));
732 assert!(!lock_by_height.is_implied_by_sequence(seq_time));
733
734 assert!(lock_by_time.is_implied_by_sequence(seq_time));
735 assert!(!lock_by_time.is_implied_by_sequence(seq_height));
736
737 let disabled_sequence = Sequence::from_consensus(1 << 31);
738 assert!(!lock_by_height.is_implied_by_sequence(disabled_sequence));
739 assert!(!lock_by_time.is_implied_by_sequence(disabled_sequence));
740 }
741
742 #[test]
743 fn incorrect_units_do_not_imply() {
744 let time = NumberOf512Seconds::from_512_second_intervals(70);
745 let height = NumberOfBlocks::from(10);
746
747 let lock_by_time = LockTime::from(time);
748 assert!(!lock_by_time.is_implied_by(LockTime::from(height)));
749 }
750
751 #[test]
752 fn consensus_round_trip() {
753 assert!(LockTime::from_consensus(1 << 31).is_err());
754 assert!(LockTime::from_consensus(1 << 30).is_ok());
755 assert_eq!(LockTime::from_consensus(65536), LockTime::from_consensus(0));
757
758 for val in [0u32, 1, 1000, 65535] {
759 let seq = Sequence::from_consensus(val);
760 let lt = LockTime::from_consensus(val).unwrap();
761 assert_eq!(lt.to_consensus_u32(), val);
762 assert_eq!(lt.to_sequence(), seq);
763 assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq);
764
765 let seq = Sequence::from_consensus(val + (1 << 22));
766 let lt = LockTime::from_consensus(val + (1 << 22)).unwrap();
767 assert_eq!(lt.to_consensus_u32(), val + (1 << 22));
768 assert_eq!(lt.to_sequence(), seq);
769 assert_eq!(LockTime::from_sequence(seq).unwrap().to_sequence(), seq);
770 }
771 }
772
773 #[test]
774 #[cfg(feature = "alloc")]
775 fn disabled_locktime_error() {
776 let disabled_sequence = Sequence::from_consensus(1 << 31);
777 let err = LockTime::try_from(disabled_sequence).unwrap_err();
778
779 assert_eq!(err.disabled_locktime_value(), 1 << 31);
780 assert!(!format!("{}", err).is_empty());
781 }
782
783 #[test]
784 #[cfg(feature = "alloc")]
785 fn incompatible_height_error() {
786 let mined_at = BlockHeight::from_u32(700_000);
788 let chain_tip = BlockHeight::from_u32(800_000);
789
790 let lock_by_time = LockTime::from_512_second_intervals(70); let err = lock_by_time.is_satisfied_by_height(chain_tip, mined_at).unwrap_err();
792
793 let expected_time = NumberOf512Seconds::from_512_second_intervals(70);
794 assert_eq!(
795 err,
796 IsSatisfiedByHeightError::Incompatible(IncompatibleHeightError(expected_time))
797 );
798 assert!(!format!("{}", err).is_empty());
799 }
800
801 #[test]
802 #[cfg(feature = "alloc")]
803 fn invalid_height_error() {
804 let mined_at = BlockHeight::from_u32(900_000);
806 let chain_tip = BlockHeight::from_u32(800_000);
807
808 let block_count = NumberOfBlocks::from_height(70); let err = block_count.is_satisfied_by(chain_tip, mined_at).unwrap_err();
810
811 assert!(matches!(err, InvalidHeightError { chain_tip: _, utxo_mined_at: _ }));
812 }
813
814 #[test]
815 #[cfg(feature = "alloc")]
816 fn incompatible_time_error() {
817 let mined_at = BlockMtp::from_u32(1_234_567_890);
819 let chain_tip = BlockMtp::from_u32(1_600_000_000);
820
821 let lock_by_height = LockTime::from_height(10); let err = lock_by_height.is_satisfied_by_time(chain_tip, mined_at).unwrap_err();
823
824 let expected_height = NumberOfBlocks::from(10);
825 assert_eq!(
826 err,
827 IsSatisfiedByTimeError::Incompatible(IncompatibleTimeError(expected_height))
828 );
829 assert!(!format!("{}", err).is_empty());
830 }
831
832 #[test]
833 #[cfg(feature = "alloc")]
834 fn invalid_time_error() {
835 let mined_at = BlockMtp::from_u32(1_734_567_890);
837 let chain_tip = BlockMtp::from_u32(1_600_000_000);
838
839 let time_interval = NumberOf512Seconds::from_512_second_intervals(10); let err = time_interval.is_satisfied_by(chain_tip, mined_at).unwrap_err();
841
842 assert!(matches!(err, InvalidTimeError { chain_tip: _, utxo_mined_at: _ }));
843 }
844
845 #[test]
846 fn test_locktime_chain_state() {
847 fn generate_timestamps(start: u32, step: u16) -> [BlockTime; 11] {
848 let mut timestamps = [BlockTime::from_u32(0); 11];
849 for (i, ts) in timestamps.iter_mut().enumerate() {
850 *ts = BlockTime::from_u32(start.saturating_sub((step * i as u16).into()));
851 }
852 timestamps
853 }
854
855 let timestamps: [BlockTime; 11] = generate_timestamps(1_600_000_000, 200);
856 let utxo_timestamps: [BlockTime; 11] = generate_timestamps(1_599_000_000, 200);
857
858 let chain_height = BlockHeight::from_u32(100);
859 let chain_mtp = BlockMtp::new(timestamps);
860 let utxo_height = BlockHeight::from_u32(80);
861 let utxo_mtp = BlockMtp::new(utxo_timestamps);
862
863 let lock1 = LockTime::Blocks(NumberOfBlocks::from(10));
864 assert!(lock1.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
865
866 let lock2 = LockTime::Blocks(NumberOfBlocks::from(21));
867 assert!(lock2.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
868
869 let lock3 = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(10));
870 assert!(lock3.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
871
872 let lock4 = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(20000));
873 assert!(!lock4.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
874
875 assert!(LockTime::ZERO
876 .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
877 .unwrap());
878 assert!(LockTime::from_512_second_intervals(0)
879 .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
880 .unwrap());
881
882 let lock6 = LockTime::from_seconds_floor(5000).unwrap();
883 assert!(lock6.is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp).unwrap());
884
885 let max_height_lock = LockTime::Blocks(NumberOfBlocks::MAX);
886 assert!(!max_height_lock
887 .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
888 .unwrap());
889
890 let max_time_lock = LockTime::Time(NumberOf512Seconds::MAX);
891 assert!(!max_time_lock
892 .is_satisfied_by(chain_height, chain_mtp, utxo_height, utxo_mtp)
893 .unwrap());
894
895 let max_chain_height = BlockHeight::from_u32(u32::MAX);
896 let max_chain_mtp = BlockMtp::new(generate_timestamps(u32::MAX, 100));
897 let max_utxo_height = BlockHeight::MAX;
898 let max_utxo_mtp = max_chain_mtp;
899 assert!(!max_height_lock
900 .is_satisfied_by(max_chain_height, max_chain_mtp, max_utxo_height, max_utxo_mtp)
901 .unwrap());
902 assert!(!max_time_lock
903 .is_satisfied_by(max_chain_height, max_chain_mtp, max_utxo_height, max_utxo_mtp)
904 .unwrap());
905 }
906
907 #[test]
908 fn sanity_check() {
909 assert_eq!(LockTime::from(NumberOfBlocks::MAX).to_consensus_u32(), u32::from(u16::MAX));
910 assert_eq!(
911 NumberOf512Seconds::from_512_second_intervals(100).to_512_second_intervals(),
912 100u16
913 );
914 assert_eq!(
915 LockTime::from(NumberOf512Seconds::from_512_second_intervals(100)).to_consensus_u32(),
916 4_194_404u32
917 ); assert_eq!(NumberOf512Seconds::from_512_second_intervals(1).to_seconds(), 512);
919 }
920
921 #[test]
922 fn from_512_second_intervals_roundtrip() {
923 let intervals = 100_u16;
924 let locktime = NumberOf512Seconds::from_512_second_intervals(intervals);
925 assert_eq!(locktime.to_512_second_intervals(), intervals);
926 }
927
928 #[test]
929 fn from_seconds_ceil_success() {
930 let actual = NumberOf512Seconds::from_seconds_ceil(100).unwrap();
931 let expected = NumberOf512Seconds(1_u16);
932 assert_eq!(actual, expected);
933 }
934
935 #[test]
936 fn from_seconds_ceil_with_maximum_encodable_seconds_success() {
937 let actual = NumberOf512Seconds::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS).unwrap();
938 let expected = NumberOf512Seconds(u16::MAX);
939 assert_eq!(actual, expected);
940 }
941
942 #[test]
943 fn from_seconds_ceil_causes_time_overflow_error() {
944 let result = NumberOf512Seconds::from_seconds_ceil(MAXIMUM_ENCODABLE_SECONDS + 1);
945 assert!(result.is_err());
946 }
947
948 #[test]
949 fn from_seconds_floor_success() {
950 let actual = NumberOf512Seconds::from_seconds_floor(100).unwrap();
951 let expected = NumberOf512Seconds(0_u16);
952 assert_eq!(actual, expected);
953 }
954
955 #[test]
956 fn from_seconds_floor_with_exact_interval() {
957 let actual = NumberOf512Seconds::from_seconds_floor(512).unwrap();
958 let expected = NumberOf512Seconds(1_u16);
959 assert_eq!(actual, expected);
960 }
961
962 #[test]
963 fn from_seconds_floor_with_maximum_encodable_seconds_success() {
964 let actual =
965 NumberOf512Seconds::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 511).unwrap();
966 let expected = NumberOf512Seconds(u16::MAX);
967 assert_eq!(actual, expected);
968 }
969
970 #[test]
971 fn from_seconds_floor_causes_time_overflow_error() {
972 let result = NumberOf512Seconds::from_seconds_floor(MAXIMUM_ENCODABLE_SECONDS + 512);
973 assert!(result.is_err());
974 }
975
976 fn generate_timestamps(start: u32, step: u16) -> [BlockTime; 11] {
977 let mut timestamps = [BlockTime::from_u32(0); 11];
978 for (i, ts) in timestamps.iter_mut().enumerate() {
979 *ts = BlockTime::from_u32(start.saturating_sub((step * i as u16).into()));
980 }
981 timestamps
982 }
983
984 #[test]
985 fn test_time_chain_state() {
986 use crate::BlockMtp;
987
988 let timestamps: [BlockTime; 11] = generate_timestamps(1_600_000_000, 200);
989 let utxo_timestamps: [BlockTime; 11] = generate_timestamps(1_599_000_000, 200);
990
991 let timestamps2: [BlockTime; 11] = generate_timestamps(1_599_995_119, 200);
992 let utxo_timestamps2: [BlockTime; 11] = generate_timestamps(1_599_990_000, 200);
993
994 let timestamps3: [BlockTime; 11] = generate_timestamps(1_600_050_000, 200);
995 let utxo_timestamps3: [BlockTime; 11] = generate_timestamps(1_599_990_000, 200);
996
997 let time_lock = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(10));
1000 let chain_state1 = BlockMtp::new(timestamps);
1001 let utxo_state1 = BlockMtp::new(utxo_timestamps);
1002 assert!(time_lock.is_satisfied_by_time(chain_state1, utxo_state1).unwrap());
1003
1004 let chain_state2 = BlockMtp::new(timestamps2);
1006 let utxo_state2 = BlockMtp::new(utxo_timestamps2);
1007 assert!(!time_lock.is_satisfied_by_time(chain_state2, utxo_state2).unwrap());
1008
1009 let larger_lock = LockTime::Time(NumberOf512Seconds::from_512_second_intervals(100));
1011 let chain_state3 = BlockMtp::new(timestamps3);
1012 let utxo_state3 = BlockMtp::new(utxo_timestamps3);
1013 assert!(larger_lock.is_satisfied_by_time(chain_state3, utxo_state3).unwrap());
1014
1015 let max_time_lock = LockTime::Time(NumberOf512Seconds::MAX);
1017 let chain_state4 = BlockMtp::new(timestamps);
1018 let utxo_state4 = BlockMtp::new(utxo_timestamps);
1019 assert!(!max_time_lock.is_satisfied_by_time(chain_state4, utxo_state4).unwrap());
1020 }
1021
1022 #[test]
1023 fn test_height_chain_state() {
1024 let height_lock = LockTime::Blocks(NumberOfBlocks(10));
1025
1026 let chain_state1 = BlockHeight::from_u32(89);
1028 let utxo_state1 = BlockHeight::from_u32(80);
1029 assert!(height_lock.is_satisfied_by_height(chain_state1, utxo_state1).unwrap());
1030
1031 let chain_state2 = BlockHeight::from_u32(88);
1033 let utxo_state2 = BlockHeight::from_u32(80);
1034 assert!(!height_lock.is_satisfied_by_height(chain_state2, utxo_state2).unwrap());
1035
1036 let max_height_lock = LockTime::Blocks(NumberOfBlocks::MAX);
1038 let chain_state3 = BlockHeight::from_u32(1000);
1039 let utxo_state3 = BlockHeight::from_u32(80);
1040 assert!(!max_height_lock.is_satisfied_by_height(chain_state3, utxo_state3).unwrap());
1041 }
1042
1043 #[test]
1044 fn test_max_height_satisfaction() {
1045 let mined_at = BlockHeight::from_u32(u32::MIN);
1047 let chain_tip = BlockHeight::from_u32(u32::MAX);
1048
1049 let block_height = NumberOfBlocks::from(10); assert!(block_height.is_satisfied_by(chain_tip, mined_at).unwrap());
1051 }
1052}