bitcoin-units 0.3.0

Basic Bitcoin numeric units such as amount
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
// SPDX-License-Identifier: CC0-1.0

//! Block height and interval types.
//!
//! These types are thin wrappers around `u32`, no invariants implemented or implied.
//!
//! These are general types for abstracting over block heights, they are not designed to use with
//! lock times. If you are creating lock times you should be using the
//! [`locktime::absolute::Height`] and [`locktime::relative::NumberOfBlocks`] types.
//!
//! The difference between these types and the locktime types is that these types are thin wrappers
//! whereas the locktime types contain more complex locktime specific abstractions.

#[cfg(feature = "encoding")]
use core::convert::Infallible;
use core::{fmt, ops};

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
#[cfg(feature = "encoding")]
use internals::write_err;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[cfg(doc)]
use crate::locktime;
use crate::locktime::{absolute, relative};

macro_rules! impl_u32_wrapper {
    {
        $(#[$($type_attrs:tt)*])*
        $type_vis:vis struct $newtype:ident($inner_vis:vis u32);
    } => {
        $(#[$($type_attrs)*])*
        $type_vis struct $newtype($inner_vis u32);

        impl fmt::Display for $newtype {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
        }

        crate::parse_int::impl_parse_str_from_int_infallible!($newtype, u32, from);

        impl From<u32> for $newtype {
            fn from(inner: u32) -> Self { Self::from_u32(inner) }
        }

        impl From<$newtype> for u32 {
            fn from(height: $newtype) -> Self { height.to_u32() }
        }

        #[cfg(feature = "serde")]
        impl Serialize for $newtype {
            #[inline]
            fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                u32::serialize(&self.to_u32(), s)
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> Deserialize<'de> for $newtype {
            #[inline]
            fn deserialize<D>(d: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                Ok(Self::from_u32(u32::deserialize(d)?))
            }
        }

        #[cfg(feature = "arbitrary")]
        impl<'a> Arbitrary<'a> for $newtype {
            fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
                let choice = u.int_in_range(0..=2)?;
                match choice {
                    0 => Ok(Self::ZERO),
                    1 => Ok(Self::MIN),
                    2 => Ok(Self::MAX),
                    _ => Ok(Self::from_u32(u32::arbitrary(u)?)),
                }
            }
        }
    }
}

impl_u32_wrapper! {
    /// A block height. Zero denotes the genesis block.
    ///
    /// This type is not meant for constructing height based timelocks. It is a general purpose
    /// blockheight abstraction. For locktimes please see [`locktime::absolute::Height`].
    ///
    /// This is a thin wrapper around a `u32` that may take on all values of a `u32`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct BlockHeight(u32);
}

impl BlockHeight {
    /// Block height 0, the genesis block.
    pub const ZERO: Self = Self(0);

    /// The minimum block height (0), the genesis block.
    pub const MIN: Self = Self::ZERO;

    /// The maximum block height.
    pub const MAX: Self = Self(u32::MAX);

    /// Constructs a new block height from a `u32`.
    pub const fn from_u32(inner: u32) -> Self { Self(inner) }

    /// Returns block height as a `u32`.
    pub const fn to_u32(self) -> u32 { self.0 }

    /// Attempt to subtract two [`BlockHeight`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_sub(self, other: Self) -> Option<BlockHeightInterval> {
        self.to_u32().checked_sub(other.to_u32()).map(BlockHeightInterval)
    }

    /// Attempt to add an interval to this [`BlockHeight`], returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_add(self, other: BlockHeightInterval) -> Option<Self> {
        self.to_u32().checked_add(other.to_u32()).map(Self)
    }

    /// Saturating integer addition.
    ///
    /// Computes self + rhs, saturating at `BlockHeight::MAX` instead of overflowing.
    #[inline]
    #[must_use]
    pub const fn saturating_add(self, rhs: BlockHeightInterval) -> Self {
        Self::from_u32(self.to_u32().saturating_add(rhs.to_u32()))
    }

    /// Saturating integer subtraction.
    ///
    /// Computes self - rhs, saturating at `BlockHeight::MIN` instead of overflowing.
    #[inline]
    #[must_use]
    pub const fn saturating_sub(self, rhs: BlockHeightInterval) -> Self {
        Self::from_u32(self.to_u32().saturating_sub(rhs.to_u32()))
    }
}

crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(BlockHeight);

impl From<absolute::Height> for BlockHeight {
    /// Converts a [`locktime::absolute::Height`] to a [`BlockHeight`].
    ///
    /// An absolute locktime block height has a maximum value of [`absolute::LOCK_TIME_THRESHOLD`]
    /// minus one, while [`BlockHeight`] may take the full range of `u32`.
    fn from(h: absolute::Height) -> Self { Self::from_u32(h.to_u32()) }
}

impl TryFrom<BlockHeight> for absolute::Height {
    type Error = absolute::ConversionError;

    /// Converts a [`BlockHeight`] to a [`locktime::absolute::Height`].
    ///
    /// An absolute locktime block height has a maximum value of [`absolute::LOCK_TIME_THRESHOLD`]
    /// minus one, while [`BlockHeight`] may take the full range of `u32`.
    fn try_from(h: BlockHeight) -> Result<Self, Self::Error> { Self::from_u32(h.to_u32()) }
}

#[cfg(feature = "encoding")]
encoding::encoder_newtype_exact! {
    /// The encoder for the [`BlockHeight`] type.
    pub struct BlockHeightEncoder<'e>(encoding::ArrayEncoder<4>);
}

#[cfg(feature = "encoding")]
impl encoding::Encodable for BlockHeight {
    type Encoder<'e> = BlockHeightEncoder<'e>;
    fn encoder(&self) -> Self::Encoder<'_> {
        BlockHeightEncoder::new(encoding::ArrayEncoder::without_length_prefix(
            self.to_u32().to_le_bytes(),
        ))
    }
}

/// The decoder for the [`BlockHeight`] type.
#[cfg(feature = "encoding")]
pub struct BlockHeightDecoder(encoding::ArrayDecoder<4>);

#[cfg(feature = "encoding")]
impl Default for BlockHeightDecoder {
    fn default() -> Self { Self::new() }
}

#[cfg(feature = "encoding")]
impl BlockHeightDecoder {
    /// Constructs a new [`BlockHeight`] decoder.
    pub const fn new() -> Self { Self(encoding::ArrayDecoder::new()) }
}

#[cfg(feature = "encoding")]
impl encoding::Decoder for BlockHeightDecoder {
    type Output = BlockHeight;
    type Error = BlockHeightDecoderError;

    #[inline]
    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
        self.0.push_bytes(bytes).map_err(BlockHeightDecoderError)
    }

    #[inline]
    fn end(self) -> Result<Self::Output, Self::Error> {
        let n = u32::from_le_bytes(self.0.end().map_err(BlockHeightDecoderError)?);
        Ok(BlockHeight::from_u32(n))
    }

    #[inline]
    fn read_limit(&self) -> usize { self.0.read_limit() }
}

#[cfg(feature = "encoding")]
impl encoding::Decodable for BlockHeight {
    type Decoder = BlockHeightDecoder;
    fn decoder() -> Self::Decoder { BlockHeightDecoder(encoding::ArrayDecoder::<4>::new()) }
}

/// An error consensus decoding an `BlockHeight`.
#[cfg(feature = "encoding")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockHeightDecoderError(encoding::UnexpectedEofError);

#[cfg(feature = "encoding")]
impl From<Infallible> for BlockHeightDecoderError {
    fn from(never: Infallible) -> Self { match never {} }
}

#[cfg(feature = "encoding")]
impl fmt::Display for BlockHeightDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_err!(f, "block height decoder error"; self.0)
    }
}

#[cfg(all(feature = "std", feature = "encoding"))]
impl std::error::Error for BlockHeightDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}

impl_u32_wrapper! {
    /// An unsigned block interval.
    ///
    /// Block interval is an integer type representing a difference between the heights of two blocks.
    ///
    /// This type is not meant for constructing relative height based timelocks. It is a general
    /// purpose block interval abstraction. For locktimes please see [`locktime::relative::NumberOfBlocks`].
    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct BlockHeightInterval(u32);
}

