Skip to main content

bitcoin_units/
pow.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Proof-of-work related integer types.
4
5use core::fmt::{self, Write as _};
6use core::ops::{Add, Div, Mul, Not, Rem, Shl, Shr, Sub};
7
8#[cfg(feature = "arbitrary")]
9use arbitrary::{Arbitrary, Unstructured};
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Serialize};
12
13use crate::internal_macros::impl_fmt_traits_for_u32_wrapper;
14use crate::parse_int::{self, PrefixedHexError, UnprefixedHexError};
15
16#[rustfmt::skip]                // Keep public re-exports separate.
17#[cfg(feature = "encoding")]
18#[doc(no_inline)]
19pub use self::error::CompactTargetDecoderError;
20#[doc(no_inline)]
21pub use self::error::{ParseTargetError, ParseWorkError};
22
23/// Implement traits and methods shared by `Target` and `Work`.
24macro_rules! do_impl {
25    ($ty:ident, $err_ty:ident) => {
26        impl $ty {
27            #[doc = "Constructs a new `"]
28            #[doc = stringify!($ty)]
29            #[doc = "` from a prefixed hex string.\n"]
30            #[doc = "\n# Errors\n"]
31            #[doc = "\n - If the input string does not contain a `0x` (or `0X`) prefix."]
32            #[doc = "\n - If the input string is not a valid hex encoding of a `"]
33            #[doc = stringify!($ty)]
34            #[doc = "`."]
35            pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
36                Ok($ty(U256::from_hex(s)?))
37            }
38
39            #[doc = "Constructs a new `"]
40            #[doc = stringify!($ty)]
41            #[doc = "` from an unprefixed hex string.\n"]
42            #[doc = "\n# Errors\n"]
43            #[doc = "\n - If the input string contains a `0x` (or `0X`) prefix."]
44            #[doc = "\n - If the input string is not a valid hex encoding of a `"]
45            #[doc = stringify!($ty)]
46            #[doc = "`."]
47            pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
48                Ok($ty(U256::from_unprefixed_hex(s)?))
49            }
50
51            #[doc = "Constructs `"]
52            #[doc = stringify!($ty)]
53            #[doc = "` from a big-endian byte array."]
54            #[inline]
55            pub fn from_be_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_be_bytes(bytes)) }
56
57            #[doc = "Constructs `"]
58            #[doc = stringify!($ty)]
59            #[doc = "` from a little-endian byte array."]
60            #[inline]
61            pub fn from_le_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_le_bytes(bytes)) }
62
63            #[doc = "Converts `"]
64            #[doc = stringify!($ty)]
65            #[doc = "` to a big-endian byte array."]
66            #[inline]
67            pub fn to_be_bytes(self) -> [u8; 32] { self.0.to_be_bytes() }
68
69            #[doc = "Converts `"]
70            #[doc = stringify!($ty)]
71            #[doc = "` to a little-endian byte array."]
72            #[inline]
73            pub fn to_le_bytes(self) -> [u8; 32] { self.0.to_le_bytes() }
74        }
75
76        impl fmt::Display for $ty {
77            #[inline]
78            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
79                fmt::Display::fmt(&self.0, f)
80            }
81        }
82
83        impl core::str::FromStr for $ty {
84            type Err = $err_ty;
85
86            #[inline]
87            fn from_str(s: &str) -> Result<Self, Self::Err> {
88                U256::from_str(s).map($ty).map_err($err_ty)
89            }
90        }
91    };
92}
93
94/// A 256 bit integer representing work.
95///
96/// Work is a measure of how difficult it is to find a hash below a given [`Target`].
97#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
98#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
99pub struct Work(U256);
100
101impl Work {
102    /// Converts this [`Work`] to [`Target`].
103    pub fn to_target(self) -> Target { Target(self.0.inverse()) }
104}
105
106do_impl!(Work, ParseWorkError);
107impl_fmt_traits_for_u32_wrapper!(Work);
108
109impl Add for Work {
110    type Output = Self;
111    fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
112}
113
114impl Sub for Work {
115    type Output = Self;
116    fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
117}
118
119/// A 256 bit integer representing target.
120///
121/// The SHA-256 hash of a block's header must be lower than or equal to the current target for the
122/// block to be accepted by the network. The lower the target, the more difficult it is to generate
123/// a block. (See also [`Work`].)
124///
125/// [`Target`] does not limit its value to the maximum attainable value for any network when it
126/// is constructed. If you need to enforce that invariant, you should compare the constructed value
127/// against the required network's `MAX_ATTAINABLE_*` target constant.
128///
129/// ref: <https://en.bitcoin.it/wiki/Target>
130#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
132pub struct Target(U256);
133
134impl Target {
135    /// When parsing nBits, Bitcoin Core converts a negative target threshold into a target of zero.
136    pub const ZERO: Self = Self(U256::ZERO);
137
138    /// The maximum possible target.
139    ///
140    /// This value is used to calculate difficulty, which is defined as how difficult the current
141    /// target makes it to find a block relative to how difficult it would be at the highest
142    /// possible target. Remember highest target == lowest difficulty.
143    ///
144    /// ref: <https://en.bitcoin.it/wiki/Target>
145    // In Bitcoind this is ~(u256)0 >> 32 stored as a floating-point type so it gets truncated, hence
146    // the low 208 bits are all zero.
147    pub const MAX: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
148
149    /// The maximum **attainable** target value on mainnet.
150    ///
151    /// Not all target values are attainable because consensus code uses the compact format to
152    /// represent targets (see [`CompactTarget`]).
153    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
154    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L88
155    pub const MAX_ATTAINABLE_MAINNET: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
156
157    /// The maximum **attainable** target value on testnet.
158    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
159    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L208
160    pub const MAX_ATTAINABLE_TESTNET: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
161
162    /// The maximum **attainable** target value on regtest.
163    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
164    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L411
165    pub const MAX_ATTAINABLE_REGTEST: Self = Self(U256(0x7FFF_FF00u128 << 96, 0));
166
167    /// The maximum **attainable** target value on signet.
168    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
169    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L348
170    pub const MAX_ATTAINABLE_SIGNET: Self = Self(U256(0x0377_ae00 << 80, 0));
171
172    /// Computes the [`Target`] value from a compact representation.
173    ///
174    /// ref: <https://developer.bitcoin.org/reference/block_chain.html#target-nbits>
175    pub fn from_compact(c: CompactTarget) -> Self {
176        let bits = c.to_consensus();
177        // This is a floating-point "compact" encoding originally used by
178        // OpenSSL, which satoshi put into consensus code, so we're stuck
179        // with it. The exponent needs to have 3 subtracted from it, hence
180        // this goofy decoding code. 3 is due to 3 bytes in the mantissa.
181        let (mant, expt) = {
182            let unshifted_expt = bits >> 24;
183            if unshifted_expt <= 3 {
184                ((bits & 0xFF_FFFF) >> (8 * (3 - unshifted_expt as usize)), 0)
185            } else {
186                (bits & 0xFF_FFFF, 8 * ((bits >> 24) - 3))
187            }
188        };
189
190        // The mantissa is signed but may not be negative.
191        if mant > 0x7F_FFFF {
192            Self::ZERO
193        } else {
194            Self(U256::from(mant) << expt)
195        }
196    }
197
198    /// Computes the compact value from a [`Target`] representation.
199    ///
200    /// The compact form is by definition lossy, this means that
201    /// `t == Target::from_compact(t.to_compact_lossy())` does not always hold.
202    pub fn to_compact_lossy(self) -> CompactTarget {
203        let mut size = self.0.bits().div_ceil(8);
204        let mut compact = if size <= 3 {
205            (self.0.low_u64() << (8 * (3 - size))) as u32
206        } else {
207            let bn = self.0 >> (8 * (size - 3));
208            bn.low_u32()
209        };
210
211        if (compact & 0x0080_0000) != 0 {
212            compact >>= 8;
213            size += 1;
214        }
215
216        CompactTarget::from_consensus(compact | (size << 24))
217    }
218
219    /// Converts this [`Target`] to [`Work`].
220    ///
221    /// "Work" is defined as the work done to mine a block with this target value (recorded in the
222    /// block header in compact form as nBits). This is not the same as the difficulty to mine a
223    /// block with this target (see `Self::difficulty`).
224    pub fn to_work(self) -> Work { Work(self.0.inverse()) }
225}
226do_impl!(Target, ParseTargetError);
227impl_fmt_traits_for_u32_wrapper!(Target);
228
229/// Encoding of 256-bit target as 32-bit float.
230///
231/// This is used to encode a target into the block header. Satoshi made this part of consensus code
232/// in the original version of Bitcoin, likely copying an idea from OpenSSL.
233///
234/// OpenSSL's bignum (BN) type has an encoding, which is even called "compact" as in bitcoin, which
235/// is exactly this format.
236///
237/// # Note on order/equality
238///
239/// Usage of the ordering and equality traits for this type may be surprising. Converting between
240/// `CompactTarget` and `Target` is lossy *in both directions* (there are multiple `CompactTarget`
241/// values that map to the same `Target` value). Ordering and equality for this type are defined in
242/// terms of the underlying `u32`.
243#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
245pub struct CompactTarget(u32);
246
247impl CompactTarget {
248    /// Constructs a new [`CompactTarget`] from a consensus encoded `u32`.
249    #[inline]
250    pub fn from_consensus(bits: u32) -> Self { Self(bits) }
251
252    /// Returns the consensus encoded `u32` representation of this [`CompactTarget`].
253    #[inline]
254    pub const fn to_consensus(self) -> u32 { self.0 }
255
256    /// Constructs a new `CompactTarget` from a prefixed hex string.
257    ///
258    /// # Errors
259    ///
260    /// - If the input string does not contain a `0x` (or `0X`) prefix.
261    /// - If the input string is not a valid hex encoding of a `u32`.
262    #[inline]
263    pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError>
264    where
265        Self: Sized,
266    {
267        let target = parse_int::hex_u32_prefixed(s)?;
268        Ok(Self::from_consensus(target))
269    }
270
271    /// Constructs a new `CompactTarget` from an unprefixed hex string.
272    ///
273    /// # Errors
274    ///
275    /// - If the input string contains a `0x` (or `0X`) prefix.
276    /// - If the input string is not a valid hex encoding of a `u32`.
277    #[inline]
278    pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError>
279    where
280        Self: Sized,
281    {
282        let target = parse_int::hex_u32_unprefixed(s)?;
283        Ok(Self::from_consensus(target))
284    }
285}
286
287crate::internal_macros::impl_fmt_traits_for_u32_wrapper!(CompactTarget);
288
289impl fmt::Display for CompactTarget {
290    #[inline]
291    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
292}
293
294parse_int::impl_parse_str_from_int_infallible!(CompactTarget, u32, from_consensus);
295
296impl From<CompactTarget> for Target {
297    fn from(c: CompactTarget) -> Self { Self::from_compact(c) }
298}
299
300#[cfg(feature = "encoding")]
301impl encoding::Encode for CompactTarget {
302    type Encoder<'e> = CompactTargetEncoder<'e>;
303    #[inline]
304    fn encoder(&self) -> Self::Encoder<'_> {
305        CompactTargetEncoder::new(encoding::ArrayEncoder::without_length_prefix(
306            self.to_consensus().to_le_bytes(),
307        ))
308    }
309}
310
311#[cfg(feature = "encoding")]
312impl encoding::Decode for CompactTarget {
313    type Decoder = CompactTargetDecoder;
314}
315
316#[cfg(feature = "encoding")]
317encoding::encoder_newtype_exact! {
318    /// The encoder for the [`CompactTarget`] type.
319    #[derive(Debug, Clone)]
320    pub struct CompactTargetEncoder<'e>(encoding::ArrayEncoder<4>);
321}
322
323#[cfg(feature = "encoding")]
324crate::decoder_newtype! {
325    /// The decoder for the [`CompactTarget`] type.
326    #[derive(Debug, Clone)]
327    pub struct CompactTargetDecoder(encoding::ArrayDecoder<4>);
328
329    /// Constructs a new [`CompactTarget`] decoder.
330    pub const fn new() -> Self { Self(encoding::ArrayDecoder::new()) }
331
332    fn end(result: Result<[u8; 4], encoding::UnexpectedEofError>) -> Result<CompactTarget, CompactTargetDecoderError> {
333        let value = result.map_err(CompactTargetDecoderError)?;
334        let n = u32::from_le_bytes(value);
335        Ok(CompactTarget::from_consensus(n))
336    }
337}
338
339/// Error types for proof-of-work related integer types.
340pub mod error {
341    use core::convert::Infallible;
342    use core::fmt;
343
344    use internals::write_err;
345
346    use super::ParseU256Error;
347
348    /// An error consensus decoding an `CompactTarget`.
349    #[derive(Debug, Clone, PartialEq, Eq)]
350    #[cfg(feature = "encoding")]
351    pub struct CompactTargetDecoderError(pub(super) encoding::UnexpectedEofError);
352
353    #[cfg(feature = "encoding")]
354    impl From<Infallible> for CompactTargetDecoderError {
355        fn from(never: Infallible) -> Self { match never {} }
356    }
357
358    #[cfg(feature = "encoding")]
359    impl fmt::Display for CompactTargetDecoderError {
360        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
361            write_err!(f, "compact target decoder error"; self.0)
362        }
363    }
364
365    #[cfg(feature = "std")]
366    #[cfg(feature = "encoding")]
367    impl std::error::Error for CompactTargetDecoderError {
368        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
369    }
370
371    /// Error returned when parsing a [`Work`] from a string.
372    ///
373    /// [`Work`]: super::Work
374    #[derive(Debug, Clone, PartialEq, Eq)]
375    pub struct ParseWorkError(pub(super) ParseU256Error);
376
377    impl From<Infallible> for ParseWorkError {
378        fn from(never: Infallible) -> Self { match never {} }
379    }
380
381    impl fmt::Display for ParseWorkError {
382        #[inline]
383        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
384            write_err!(f, "work parse error"; self.0)
385        }
386    }
387
388    #[cfg(feature = "std")]
389    impl std::error::Error for ParseWorkError {
390        #[inline]
391        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
392    }
393
394    /// Error returned when parsing a [`Target`] from a string.
395    ///
396    /// [`Target`]: super::Target
397    #[derive(Debug, Clone, PartialEq, Eq)]
398    pub struct ParseTargetError(pub(super) ParseU256Error);
399
400    impl From<Infallible> for ParseTargetError {
401        fn from(never: Infallible) -> Self { match never {} }
402    }
403
404    impl fmt::Display for ParseTargetError {
405        #[inline]
406        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407            write_err!(f, "target parse error"; self.0)
408        }
409    }
410
411    #[cfg(feature = "std")]
412    impl std::error::Error for ParseTargetError {
413        #[inline]
414        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
415    }
416}
417
418#[cfg(feature = "arbitrary")]
419impl<'a> Arbitrary<'a> for CompactTarget {
420    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
421        Ok(Self::from_consensus(u.arbitrary()?))
422    }
423}
424
425include!("../include/u256.rs");
426
427impl U256 {
428    /// Constructs a new `U256` from a prefixed hex string.
429    fn from_hex(s: &str) -> Result<Self, PrefixedHexError> { parse_int::hex_u256_prefixed(s) }
430
431    /// Constructs a new `U256` from an unprefixed hex string.
432    fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
433        parse_int::hex_u256_unprefixed(s)
434    }
435}
436
437macro_rules! impl_hex {
438    ($hex:path, $lookup:expr) => {
439        impl $hex for U256 {
440            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
441                if f.alternate() {
442                    f.write_str("0x")?;
443                }
444
445                #[allow(clippy::indexing_slicing)]
446                for byte in self.to_be_bytes() {
447                    let upper_idx = ((byte & 0xf0) >> 4) as usize;
448                    let lower_idx = (byte & 0xf) as usize;
449                    f.write_char($lookup[upper_idx])?;
450                    f.write_char($lookup[lower_idx])?;
451                }
452                Ok(())
453            }
454        }
455    };
456}
457impl_hex!(
458    fmt::LowerHex,
459    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
460);
461impl_hex!(
462    fmt::UpperHex,
463    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
464);
465
466#[cfg(feature = "serde")]
467impl serde::Serialize for U256 {
468    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
469    where
470        S: serde::Serializer,
471    {
472        struct DisplayHex(U256);
473
474        impl fmt::Display for DisplayHex {
475            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:x}", self.0) }
476        }
477
478        if serializer.is_human_readable() {
479            serializer.collect_str(&DisplayHex(*self))
480        } else {
481            let bytes = self.to_be_bytes();
482            serializer.serialize_bytes(&bytes)
483        }
484    }
485}
486
487#[cfg(feature = "serde")]
488impl<'de> serde::Deserialize<'de> for U256 {
489    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
490        use serde::de;
491
492        if d.is_human_readable() {
493            struct HexVisitor;
494
495            impl de::Visitor<'_> for HexVisitor {
496                type Value = U256;
497
498                fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
499                    f.write_str("a 32 byte ASCII hex string")
500                }
501
502                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
503                where
504                    E: de::Error,
505                {
506                    if s.len() != 64 {
507                        return Err(de::Error::invalid_length(s.len(), &self));
508                    }
509
510                    U256::from_unprefixed_hex(s)
511                        .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))
512                }
513            }
514            d.deserialize_str(HexVisitor)
515        } else {
516            struct BytesVisitor;
517
518            impl serde::de::Visitor<'_> for BytesVisitor {
519                type Value = U256;
520
521                fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
522                    f.write_str("a sequence of bytes")
523                }
524
525                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
526                where
527                    E: serde::de::Error,
528                {
529                    let b = v.try_into().map_err(|_| de::Error::invalid_length(v.len(), &self))?;
530                    Ok(U256::from_be_bytes(b))
531                }
532            }
533
534            d.deserialize_bytes(BytesVisitor)
535        }
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    #[cfg(feature = "alloc")]
542    use alloc::format;
543    #[cfg(feature = "alloc")]
544    #[cfg(feature = "encoding")]
545    use alloc::string::ToString;
546
547    #[cfg(feature = "encoding")]
548    use encoding::Decoder as _;
549
550    use super::*;
551
552    impl U256 {
553        fn bit_at(&self, index: usize) -> bool {
554            assert!(index <= 255, "index out of bounds");
555
556            let word = if index < 128 { self.1 } else { self.0 };
557            (word & (1 << (index % 128))) != 0
558        }
559
560        /// Constructs a new U256 from a big-endian array of u64's
561        fn from_array(a: [u64; 4]) -> Self {
562            let mut ret = Self::ZERO;
563            ret.0 = (u128::from(a[0]) << 64) ^ u128::from(a[1]);
564            ret.1 = (u128::from(a[2]) << 64) ^ u128::from(a[3]);
565            ret
566        }
567    }
568
569    #[test]
570    fn u256_num_bits() {
571        assert_eq!(U256::from(255_u64).bits(), 8);
572        assert_eq!(U256::from(256_u64).bits(), 9);
573        assert_eq!(U256::from(300_u64).bits(), 9);
574        assert_eq!(U256::from(60000_u64).bits(), 16);
575        assert_eq!(U256::from(70000_u64).bits(), 17);
576
577        let u = U256::from(u128::MAX) << 1;
578        assert_eq!(u.bits(), 129);
579
580        // Try to read the following lines out loud quickly
581        let mut shl = U256::from(70000_u64);
582        shl = shl << 100;
583        assert_eq!(shl.bits(), 117);
584        shl = shl << 100;
585        assert_eq!(shl.bits(), 217);
586        shl = shl << 100;
587        assert_eq!(shl.bits(), 0);
588    }
589
590    #[test]
591    fn u256_bit_at() {
592        assert!(!U256::from(10_u64).bit_at(0));
593        assert!(U256::from(10_u64).bit_at(1));
594        assert!(!U256::from(10_u64).bit_at(2));
595        assert!(U256::from(10_u64).bit_at(3));
596        assert!(!U256::from(10_u64).bit_at(4));
597
598        let u = U256(0xa000_0000_0000_0000_0000_0000_0000_0000, 0);
599        assert!(u.bit_at(255));
600        assert!(!u.bit_at(254));
601        assert!(u.bit_at(253));
602        assert!(!u.bit_at(252));
603    }
604
605    #[test]
606    #[cfg(feature = "alloc")]
607    #[cfg(feature = "serde")]
608    fn u256_serde() {
609        let check = |uint, hex| {
610            let json = format!("\"{}\"", hex);
611            assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
612            assert_eq!(::serde_json::from_str::<U256>(&json).unwrap(), uint);
613
614            let bin_encoded = bincode::serialize(&uint).unwrap();
615            let bin_decoded: U256 = bincode::deserialize(&bin_encoded).unwrap();
616            assert_eq!(bin_decoded, uint);
617        };
618
619        check(U256::ZERO, "0000000000000000000000000000000000000000000000000000000000000000");
620        check(
621            U256::from(0xDEAD_BEEF_u32),
622            "00000000000000000000000000000000000000000000000000000000deadbeef",
623        );
624        check(
625            U256::from_array([0xdd44, 0xcc33, 0xbb22, 0xaa11]),
626            "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
627        );
628        check(U256::MAX, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
629        check(
630            U256(
631                0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
632                0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
633            ),
634            "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
635        );
636
637        assert!(::serde_json::from_str::<U256>(
638            "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
639        )
640        .is_err()); // invalid char
641        assert!(::serde_json::from_str::<U256>(
642            "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
643        )
644        .is_err()); // invalid length
645        assert!(::serde_json::from_str::<U256>(
646            "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
647        )
648        .is_err()); // invalid length
649    }
650
651    #[test]
652    #[cfg(feature = "alloc")]
653    fn u256_lower_hex() {
654        assert_eq!(
655            format!("{:x}", U256::from(0xDEAD_BEEF_u64)),
656            "00000000000000000000000000000000000000000000000000000000deadbeef",
657        );
658        assert_eq!(
659            format!("{:#x}", U256::from(0xDEAD_BEEF_u64)),
660            "0x00000000000000000000000000000000000000000000000000000000deadbeef",
661        );
662        assert_eq!(
663            format!("{:x}", U256::MAX),
664            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
665        );
666        assert_eq!(
667            format!("{:#x}", U256::MAX),
668            "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
669        );
670    }
671
672    #[test]
673    #[cfg(feature = "alloc")]
674    fn u256_upper_hex() {
675        assert_eq!(
676            format!("{:X}", U256::from(0xDEAD_BEEF_u64)),
677            "00000000000000000000000000000000000000000000000000000000DEADBEEF",
678        );
679        assert_eq!(
680            format!("{:#X}", U256::from(0xDEAD_BEEF_u64)),
681            "0x00000000000000000000000000000000000000000000000000000000DEADBEEF",
682        );
683        assert_eq!(
684            format!("{:X}", U256::MAX),
685            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
686        );
687        assert_eq!(
688            format!("{:#X}", U256::MAX),
689            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
690        );
691    }
692
693    #[test]
694    #[cfg(feature = "alloc")]
695    fn u256_display() {
696        assert_eq!(format!("{}", U256::from(100_u32)), "100",);
697        assert_eq!(format!("{}", U256::ZERO), "0",);
698        assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
699        assert_eq!(
700            format!("{}", U256::MAX),
701            "115792089237316195423570985008687907853269984665640564039457584007913129639935",
702        );
703    }
704
705    macro_rules! check_format {
706        ($($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
707            $(
708                #[test]
709                #[cfg(feature = "alloc")]
710                fn $test_name() {
711                    assert_eq!(format!($format_string, U256::from($val)), $expected);
712                }
713            )*
714        }
715    }
716    check_format! {
717        check_fmt_0, 0_u32, "{}", "0";
718        check_fmt_1, 0_u32, "{:2}", " 0";
719        check_fmt_2, 0_u32, "{:02}", "00";
720
721        check_fmt_3, 1_u32, "{}", "1";
722        check_fmt_4, 1_u32, "{:2}", " 1";
723        check_fmt_5, 1_u32, "{:02}", "01";
724
725        check_fmt_10, 10_u32, "{}", "10";
726        check_fmt_11, 10_u32, "{:2}", "10";
727        check_fmt_12, 10_u32, "{:02}", "10";
728        check_fmt_13, 10_u32, "{:3}", " 10";
729        check_fmt_14, 10_u32, "{:03}", "010";
730
731        check_fmt_20, 1_u32, "{:<2}", "1 ";
732        check_fmt_21, 1_u32, "{:<02}", "01";
733        check_fmt_22, 1_u32, "{:>2}", " 1"; // This is default but check it anyways.
734        check_fmt_23, 1_u32, "{:>02}", "01";
735        check_fmt_24, 1_u32, "{:^3}", " 1 ";
736        check_fmt_25, 1_u32, "{:^03}", "001";
737        // Sanity check, for integral types precision is ignored.
738        check_fmt_30, 0_u32, "{:.1}", "0";
739        check_fmt_31, 0_u32, "{:4.1}", "   0";
740        check_fmt_32, 0_u32, "{:04.1}", "0000";
741
742        check_fmt_33, 0_u32, "{:b}", "0";
743        check_fmt_34, 0_u32, "{:#b}", "0b0";
744        check_fmt_35, 42_u32, "{:b}", "101010";
745        check_fmt_36, 42_u32, "{:#b}", "0b101010";
746        check_fmt_37, 42_u32, "{:8b}", "  101010";
747        check_fmt_38, 42_u32, "{:08b}", "00101010";
748        check_fmt_39, 42_u32, "{:<8b}", "101010  ";
749        check_fmt_40, 42_u32, "{:>8b}", "  101010";
750        check_fmt_41, 42_u32, "{:^8b}", " 101010 ";
751        check_fmt_42, 42_u32, "{:#10b}", "  0b101010";
752        check_fmt_43, 42_u32, "{:#010b}", "0b00101010";
753        check_fmt_44, 42_u32, "{:.4b}", "101010";
754        check_fmt_45, 42_u32, "{:10.4b}", "    101010";
755
756        check_fmt_46, 0_u32, "{:o}", "0";
757        check_fmt_47, 0_u32, "{:#o}", "0o0";
758        check_fmt_48, 42_u32, "{:o}", "52";
759        check_fmt_49, 42_u32, "{:#o}", "0o52";
760        check_fmt_50, 42_u32, "{:4o}", "  52";
761        check_fmt_51, 42_u32, "{:04o}", "0052";
762        check_fmt_52, 42_u32, "{:<4o}", "52  ";
763        check_fmt_53, 42_u32, "{:>4o}", "  52";
764        check_fmt_54, 42_u32, "{:^4o}", " 52 ";
765        check_fmt_55, 42_u32, "{:#6o}", "  0o52";
766        check_fmt_56, 42_u32, "{:#06o}", "0o0052";
767        check_fmt_57, 42_u32, "{:.4o}", "52";
768        check_fmt_58, 42_u32, "{:6.4o}", "    52";
769    }
770
771    #[test]
772    #[cfg(feature = "alloc")]
773    fn u256_comp() {
774        let small = U256::from_array([0, 0, 0, 10]);
775        let big = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]);
776        let bigger = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x9C8C_3EE7_0C64_4118]);
777        let biggest = U256::from_array([1, 0, 0x0209_E737_8231_E632, 0x5C8C_3EE7_0C64_4118]);
778
779        assert!(small < big);
780        assert!(big < bigger);
781        assert!(bigger < biggest);
782        assert!(bigger <= biggest);
783        assert!(biggest <= biggest);
784        assert!(bigger >= big);
785        assert!(bigger >= small);
786        assert!(small <= small);
787    }
788
789    const WANT: U256 =
790        U256(0x1bad_cafe_dead_beef_deaf_babe_2bed_feed, 0xbaad_f00d_defa_ceda_11fe_d2ba_d1c0_ffe0);
791
792    #[rustfmt::skip]
793    const BE_BYTES: [u8; 32] = [
794        0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed,
795        0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba, 0xd1, 0xc0, 0xff, 0xe0,
796    ];
797
798    #[rustfmt::skip]
799    const LE_BYTES: [u8; 32] = [
800        0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0, 0xad, 0xba,
801        0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca, 0xad, 0x1b,
802    ];
803
804    // Sanity check that we have the bytes in the correct big-endian order.
805    #[test]
806    fn sanity_be_bytes() {
807        let mut out = [0_u8; 32];
808        out[..16].copy_from_slice(&WANT.0.to_be_bytes());
809        out[16..].copy_from_slice(&WANT.1.to_be_bytes());
810        assert_eq!(out, BE_BYTES);
811    }
812
813    // Sanity check that we have the bytes in the correct little-endian order.
814    #[test]
815    fn sanity_le_bytes() {
816        let mut out = [0_u8; 32];
817        out[..16].copy_from_slice(&WANT.1.to_le_bytes());
818        out[16..].copy_from_slice(&WANT.0.to_le_bytes());
819        assert_eq!(out, LE_BYTES);
820    }
821
822    #[test]
823    fn u256_to_be_bytes() {
824        assert_eq!(WANT.to_be_bytes(), BE_BYTES);
825    }
826
827    #[test]
828    fn u256_from_be_bytes() {
829        assert_eq!(U256::from_be_bytes(BE_BYTES), WANT);
830    }
831
832    #[test]
833    fn u256_to_le_bytes() {
834        assert_eq!(WANT.to_le_bytes(), LE_BYTES);
835    }
836
837    #[test]
838    fn u256_from_le_bytes() {
839        assert_eq!(U256::from_le_bytes(LE_BYTES), WANT);
840    }
841
842    #[test]
843    fn u256_from_u8() {
844        let u = U256::from(0xbe_u8);
845        assert_eq!(u, U256(0, 0xbe));
846    }
847
848    #[test]
849    fn u256_from_u16() {
850        let u = U256::from(0xbeef_u16);
851        assert_eq!(u, U256(0, 0xbeef));
852    }
853
854    #[test]
855    fn u256_from_u32() {
856        let u = U256::from(0xdead_beef_u32);
857        assert_eq!(u, U256(0, 0xdead_beef));
858    }
859
860    #[test]
861    fn u256_from_u64() {
862        let u = U256::from(0xdead_beef_cafe_babe_u64);
863        assert_eq!(u, U256(0, 0xdead_beef_cafe_babe));
864    }
865
866    #[test]
867    fn u256_from_u128() {
868        let u = U256::from(0xdead_beef_cafe_babe_0123_4567_89ab_cdefu128);
869        assert_eq!(u, U256(0, 0xdead_beef_cafe_babe_0123_4567_89ab_cdef));
870    }
871
872    macro_rules! test_from_unsigned_integer_type {
873        ($($test_name:ident, $ty:ident);* $(;)?) => {
874            $(
875                #[test]
876                fn $test_name() {
877                    // Internal representation is big-endian.
878                    let want = U256(0, 0xAB);
879
880                    let x = 0xAB as $ty;
881                    let got = U256::from(x);
882
883                    assert_eq!(got, want);
884                }
885            )*
886        }
887    }
888    test_from_unsigned_integer_type! {
889        from_unsigned_integer_type_u8, u8;
890        from_unsigned_integer_type_u16, u16;
891        from_unsigned_integer_type_u32, u32;
892        from_unsigned_integer_type_u64, u64;
893        from_unsigned_integer_type_u128, u128;
894    }
895
896    #[test]
897    fn u256_from_be_array_u64() {
898        let array = [
899            0x1bad_cafe_dead_beef,
900            0xdeaf_babe_2bed_feed,
901            0xbaad_f00d_defa_ceda,
902            0x11fe_d2ba_d1c0_ffe0,
903        ];
904
905        let uint = U256::from_array(array);
906        assert_eq!(uint, WANT);
907    }
908
909    #[test]
910    fn u256_shift_left() {
911        let u = U256::from(1_u32);
912        assert_eq!(u << 0, u);
913        assert_eq!(u << 1, U256::from(2_u64));
914        assert_eq!(u << 63, U256::from(0x8000_0000_0000_0000_u64));
915        assert_eq!(u << 64, U256::from_array([0, 0, 0x0000_0000_0000_0001, 0]));
916        assert_eq!(u << 127, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
917        assert_eq!(u << 128, U256(1, 0));
918
919        let x = U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000);
920        assert_eq!(x << 1, U256(1, 0));
921    }
922
923    #[test]
924    fn u256_shift_right() {
925        let u = U256(1, 0);
926        assert_eq!(u >> 0, u);
927        assert_eq!(u >> 1, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
928        assert_eq!(u >> 127, U256(0, 2));
929        assert_eq!(u >> 128, U256(0, 1));
930    }
931
932    #[test]
933    fn u256_arithmetic() {
934        let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
935        let copy = init;
936
937        let add = init.wrapping_add(copy);
938        assert_eq!(add, U256::from_array([0, 0, 1, 0xBD5B_7DDF_BD5B_7DDE]));
939        // Bitshifts
940        let shl = add << 88;
941        assert_eq!(shl, U256::from_array([0, 0x01BD_5B7D, 0xDFBD_5B7D_DE00_0000, 0]));
942        let shr = shl >> 40;
943        assert_eq!(shr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0000]));
944        // Increment
945        let mut incr = shr;
946        incr = incr.wrapping_inc();
947        assert_eq!(incr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0001]));
948        // Subtraction
949        let sub = incr.wrapping_sub(init);
950        assert_eq!(sub, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
951        // Multiplication
952        let (mult, _) = sub.mul_u64(300);
953        assert_eq!(mult, U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]));
954        // Division
955        assert_eq!(U256::from(105_u32) / U256::from(5_u32), U256::from(21_u32));
956        let div = mult / U256::from(300_u32);
957        assert_eq!(div, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
958
959        assert_eq!(U256::from(105_u32) % U256::from(5_u32), U256::ZERO);
960        assert_eq!(U256::from(35_498_456_u32) % U256::from(3_435_u32), U256::from(1_166_u32));
961        let rem_src = mult.wrapping_mul(U256::from(39842_u32)).wrapping_add(U256::from(9054_u32));
962        assert_eq!(rem_src % U256::from(39_842_u32), U256::from(9_054_u32));
963    }
964
965    #[test]
966    fn u256_bit_inversion() {
967        let v = U256(1, 0);
968        let want = U256(
969            0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe,
970            0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff,
971        );
972        assert_eq!(!v, want);
973
974        let v = U256(0x0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c, 0xeeee_eeee_eeee_eeee);
975        let want = U256(
976            0xf3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3,
977            0xffff_ffff_ffff_ffff_1111_1111_1111_1111,
978        );
979        assert_eq!(!v, want);
980    }
981
982    #[test]
983    fn u256_mul_u64_by_one() {
984        let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
985        assert_eq!(v, v.mul_u64(1_u64).0);
986    }
987
988    #[test]
989    fn u256_mul_u64_by_zero() {
990        let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
991        assert_eq!(U256::ZERO, v.mul_u64(0_u64).0);
992    }
993
994    #[test]
995    fn u256_mul_u64() {
996        let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
997
998        let u96_res = u64_val.mul_u64(0xFFFF_FFFF).0;
999        let u128_res = u96_res.mul_u64(0xFFFF_FFFF).0;
1000        let u160_res = u128_res.mul_u64(0xFFFF_FFFF).0;
1001        let u192_res = u160_res.mul_u64(0xFFFF_FFFF).0;
1002        let u224_res = u192_res.mul_u64(0xFFFF_FFFF).0;
1003        let u256_res = u224_res.mul_u64(0xFFFF_FFFF).0;
1004
1005        assert_eq!(u96_res, U256::from_array([0, 0, 0xDEAD_BEEE, 0xFFFF_FFFF_2152_4111]));
1006        assert_eq!(
1007            u128_res,
1008            U256::from_array([0, 0, 0xDEAD_BEEE_2152_4110, 0x2152_4111_DEAD_BEEF])
1009        );
1010        assert_eq!(
1011            u160_res,
1012            U256::from_array([0, 0xDEAD_BEED, 0x42A4_8222_0000_0001, 0xBD5B_7DDD_2152_4111])
1013        );
1014        assert_eq!(
1015            u192_res,
1016            U256::from_array([
1017                0,
1018                0xDEAD_BEEC_63F6_C334,
1019                0xBD5B_7DDF_BD5B_7DDB,
1020                0x63F6_C333_DEAD_BEEF
1021            ])
1022        );
1023        assert_eq!(
1024            u224_res,
1025            U256::from_array([
1026                0xDEAD_BEEB,
1027                0x8549_0448_5964_BAAA,
1028                0xFFFF_FFFB_A69B_4558,
1029                0x7AB6_FBBB_2152_4111
1030            ])
1031        );
1032        assert_eq!(
1033            u256_res,
1034            U256(
1035                0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1036                0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1037            )
1038        );
1039    }
1040
1041    #[test]
1042    fn u256_addition() {
1043        let x = U256::from(u128::MAX);
1044        let (add, overflow) = x.overflowing_add(U256::ONE);
1045        assert!(!overflow);
1046        assert_eq!(add, U256(1, 0));
1047
1048        let (add, _) = add.overflowing_add(U256::ONE);
1049        assert_eq!(add, U256(1, 1));
1050    }
1051
1052    #[test]
1053    fn u256_subtraction() {
1054        let (sub, overflow) = U256::ONE.overflowing_sub(U256::ONE);
1055        assert!(!overflow);
1056        assert_eq!(sub, U256::ZERO);
1057
1058        let x = U256(1, 0);
1059        let (sub, overflow) = x.overflowing_sub(U256::ONE);
1060        assert!(!overflow);
1061        assert_eq!(sub, U256::from(u128::MAX));
1062    }
1063
1064    #[test]
1065    fn u256_multiplication() {
1066        let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1067
1068        let u128_res = u64_val.wrapping_mul(u64_val);
1069
1070        assert_eq!(u128_res, U256(0, 0xC1B1_CD13_A4D1_3D46_048D_1354_216D_A321));
1071
1072        let u256_res = u128_res.wrapping_mul(u128_res);
1073
1074        assert_eq!(
1075            u256_res,
1076            U256(
1077                0x928D_92B4_D7F5_DF33_4AFC_FF6F_0375_C608,
1078                0xF5CF_7F36_18C2_C886_F4E1_66AA_D40D_0A41,
1079            )
1080        );
1081    }
1082
1083    #[test]
1084    fn u256_multiplication_bits_in_each_word() {
1085        // Put a digit in the least significant bit of each 64 bit word.
1086        let u = (1_u128 << 64) | 1_u128;
1087        let x = U256(u, u);
1088
1089        // Put a digit in the second least significant bit of each 64 bit word.
1090        let u = (2_u128 << 64) | 2_u128;
1091        let y = U256(u, u);
1092
1093        let (got, overflow) = x.overflowing_mul(y);
1094
1095        let want = U256(
1096            0x0000_0000_0000_0008_0000_0000_0000_0006,
1097            0x0000_0000_0000_0004_0000_0000_0000_0002,
1098        );
1099        assert!(overflow);
1100        assert_eq!(got, want);
1101    }
1102
1103    #[test]
1104    fn u256_overflowing_mul() {
1105        let a = U256(u128::MAX, 0);
1106        let b = U256(1 << 65 | 1, 0);
1107        let (res, overflow) = a.overflowing_mul(b);
1108        assert_eq!(res, U256::ZERO);
1109        assert!(overflow);
1110
1111        let a = U256(1 << 64, 0);
1112        let b = U256(1, 0);
1113        let (res, overflow) = a.overflowing_mul(b);
1114        assert_eq!(res, U256::ZERO);
1115        assert!(overflow);
1116
1117        let a = U256(0, 1 << 63);
1118        let b = U256(1, 0);
1119        let (res, overflow) = a.overflowing_mul(b);
1120        assert_eq!(res, b << 63);
1121        assert!(!overflow);
1122
1123        let (res, overflow) = U256::ONE.overflowing_mul(U256::ONE);
1124        assert_eq!(res, U256::ONE);
1125        assert!(!overflow);
1126
1127        // Simple case near upper edge
1128        let a = U256(1 << 125, 0);
1129        let b = U256(0, 4);
1130        let (res, overflow) = a.overflowing_mul(b);
1131        assert_eq!(res, U256(1 << 127, 0));
1132        assert!(!overflow);
1133
1134        // Check case where bits overflow during shift. Kills * -> + and - -> + mutants.
1135        let a = U256::ONE << 2;
1136        let b = U256::ONE << 254;
1137        let (res, overflow) = a.overflowing_mul(b);
1138        assert_eq!(res, U256::ZERO);
1139        assert!(overflow);
1140
1141        // mul_u64 overflows twice but no other overflows. Kills |= -> ^= mutant.
1142        let a = U256::ONE << 255;
1143        let b = U256(1 << 1 | 1 << 65, 0);
1144        let (res, overflow) = a.overflowing_mul(b);
1145        assert_eq!(res, U256::ZERO);
1146        assert!(overflow);
1147    }
1148
1149    #[test]
1150    fn u256_increment() {
1151        let mut val = U256(
1152            0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1153            0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
1154        );
1155        val = val.wrapping_inc();
1156        assert_eq!(
1157            val,
1158            U256(
1159                0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1160                0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1161            )
1162        );
1163        val = val.wrapping_inc();
1164        assert_eq!(
1165            val,
1166            U256(
1167                0xF000_0000_0000_0000_0000_0000_0000_0000,
1168                0x0000_0000_0000_0000_0000_0000_0000_0000,
1169            )
1170        );
1171
1172        assert_eq!(U256::MAX.wrapping_inc(), U256::ZERO);
1173    }
1174
1175    #[test]
1176    fn u256_extreme_bitshift() {
1177        // Shifting a u64 by 64 bits gives an undefined value, so make sure that
1178        // we're doing the Right Thing here
1179        let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1180
1181        assert_eq!(init << 64, U256(0, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000));
1182        let add = (init << 64).wrapping_add(init);
1183        assert_eq!(add, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1184        assert_eq!(add >> 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1185        assert_eq!(add << 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1186        assert_eq!(add >> 64, U256(0, 0x0000_0000_0000_0000_DEAD_BEEF_DEAD_BEEF));
1187        assert_eq!(
1188            add << 64,
1189            U256(0xDEAD_BEEF_DEAD_BEEF, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000)
1190        );
1191    }
1192
1193    #[test]
1194    #[cfg(feature = "alloc")]
1195    fn u256_to_from_hex_roundtrips() {
1196        let val = U256(
1197            0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1198            0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1199        );
1200        let hex = format!("0x{:x}", val);
1201        let got = U256::from_hex(&hex).expect("failed to parse hex");
1202        assert_eq!(got, val);
1203    }
1204
1205    #[test]
1206    #[cfg(feature = "alloc")]
1207    fn u256_to_from_unprefixed_hex_roundtrips() {
1208        let val = U256(
1209            0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1210            0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1211        );
1212        let hex = format!("{:x}", val);
1213        let got = U256::from_unprefixed_hex(&hex).expect("failed to parse hex");
1214        assert_eq!(got, val);
1215    }
1216
1217    #[test]
1218    fn u256_from_hex_32_characters_long() {
1219        let hex = "a69b455cd41bb662a69b4555deadbeef";
1220        let want = U256(0x00, 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF);
1221        let got = U256::from_unprefixed_hex(hex).expect("failed to parse hex");
1222        assert_eq!(got, want);
1223    }
1224
1225    #[test]
1226    fn u256_is_max_correct_negative() {
1227        let tc = [U256::ZERO, U256::ONE, U256::from(u128::MAX)];
1228        for t in tc {
1229            assert!(!t.is_max());
1230        }
1231    }
1232
1233    #[test]
1234    fn u256_is_max_correct_positive() {
1235        assert!(U256::MAX.is_max());
1236
1237        let u = u128::MAX;
1238        assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
1239    }
1240
1241    #[test]
1242    fn u256_zero_min_max_inverse() {
1243        assert_eq!(U256::MAX.inverse(), U256::ONE);
1244        assert_eq!(U256::ONE.inverse(), U256::MAX);
1245        assert_eq!(U256::ZERO.inverse(), U256::MAX);
1246    }
1247
1248    #[test]
1249    fn u256_max_min_inverse_roundtrip() {
1250        let max = U256::MAX;
1251
1252        for min in &[U256::ZERO, U256::ONE] {
1253            // lower target means more work required.
1254            assert_eq!(Target(max).to_work(), Work(U256::ONE));
1255            assert_eq!(Target(*min).to_work(), Work(max));
1256
1257            assert_eq!(Work(max).to_target(), Target(U256::ONE));
1258            assert_eq!(Work(*min).to_target(), Target(max));
1259        }
1260    }
1261
1262    #[test]
1263    fn u256_wrapping_add_wraps_at_boundary() {
1264        assert_eq!(U256::MAX.wrapping_add(U256::ONE), U256::ZERO);
1265        assert_eq!(U256::MAX.wrapping_add(U256::from(2_u8)), U256::ONE);
1266    }
1267
1268    #[test]
1269    fn u256_wrapping_sub_wraps_at_boundary() {
1270        assert_eq!(U256::ZERO.wrapping_sub(U256::ONE), U256::MAX);
1271        assert_eq!(U256::ONE.wrapping_sub(U256::from(2_u8)), U256::MAX);
1272    }
1273
1274    #[test]
1275    fn mul_u64_overflows() {
1276        let (_, overflow) = U256::MAX.mul_u64(2);
1277        assert!(overflow, "max * 2 should overflow");
1278    }
1279
1280    #[test]
1281    #[cfg(debug_assertions)]
1282    #[should_panic(expected = "overflowed")]
1283    fn u256_overflowing_addition_panics() { let _ = U256::MAX + U256::ONE; }
1284
1285    #[test]
1286    #[cfg(debug_assertions)]
1287    #[should_panic(expected = "overflowed")]
1288    fn u256_overflowing_subtraction_panics() { let _ = U256::ZERO - U256::ONE; }
1289
1290    #[test]
1291    #[cfg(debug_assertions)]
1292    #[should_panic(expected = "overflowed")]
1293    fn u256_multiplication_by_max_panics() { let _ = U256::MAX * U256::MAX; }
1294
1295    #[test]
1296    fn u256_to_f64() {
1297        assert_eq!(U256::ZERO.to_f64(), 0.0_f64);
1298        assert_eq!(U256::ONE.to_f64(), 1.0_f64);
1299        assert_eq!(U256::MAX.to_f64(), 1.157_920_892_373_162e77_f64);
1300        assert_eq!((U256::MAX >> 1).to_f64(), 5.789_604_461_865_81e76_f64);
1301        assert_eq!((U256::MAX >> 128).to_f64(), 3.402_823_669_209_385e38_f64);
1302        assert_eq!((U256::MAX >> (256 - 54)).to_f64(), 1.801_439_850_948_198_4e16_f64);
1303        // 53 bits and below should not use exponents
1304        assert_eq!((U256::MAX >> (256 - 53)).to_f64(), 9_007_199_254_740_991.0_f64);
1305        assert_eq!((U256::MAX >> (256 - 32)).to_f64(), 4_294_967_295.0_f64);
1306        assert_eq!((U256::MAX >> (256 - 16)).to_f64(), 65535.0_f64);
1307        assert_eq!((U256::MAX >> (256 - 8)).to_f64(), 255.0_f64);
1308    }
1309
1310    #[test]
1311    #[cfg(debug_assertions)]
1312    #[should_panic(expected = "overflowed")]
1313    fn work_overflowing_addition_panics() { let _ = Work(U256::MAX) + Work(U256::ONE); }
1314
1315    #[test]
1316    #[cfg(debug_assertions)]
1317    #[should_panic(expected = "overflowed")]
1318    fn work_overflowing_subtraction_panics() { let _ = Work(U256::ZERO) - Work(U256::ONE); }
1319
1320    #[test]
1321    fn target_from_compact() {
1322        // (nBits, target)
1323        let tests = [
1324            (0x0100_3456_u32, 0x00_u64), // High bit set.
1325            (0x0112_3456_u32, 0x12_u64),
1326            (0x0200_8000_u32, 0x80_u64),
1327            (0x0500_9234_u32, 0x9234_0000_u64),
1328            (0x0492_3456_u32, 0x00_u64), // High bit set (0x80 in 0x92).
1329            (0x0412_3456_u32, 0x1234_5600_u64), // Inverse of above; no high bit.
1330        ];
1331
1332        for (n_bits, target) in tests {
1333            let want = Target(U256::from(target));
1334            let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
1335            assert_eq!(got, want);
1336        }
1337    }
1338
1339    macro_rules! check_from_str {
1340        ($ty:ident, $err_ty:ident, $mod_name:ident) => {
1341            #[cfg(feature = "alloc")]
1342            mod $mod_name {
1343                use alloc::string::ToString;
1344                use core::str::FromStr;
1345
1346                use super::{$err_ty, $ty, ParseU256Error, U256};
1347
1348                #[test]
1349                fn target_from_str_decimal() {
1350                    assert_eq!($ty::from_str("0").unwrap(), $ty(U256::ZERO));
1351                    assert_eq!("1".parse::<$ty>().unwrap(), $ty(U256(0, 1)));
1352                    assert_eq!("123456789".parse::<$ty>().unwrap(), $ty(U256(0, 123_456_789)));
1353
1354                    let str_tgt = "340282366920938463463374607431768211455";
1355                    let got = str_tgt.parse::<$ty>().unwrap();
1356                    assert_eq!(got, $ty(u128::MAX.into()));
1357
1358                    // 2^128
1359                    let str_tgt = "340282366920938463463374607431768211456";
1360                    let got = str_tgt.parse::<$ty>().unwrap();
1361                    assert_eq!(got, $ty(U256(1, 0)));
1362
1363                    // 2^256 - 1
1364                    let str_tgt = concat!(
1365                        "115792089237316195423570985008687907853",
1366                        "269984665640564039457584007913129639935"
1367                    );
1368                    let got = str_tgt.parse::<$ty>().unwrap();
1369                    assert_eq!(got, $ty(U256::MAX));
1370
1371                    // Padding
1372                    let got = "00000000000042".parse::<$ty>().unwrap();
1373                    assert_eq!(got, $ty(U256(0, 42)));
1374
1375                    // roundtrip
1376                    let want = $ty(u128::MAX.into());
1377                    let got = want.to_string().parse::<$ty>().unwrap();
1378                    assert_eq!(got, want);
1379                }
1380
1381                #[test]
1382                fn target_from_str_error() {
1383                    assert!(matches!(
1384                        "".parse::<$ty>().unwrap_err(),
1385                        $err_ty(ParseU256Error::Empty),
1386                    ));
1387                    assert!(matches!(
1388                        "12a34".parse::<$ty>().unwrap_err(),
1389                        $err_ty(ParseU256Error::InvalidDigit(_)),
1390                    ));
1391                    assert!(matches!(
1392                        " 42".parse::<$ty>().unwrap_err(),
1393                        $err_ty(ParseU256Error::InvalidDigit(_)),
1394                    ));
1395                    assert!(matches!(
1396                        "-1".parse::<$ty>().unwrap_err(),
1397                        $err_ty(ParseU256Error::InvalidDigit(_)),
1398                    ));
1399
1400                    assert!(matches!(
1401                        "1157ééééé92089237316195423570985008687907853".parse::<$ty>().unwrap_err(),
1402                        $err_ty(ParseU256Error::InvalidEncoding(_)),
1403                    ));
1404
1405                    // 2^256
1406                    let tgt_str = concat!(
1407                        "115792089237316195423570985008687907853",
1408                        "269984665640564039457584007913129639936"
1409                    );
1410                    assert!(matches!(
1411                        tgt_str.parse::<$ty>().unwrap_err(),
1412                        $err_ty(ParseU256Error::Overflow),
1413                    ));
1414                }
1415            }
1416        };
1417    }
1418
1419    check_from_str!(Target, ParseTargetError, target_from_str);
1420    check_from_str!(Work, ParseWorkError, work_from_str);
1421
1422    #[test]
1423    fn target_to_compact_lossy() {
1424        // (nBits, target)
1425        let tests = [
1426            (0x0_u32, 0x00_u64),
1427            (0x0112_0000_u32, 0x12_u64),
1428            (0x0200_8000_u32, 0x80_u64),
1429            (0x0500_9234_u32, 0x9234_0000_u64),
1430            (0x0412_3456_u32, 0x1234_5600_u64),
1431        ];
1432
1433        for (n_bits, target) in tests {
1434            let want = CompactTarget::from_consensus(n_bits);
1435            let got = Target(U256::from(target)).to_compact_lossy();
1436            assert_eq!(got, want);
1437        }
1438    }
1439
1440    #[test]
1441    fn roundtrip_compact_target() {
1442        let consensus = 0x1d00_ffff;
1443        let compact = CompactTarget::from_consensus(consensus);
1444        let t = Target::from_compact(CompactTarget::from_consensus(consensus));
1445        assert_eq!(t, Target::from(compact)); // From/Into sanity check.
1446
1447        let back = t.to_compact_lossy();
1448        assert_eq!(back, compact); // From/Into sanity check.
1449
1450        assert_eq!(back.to_consensus(), consensus);
1451    }
1452
1453    #[test]
1454    fn max_target_from_compact() {
1455        // The highest possible target is defined as 0x1d00ffff
1456        let bits = 0x1d00_ffff_u32;
1457        let want = Target::MAX;
1458        let got = Target::from_compact(CompactTarget::from_consensus(bits));
1459        assert_eq!(got, want);
1460    }
1461
1462    #[test]
1463    fn target_attainable_constants_from_original() {
1464        // The plain target values for the various nets from Bitcoin Core with no conversions.
1465        // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L88
1466        let max_mainnet: Target = Target(U256(u128::MAX >> 32, u128::MAX));
1467        // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L208
1468        let max_testnet: Target = Target(U256(u128::MAX >> 32, u128::MAX));
1469        // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L411
1470        let max_regtest: Target = Target(U256(u128::MAX >> 1, u128::MAX));
1471        // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L348
1472        let max_signet: Target = Target(U256(0x3_77aeu128 << 88, 0));
1473
1474        assert_eq!(
1475            Target::MAX_ATTAINABLE_MAINNET,
1476            Target::from_compact(max_mainnet.to_compact_lossy())
1477        );
1478        assert_eq!(
1479            Target::MAX_ATTAINABLE_TESTNET,
1480            Target::from_compact(max_testnet.to_compact_lossy())
1481        );
1482        assert_eq!(
1483            Target::MAX_ATTAINABLE_REGTEST,
1484            Target::from_compact(max_regtest.to_compact_lossy())
1485        );
1486        assert_eq!(
1487            Target::MAX_ATTAINABLE_SIGNET,
1488            Target::from_compact(max_signet.to_compact_lossy())
1489        );
1490    }
1491
1492    #[test]
1493    #[cfg(feature = "alloc")]
1494    fn target_max_attainable_hex() {
1495        // Also check explicit hex representations for regression testing.
1496        assert_eq!(
1497            format!("{:x}", Target::MAX_ATTAINABLE_MAINNET),
1498            "00000000ffff0000000000000000000000000000000000000000000000000000"
1499        );
1500        assert_eq!(
1501            format!("{:x}", Target::MAX_ATTAINABLE_TESTNET),
1502            "00000000ffff0000000000000000000000000000000000000000000000000000"
1503        );
1504        assert_eq!(
1505            format!("{:x}", Target::MAX_ATTAINABLE_REGTEST),
1506            "7fffff0000000000000000000000000000000000000000000000000000000000"
1507        );
1508        assert_eq!(
1509            format!("{:x}", Target::MAX_ATTAINABLE_SIGNET),
1510            "00000377ae000000000000000000000000000000000000000000000000000000"
1511        );
1512    }
1513
1514    #[test]
1515    #[cfg(feature = "encoding")]
1516    fn compact_target_decoder_read_limit() {
1517        // read_limit is one u32 = 4 bytes for empty decoder
1518        assert_eq!(CompactTargetDecoder::default().read_limit(), 4);
1519        assert_eq!(<CompactTarget as encoding::Decode>::decoder().read_limit(), 4);
1520    }
1521
1522    #[test]
1523    #[cfg(feature = "encoding")]
1524    fn compact_target_decoder_round_trip() {
1525        let bits: u32 = 0x1d00_ffff;
1526        let compact_target =
1527            encoding::decode_from_slice::<CompactTarget>(&bits.to_le_bytes()).unwrap();
1528        assert_eq!(compact_target.to_consensus(), bits);
1529    }
1530
1531    #[test]
1532    #[cfg(feature = "alloc")]
1533    fn compact_target_to_hex() {
1534        let compact_target = CompactTarget::from_consensus(0x1d00_ffff);
1535        let got = alloc::format!("{:x}", compact_target);
1536        assert_eq!(got, "1d00ffff");
1537    }
1538
1539    #[test]
1540    #[cfg(feature = "encoding")]
1541    #[cfg(feature = "alloc")]
1542    fn compact_target_decoder_error_display_and_source() {
1543        #[cfg(feature = "std")]
1544        use std::error::Error as _;
1545
1546        let mut slice = [0u8; 3].as_slice();
1547        let mut decoder = CompactTargetDecoder::new();
1548
1549        assert!(decoder.push_bytes(&mut slice).unwrap().needs_more());
1550
1551        let err = decoder.end().unwrap_err();
1552        assert!(!err.to_string().is_empty());
1553        #[cfg(feature = "std")]
1554        assert!(err.source().is_some());
1555    }
1556
1557    #[test]
1558    fn compact_target_ordering() {
1559        let lower = CompactTarget::from_consensus(0x1d00_fffe);
1560        let lower_copy = CompactTarget::from_consensus(0x1d00_fffe);
1561        let higher = CompactTarget::from_consensus(0x1d00_ffff);
1562
1563        assert!(lower < higher);
1564        assert!(lower == lower_copy);
1565    }
1566
1567    #[test]
1568    #[cfg(feature = "alloc")]
1569    fn compact_target_formatting() {
1570        let compact_target = CompactTarget::from_consensus(0x1d00_ffff);
1571        assert_eq!(format!("{}", compact_target), "486604799");
1572        assert_eq!(format!("{:x}", compact_target), "1d00ffff");
1573        assert_eq!(format!("{:#x}", compact_target), "0x1d00ffff");
1574        assert_eq!(format!("{:X}", compact_target), "1D00FFFF");
1575        assert_eq!(format!("{:#X}", compact_target), "0x1D00FFFF");
1576        assert_eq!(format!("{:o}", compact_target), "3500177777");
1577        assert_eq!(format!("{:#o}", compact_target), "0o3500177777");
1578        assert_eq!(format!("{:b}", compact_target), "11101000000001111111111111111");
1579        assert_eq!(format!("{:#b}", compact_target), "0b11101000000001111111111111111");
1580        assert_eq!(compact_target.to_consensus(), 0x1d00_ffff);
1581    }
1582
1583    #[test]
1584    fn compact_target_from_hex_lower() {
1585        let target = CompactTarget::from_hex("0x010034ab").unwrap();
1586        assert_eq!(target, CompactTarget::from_consensus(0x0100_34ab));
1587    }
1588
1589    #[test]
1590    fn compact_target_from_hex_upper() {
1591        let target = CompactTarget::from_hex("0X010034AB").unwrap();
1592        assert_eq!(target, CompactTarget::from_consensus(0x0100_34ab));
1593    }
1594
1595    #[test]
1596    fn compact_target_from_unprefixed_hex_lower() {
1597        let target = CompactTarget::from_unprefixed_hex("010034ab").unwrap();
1598        assert_eq!(target, CompactTarget::from_consensus(0x0100_34ab));
1599    }
1600
1601    #[test]
1602    fn compact_target_from_unprefixed_hex_upper() {
1603        let target = CompactTarget::from_unprefixed_hex("010034AB").unwrap();
1604        assert_eq!(target, CompactTarget::from_consensus(0x0100_34ab));
1605    }
1606
1607    #[test]
1608    fn compact_target_from_hex_invalid_hex_should_err() {
1609        let hex = "0xzbf9";
1610        let result = CompactTarget::from_hex(hex);
1611        assert!(result.is_err());
1612    }
1613
1614    #[test]
1615    #[cfg(feature = "alloc")]
1616    fn compact_target_lower_hex_and_upper_hex() {
1617        assert_eq!(format!("{:08x}", CompactTarget::from_consensus(0x01D0_F456)), "01d0f456");
1618        assert_eq!(format!("{:08X}", CompactTarget::from_consensus(0x01d0_f456)), "01D0F456");
1619    }
1620}