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