impl BlockHeightInterval {
    /// Block interval 0.
    pub const ZERO: Self = Self(0);

    /// The minimum block interval, equivalent to `Self::ZERO`.
    pub const MIN: Self = Self::ZERO;

    /// The maximum block interval.
    pub const MAX: Self = Self(u32::MAX);

    /// Constructs a new block interval from a `u32`.
    pub const fn from_u32(inner: u32) -> Self { Self(inner) }

    /// Returns block interval as a `u32`.
    pub const fn to_u32(self) -> u32 { self.0 }

    /// Attempt to subtract two [`BlockHeightInterval`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        self.to_u32().checked_sub(other.to_u32()).map(Self)
    }

    /// Attempt to add two [`BlockHeightInterval`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_add(self, other: Self) -> Option<Self> {
        self.to_u32().checked_add(other.to_u32()).map(Self)
    }
}

crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(BlockHeightInterval);

impl From<relative::NumberOfBlocks> for BlockHeightInterval {
    /// Converts a [`locktime::relative::NumberOfBlocks`] to a [`BlockHeightInterval`].
    ///
    /// A relative locktime block height has a maximum value of `u16::MAX` where as a
    /// [`BlockHeightInterval`] is a thin wrapper around a `u32`, the two types are not interchangeable.
    fn from(h: relative::NumberOfBlocks) -> Self { Self::from_u32(h.to_height().into()) }
}

impl TryFrom<BlockHeightInterval> for relative::NumberOfBlocks {
    type Error = TooBigForRelativeHeightError;

    /// Converts a [`BlockHeightInterval`] to a [`locktime::relative::NumberOfBlocks`].
    ///
    /// A relative locktime block height has a maximum value of `u16::MAX` where as a
    /// [`BlockHeightInterval`] is a thin wrapper around a `u32`, the two types are not interchangeable.
    fn try_from(h: BlockHeightInterval) -> Result<Self, Self::Error> {
        u16::try_from(h.to_u32())
            .map(Self::from)
            .map_err(|_| TooBigForRelativeHeightError(h.into()))
    }
}

impl_u32_wrapper! {
    /// The median timestamp of 11 consecutive blocks.
    ///
    /// This type is not meant for constructing time-based timelocks. It is a general purpose
    /// MTP abstraction. For locktimes please see [`locktime::absolute::MedianTimePast`].
    ///
    /// This is a thin wrapper around a `u32` that may take on all values of a `u32`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct BlockMtp(u32);
}

impl BlockMtp {
    /// Block MTP 0.
    ///
    /// Since MTP is a timestamp, 0 is before Bitcoin was invented. This const may still be useful
    /// for some use cases e.g., folding a sum of intervals.
    pub const ZERO: Self = Self(0);

    /// The minimum block MTP, equivalent to `Self::ZERO`.
    pub const MIN: Self = Self::ZERO;

    /// The maximum block MTP.
    pub const MAX: Self = Self(u32::MAX);

    /// Constructs a new block MTP from a `u32`.
    pub const fn from_u32(inner: u32) -> Self { Self(inner) }

    /// Returns block MTP as a `u32`.
    pub const fn to_u32(self) -> u32 { self.0 }

    /// Constructs a [`BlockMtp`] by computing the median‐time‐past from the last 11 block timestamps
    ///
    /// Because block timestamps are not monotonic, this function internally sorts them;
    /// it is therefore not important what order they appear in the array; use whatever
    /// is most convenient.
    pub fn new(mut timestamps: [crate::BlockTime; 11]) -> Self {
        timestamps.sort_unstable();
        Self::from_u32(u32::from(timestamps[5]))
    }

    /// Attempt to subtract two [`BlockMtp`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_sub(self, other: Self) -> Option<BlockMtpInterval> {
        self.to_u32().checked_sub(other.to_u32()).map(BlockMtpInterval)
    }

    /// Attempt to add an interval to this [`BlockMtp`], returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_add(self, other: BlockMtpInterval) -> Option<Self> {
        self.to_u32().checked_add(other.to_u32()).map(Self)
    }
}

crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(BlockMtp);

impl From<absolute::MedianTimePast> for BlockMtp {
    /// Converts a [`locktime::absolute::MedianTimePast`] to a [`BlockMtp`].
    ///
    /// An absolute locktime MTP has a minimum value of [`absolute::LOCK_TIME_THRESHOLD`],
    /// while [`BlockMtp`] may take the full range of `u32`.
    fn from(h: absolute::MedianTimePast) -> Self { Self::from_u32(h.to_u32()) }
}

impl TryFrom<BlockMtp> for absolute::MedianTimePast {
    type Error = absolute::ConversionError;

    /// Converts a [`BlockHeight`] to a [`locktime::absolute::Height`].
    ///
    /// An absolute locktime MTP has a minimum value of [`absolute::LOCK_TIME_THRESHOLD`],
    /// while [`BlockMtp`] may take the full range of `u32`.
    fn try_from(h: BlockMtp) -> Result<Self, Self::Error> { Self::from_u32(h.to_u32()) }
}

impl_u32_wrapper! {
    /// An unsigned difference between two [`BlockMtp`]s.
    ///
    /// This type is not meant for constructing time-based timelocks. It is a general purpose
    /// MTP abstraction. For locktimes please see [`locktime::relative::NumberOf512Seconds`].
    ///
    /// This is a thin wrapper around a `u32` that may take on all values of a `u32`.
    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct BlockMtpInterval(u32);
}

impl BlockMtpInterval {
    /// Block MTP interval 0.
    pub const ZERO: Self = Self(0);

    /// The minimum block MTP interval, equivalent to `Self::ZERO`.
    pub const MIN: Self = Self::ZERO;

    /// The maximum block MTP interval.
    pub const MAX: Self = Self(u32::MAX);

    /// Constructs a new block MTP interval from a `u32`.
    pub const fn from_u32(inner: u32) -> Self { Self(inner) }

    /// Returns block MTP interval as a `u32`.
    pub const fn to_u32(self) -> u32 { self.0 }

    /// Converts a [`BlockMtpInterval`] to a [`locktime::relative::NumberOf512Seconds`], rounding down.
    ///
    /// Relative timelock MTP intervals have a resolution of 512 seconds, while
    /// [`BlockMtpInterval`], like all block timestamp types, has a one-second resolution.
    ///
    /// # Errors
    ///
    /// Errors if the MTP is out-of-range (in excess of 512 times `u16::MAX` seconds, or about
    /// 388 days) for a time-based relative locktime.
    #[inline]
    pub const fn to_relative_mtp_interval_floor(
        self,
    ) -> Result<relative::NumberOf512Seconds, relative::TimeOverflowError> {
        relative::NumberOf512Seconds::from_seconds_floor(self.to_u32())
    }

    /// Converts a [`BlockMtpInterval`] to a [`locktime::relative::NumberOf512Seconds`], rounding up.
    ///
    /// Relative timelock MTP intervals have a resolution of 512 seconds, while
    /// [`BlockMtpInterval`], like all block timestamp types, has a one-second resolution.
    ///
    /// # Errors
    ///
    /// Errors if the MTP is out-of-range (in excess of 512 times `u16::MAX` seconds, or about
    /// 388 days) for a time-based relative locktime.
    #[inline]
    pub const fn to_relative_mtp_interval_ceil(
        self,
    ) -> Result<relative::NumberOf512Seconds, relative::TimeOverflowError> {
        relative::NumberOf512Seconds::from_seconds_ceil(self.to_u32())
    }

    /// Attempt to subtract two [`BlockMtpInterval`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        self.to_u32().checked_sub(other.to_u32()).map(Self)
    }

    /// Attempt to add two [`BlockMtpInterval`]s, returning `None` if overflow occurred.
    #[must_use]
    pub fn checked_add(self, other: Self) -> Option<Self> {
        self.to_u32().checked_add(other.to_u32()).map(Self)
    }
}

crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(BlockMtpInterval);

impl From<relative::NumberOf512Seconds> for BlockMtpInterval {
    /// Converts a [`locktime::relative::NumberOf512Seconds`] to a [`BlockMtpInterval `].
    ///
    /// A relative locktime MTP interval has a resolution of 512 seconds, and a maximum value
    /// of `u16::MAX` 512-second intervals. [`BlockMtpInterval`] may take the full range of
    /// `u32`.
    fn from(h: relative::NumberOf512Seconds) -> Self { Self::from_u32(h.to_seconds()) }
}

/// Error returned when the block interval is too big to be used as a relative lock time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TooBigForRelativeHeightError(u32);

impl fmt::Display for TooBigForRelativeHeightError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "block interval is too big to be used as a relative lock time: {} (max: {})",
            self.0,
            relative::NumberOfBlocks::MAX
        )
    }
}

#[cfg(feature = "std")]
impl std::error::Error for TooBigForRelativeHeightError {}

crate::internal_macros::impl_op_for_references! {
    // height - height = interval
    impl ops::Sub<BlockHeight> for BlockHeight {
        type Output = BlockHeightInterval;

        fn sub(self, rhs: BlockHeight) -> Self::Output {
            let interval = self.to_u32() - rhs.to_u32();
            BlockHeightInterval::from_u32(interval)
        }
    }

    // height + interval = height
    impl ops::Add<BlockHeightInterval> for BlockHeight {
        type Output = BlockHeight;

        fn add(self, rhs: BlockHeightInterval) -> Self::Output {
            let height = self.to_u32() + rhs.to_u32();
            BlockHeight::from_u32(height)
        }
    }

    // height - interval = height
    impl ops::Sub<BlockHeightInterval> for BlockHeight {
        type Output = BlockHeight;

        fn sub(self, rhs: BlockHeightInterval) -> Self::Output {
            let height = self.to_u32() - rhs.to_u32();
            BlockHeight::from_u32(height)
        }
    }

    // interval + interval = interval
    impl ops::Add<BlockHeightInterval> for BlockHeightInterval {
        type Output = BlockHeightInterval;

        fn add(self, rhs: BlockHeightInterval) -> Self::Output {
            let height = self.to_u32() + rhs.to_u32();
            BlockHeightInterval::from_u32(height)
        }
    }

    // interval - interval = interval
    impl ops::Sub<BlockHeightInterval> for BlockHeightInterval {
        type Output = BlockHeightInterval;

        fn sub(self, rhs: BlockHeightInterval) -> Self::Output {
            let height = self.to_u32() - rhs.to_u32();
            BlockHeightInterval::from_u32(height)
        }
    }

    // height - height = interval
    impl ops::Sub<BlockMtp> for BlockMtp {
        type Output = BlockMtpInterval;

        fn sub(self, rhs: BlockMtp) -> Self::Output {
            let interval = self.to_u32() - rhs.to_u32();
            BlockMtpInterval::from_u32(interval)
        }
    }

    // height + interval = height
    impl ops::Add<BlockMtpInterval> for BlockMtp {
        type Output = BlockMtp;

        fn add(self, rhs: BlockMtpInterval) -> Self::Output {
            let height = self.to_u32() + rhs.to_u32();
            BlockMtp::from_u32(height)
        }
    }

    // height - interval = height
    impl ops::Sub<BlockMtpInterval> for BlockMtp {
        type Output = BlockMtp;

        fn sub(self, rhs: BlockMtpInterval) -> Self::Output {
            let height = self.to_u32() - rhs.to_u32();
            BlockMtp::from_u32(height)
        }
    }

    // interval + interval = interval
    impl ops::Add<BlockMtpInterval> for BlockMtpInterval {
        type Output = BlockMtpInterval;

        fn add(self, rhs: BlockMtpInterval) -> Self::Output {
            let height = self.to_u32() + rhs.to_u32();
            BlockMtpInterval::from_u32(height)
        }
    }

    // interval - interval = interval
    impl ops::Sub<BlockMtpInterval> for BlockMtpInterval {
        type Output = BlockMtpInterval;

        fn sub(self, rhs: BlockMtpInterval) -> Self::Output {
            let height = self.to_u32() - rhs.to_u32();
            BlockMtpInterval::from_u32(height)
        }
    }
}

crate::internal_macros::impl_add_assign!(BlockHeightInterval);
crate::internal_macros::impl_sub_assign!(BlockHeightInterval);
crate::internal_macros::impl_add_assign!(BlockMtpInterval);
crate::internal_macros::impl_sub_assign!(BlockMtpInterval);

impl core::iter::Sum for BlockHeightInterval {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        let sum = iter.map(Self::to_u32).sum();
        Self::from_u32(sum)
    }
}

impl<'a> core::iter::Sum<&'a Self> for BlockHeightInterval {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'a Self>,
    {
        let sum = iter.map(|interval| interval.to_u32()).sum();
        Self::from_u32(sum)
    }
}

impl core::iter::Sum for BlockMtpInterval {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        let sum = iter.map(Self::to_u32).sum();
        Self::from_u32(sum)
    }
}

impl<'a> core::iter::Sum<&'a Self> for BlockMtpInterval {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'a Self>,
    {
        let sum = iter.map(|interval| interval.to_u32()).sum();
        Self::from_u32(sum)
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "encoding")]
    use encoding::{Decoder as _, UnexpectedEofError};

    use super::*;
    use crate::relative::{NumberOf512Seconds, TimeOverflowError};

    #[test]
    fn sanity_check() {
        let height: u32 = BlockHeight(100).into();
        assert_eq!(height, 100);

        let interval: u32 = BlockHeightInterval(100).into();
        assert_eq!(interval, 100);

        let interval_from_height: BlockHeightInterval =
            relative::NumberOfBlocks::from(10u16).into();
        assert_eq!(interval_from_height.to_u32(), 10u32);

        let invalid_height_greater =
            relative::NumberOfBlocks::try_from(BlockHeightInterval(u32::from(u16::MAX) + 1));
        assert!(invalid_height_greater.is_err());

        let valid_height =
            relative::NumberOfBlocks::try_from(BlockHeightInterval(u32::from(u16::MAX)));
        assert!(valid_height.is_ok());
    }

    // These tests are supposed to comprise an exhaustive list of available operations.
    #[test]
    fn all_available_ops() {
        // height - height = interval
        assert!(BlockHeight(10) - BlockHeight(7) == BlockHeightInterval(3));

        // height + interval = height
        assert!(BlockHeight(100) + BlockHeightInterval(1) == BlockHeight(101));

        // height - interval == height
        assert!(BlockHeight(100) - BlockHeightInterval(1) == BlockHeight(99));

        // interval + interval = interval
        assert!(BlockHeightInterval(1) + BlockHeightInterval(2) == BlockHeightInterval(3));

        // interval - interval = interval
        assert!(BlockHeightInterval(10) - BlockHeightInterval(7) == BlockHeightInterval(3));

        // Sum for BlockHeightInterval by reference and by value
        assert!(
            [BlockHeightInterval(1), BlockHeightInterval(2), BlockHeightInterval(3)]
                .iter()
                .sum::<BlockHeightInterval>()
                == BlockHeightInterval(6)
        );
        assert!(
            [BlockHeightInterval(4), BlockHeightInterval(5), BlockHeightInterval(6)]
                .into_iter()
                .sum::<BlockHeightInterval>()
                == BlockHeightInterval(15)
        );

        // Sum for BlockMtpInterval by reference and by value
        assert!(
            [BlockMtpInterval(1), BlockMtpInterval(2), BlockMtpInterval(3)]
                .iter()
                .sum::<BlockMtpInterval>()
                == BlockMtpInterval(6)
        );
        assert!(
            [BlockMtpInterval(4), BlockMtpInterval(5), BlockMtpInterval(6)]
                .into_iter()
                .sum::<BlockMtpInterval>()
                == BlockMtpInterval(15)
        );

        // interval += interval
        let mut int = BlockHeightInterval(1);
        int += BlockHeightInterval(2);
        assert_eq!(int, BlockHeightInterval(3));

        // interval -= interval
        let mut int = BlockHeightInterval(10);
        int -= BlockHeightInterval(7);
        assert_eq!(int, BlockHeightInterval(3));
    }

    #[test]
    fn block_height_checked() {
        let a = BlockHeight(10);
        let b = BlockHeight(5);
        assert_eq!(a.checked_sub(b), Some(BlockHeightInterval(5)));
        assert_eq!(a.checked_add(BlockHeightInterval(5)), Some(BlockHeight(15)));
        assert_eq!(a.checked_sub(BlockHeight(11)), None);
        assert_eq!(a.checked_add(BlockHeightInterval(u32::MAX - 5)), None);
    }

    #[test]
    fn block_height_interval_checked() {
        let a = BlockHeightInterval(10);
        let b = BlockHeightInterval(5);
        assert_eq!(a.checked_sub(b), Some(BlockHeightInterval(5)));
        assert_eq!(a.checked_add(b), Some(BlockHeightInterval(15)));
        assert_eq!(a.checked_sub(BlockHeightInterval(11)), None);
        assert_eq!(a.checked_add(BlockHeightInterval(u32::MAX - 5)), None);
    }

    #[test]
    fn block_mtp_interval_checked() {
        let a = BlockMtpInterval(10);
        let b = BlockMtpInterval(5);
        assert_eq!(a.checked_sub(b), Some(BlockMtpInterval(5)));
        assert_eq!(a.checked_add(b), Some(BlockMtpInterval(15)));
        assert_eq!(a.checked_sub(BlockMtpInterval(11)), None);
        assert_eq!(a.checked_add(BlockMtpInterval(u32::MAX - 5)), None);
    }

    #[test]
    fn block_mtp_checked() {
        let a = BlockMtp(10);
        let b = BlockMtp(5);
        assert_eq!(a.checked_sub(b), Some(BlockMtpInterval(5)));
        assert_eq!(a.checked_add(BlockMtpInterval(5)), Some(BlockMtp(15)));
        assert_eq!(a.checked_sub(BlockMtp(11)), None);
        assert_eq!(a.checked_add(BlockMtpInterval(u32::MAX - 5)), None);
    }

    #[test]
    fn block_mtp_interval_from_number_of_512seconds() {
        let n = NumberOf512Seconds::from_seconds_floor(0).unwrap();
        let interval = BlockMtpInterval::from(n);
        assert_eq!(interval, BlockMtpInterval(0));
        let n = NumberOf512Seconds::from_seconds_floor(1024).unwrap();
        let interval = BlockMtpInterval::from(n);
        assert_eq!(interval, BlockMtpInterval(1024));
    }

    #[test]
    fn block_mtp_interval_to_relative_mtp_floor() {
        let time = NumberOf512Seconds::from_512_second_intervals(0);
        let interval = BlockMtpInterval::from_u32(0);
        assert_eq!(interval.to_relative_mtp_interval_floor().unwrap(), time);

        let time = NumberOf512Seconds::from_512_second_intervals(1);
        let interval = BlockMtpInterval::from_u32(1023);
        assert_eq!(interval.to_relative_mtp_interval_floor().unwrap(), time); // Should floor down to 1
        assert_ne!(interval.to_relative_mtp_interval_ceil().unwrap(), time); // Should ceil up to 2

        // Check overflow limit
        let max_time = NumberOf512Seconds::from_512_second_intervals(u16::MAX);
        let max_seconds = u32::from(u16::MAX) * 512 + 511;

        let interval = BlockMtpInterval::from_u32(max_seconds);
        assert_eq!(interval.to_relative_mtp_interval_floor().unwrap(), max_time);
        let interval = BlockMtpInterval::from_u32(max_seconds + 1);
        assert_eq!(
            interval.to_relative_mtp_interval_floor().unwrap_err(),
            TimeOverflowError { seconds: max_seconds + 1 }
        );
    }

    #[test]
    fn block_mtp_interval_to_relative_mtp_ceil() {
        let time = NumberOf512Seconds::from_512_second_intervals(0);
        let interval = BlockMtpInterval::from_u32(0);
        assert_eq!(interval.to_relative_mtp_interval_ceil().unwrap(), time);

        let time = NumberOf512Seconds::from_512_second_intervals(2);
        let interval = BlockMtpInterval::from_u32(1023);
        assert_eq!(interval.to_relative_mtp_interval_ceil().unwrap(), time); // Should ceil up to 2
        assert_ne!(interval.to_relative_mtp_interval_floor().unwrap(), time); // Should floor down to 1

        // Check overflow limit
        let max_time = NumberOf512Seconds::from_512_second_intervals(u16::MAX);
        let max_seconds = u32::from(u16::MAX) * 512;

        let interval = BlockMtpInterval::from_u32(max_seconds);
        assert_eq!(interval.to_relative_mtp_interval_ceil().unwrap(), max_time);
        let interval = BlockMtpInterval::from_u32(max_seconds + 1);
        assert_eq!(
            interval.to_relative_mtp_interval_ceil().unwrap_err(),
            TimeOverflowError { seconds: max_seconds + 1 }
        );
    }

    #[test]
    #[cfg(feature = "encoding")]
    fn block_height_decoding_error() {
        let bytes = [0xff, 0xff, 0xff]; // 3 bytes is an EOF error

        let mut decoder = BlockHeightDecoder::default();
        assert!(decoder.push_bytes(&mut bytes.as_slice()).unwrap());

        let error = decoder.end().unwrap_err();
        assert!(matches!(error, BlockHeightDecoderError(UnexpectedEofError { .. })));
    }

    // Test a impl_u32_wrapper! type serde serialisation roundtrip.
    macro_rules! serde_roundtrip_test {
        { $test_name:tt, $typ:ident } => {
            #[test]
            #[cfg(feature = "serde")]
            fn $test_name() {
                let t = $typ(1_654_321);

                let json = serde_json::to_string(&t).unwrap();
                assert_eq!(json, "1654321"); // ASCII number representation

                let roundtrip = serde_json::from_str::<$typ>(&json).unwrap();
                assert_eq!(t, roundtrip);
            }
        }
    }

    serde_roundtrip_test!(block_height_serde_round_trip, BlockHeight);
    serde_roundtrip_test!(block_height_interval_serde_round_trip, BlockHeightInterval);
    serde_roundtrip_test!(block_mtp_serde_round_trip, BlockMtp);
    serde_roundtrip_test!(block_mtp_interval_serde_round_trip, BlockMtpInterval);

    #[test]
    fn block_height_saturating_add() {
        // Normal addition
        assert_eq!(BlockHeight(100).saturating_add(BlockHeightInterval(50)), BlockHeight(150),);
        assert_eq!(BlockHeight::ZERO.saturating_add(BlockHeightInterval(1)), BlockHeight(1),);

        // Saturates at MAX instead of overflowing
        assert_eq!(BlockHeight::MAX.saturating_add(BlockHeightInterval(1)), BlockHeight::MAX,);
        assert_eq!(BlockHeight::MAX.saturating_add(BlockHeightInterval(100)), BlockHeight::MAX,);
        assert_eq!(
            BlockHeight(u32::MAX - 10).saturating_add(BlockHeightInterval(20)),
            BlockHeight::MAX,
        );

        // Adding zero
        assert_eq!(BlockHeight(500).saturating_add(BlockHeightInterval::ZERO), BlockHeight(500),);
    }

    #[test]
    fn block_height_saturating_sub() {
        // Normal subtraction
        assert_eq!(BlockHeight(100).saturating_sub(BlockHeightInterval(50)), BlockHeight(50),);
        assert_eq!(BlockHeight(100).saturating_sub(BlockHeightInterval(100)), BlockHeight(0),);

        // Saturates at MIN instead of underflowing
        assert_eq!(BlockHeight::MIN.saturating_sub(BlockHeightInterval(1)), BlockHeight::MIN,);
        assert_eq!(BlockHeight::ZERO.saturating_sub(BlockHeightInterval(100)), BlockHeight::ZERO,);
        assert_eq!(BlockHeight(10).saturating_sub(BlockHeightInterval(20)), BlockHeight::ZERO,);

        // Subtracting zero
        assert_eq!(BlockHeight(500).saturating_sub(BlockHeightInterval::ZERO), BlockHeight(500),);
    }
}