bitcoin/
pow.rs

1// SPDX-License-Identifier: CC0-1.0 OR Apache-2.0
2
3//! Proof-of-work related integer types.
4//!
5//! Provides the [`Work`] and [`Target`] types that are used in proof-of-work calculations. The
6//! functions here are designed to be fast, by that we mean it is safe to use them to check headers.
7//!
8
9use core::cmp;
10use core::fmt::{self, LowerHex, UpperHex};
11use core::ops::{Add, Div, Mul, Not, Rem, Shl, Shr, Sub};
12
13use io::{Read, Write};
14#[cfg(all(test, mutate))]
15use mutagen::mutate;
16use units::parse;
17
18use crate::block::Header;
19use crate::blockdata::block::BlockHash;
20use crate::consensus::encode::{self, Decodable, Encodable};
21use crate::consensus::Params;
22use crate::dogecoin::{params::Params as DogecoinParams, Header as DogecoinHeader};
23use crate::error::{ContainsPrefixError, MissingPrefixError, ParseIntError, PrefixedHexError, UnprefixedHexError};
24
25/// Implement traits and methods shared by `Target` and `Work`.
26macro_rules! do_impl {
27    ($ty:ident) => {
28        impl $ty {
29            #[doc = "Creates `"]
30            #[doc = stringify!($ty)]
31            #[doc = "` from a prefixed hex string."]
32            pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
33                Ok($ty(U256::from_hex(s)?))
34            }
35
36            #[doc = "Creates `"]
37            #[doc = stringify!($ty)]
38            #[doc = "` from an unprefixed hex string."]
39            pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
40                Ok($ty(U256::from_unprefixed_hex(s)?))
41            }
42
43            #[doc = "Creates `"]
44            #[doc = stringify!($ty)]
45            #[doc = "` from a big-endian byte array."]
46            #[inline]
47            pub fn from_be_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_be_bytes(bytes)) }
48
49            #[doc = "Creates `"]
50            #[doc = stringify!($ty)]
51            #[doc = "` from a little-endian byte array."]
52            #[inline]
53            pub fn from_le_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_le_bytes(bytes)) }
54
55            #[doc = "Converts `"]
56            #[doc = stringify!($ty)]
57            #[doc = "` to a big-endian byte array."]
58            #[inline]
59            pub fn to_be_bytes(self) -> [u8; 32] { self.0.to_be_bytes() }
60
61            #[doc = "Converts `"]
62            #[doc = stringify!($ty)]
63            #[doc = "` to a little-endian byte array."]
64            #[inline]
65            pub fn to_le_bytes(self) -> [u8; 32] { self.0.to_le_bytes() }
66        }
67
68        impl fmt::Display for $ty {
69            #[inline]
70            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
71                fmt::Display::fmt(&self.0, f)
72            }
73        }
74
75        impl fmt::LowerHex for $ty {
76            #[inline]
77            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
78                fmt::LowerHex::fmt(&self.0, f)
79            }
80        }
81
82        impl fmt::UpperHex for $ty {
83            #[inline]
84            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
85                fmt::UpperHex::fmt(&self.0, f)
86            }
87        }
88    };
89}
90
91/// A 256 bit integer representing work.
92///
93/// Work is a measure of how difficult it is to find a hash below a given [`Target`].
94#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
95#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
96#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
97pub struct Work(U256);
98
99impl Work {
100    /// Converts this [`Work`] to [`Target`].
101    pub fn to_target(self) -> Target { Target(self.0.inverse()) }
102
103    /// Returns log2 of this work.
104    ///
105    /// The result inherently suffers from a loss of precision and is, therefore, meant to be
106    /// used mainly for informative and displaying purposes, similarly to Bitcoin Core's
107    /// `log2_work` output in its logs.
108    #[cfg(feature = "std")]
109    pub fn log2(self) -> f64 { self.0.to_f64().log2() }
110}
111do_impl!(Work);
112
113impl Add for Work {
114    type Output = Work;
115    fn add(self, rhs: Self) -> Self { Work(self.0 + rhs.0) }
116}
117
118impl Sub for Work {
119    type Output = Work;
120    fn sub(self, rhs: Self) -> Self { Work(self.0 - rhs.0) }
121}
122
123/// A 256 bit integer representing target.
124///
125/// The SHA-256 hash of a block's header must be lower than or equal to the current target for the
126/// block to be accepted by the network. The lower the target, the more difficult it is to generate
127/// a block. (See also [`Work`].)
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))]
132#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
133pub struct Target(U256);
134
135impl Target {
136    /// When parsing nBits, Bitcoin Core converts a negative target threshold into a target of zero.
137    pub const ZERO: Target = Target(U256::ZERO);
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 = Target(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    pub const MAX_ATTAINABLE_MAINNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
154
155    /// The proof of work limit on testnet.
156    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
157    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L208
158    pub const MAX_ATTAINABLE_TESTNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
159
160    /// The proof of work limit on regtest.
161    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
162    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L411
163    pub const MAX_ATTAINABLE_REGTEST: Self = Target(U256(0x7FFF_FF00u128 << 96, 0));
164
165    /// The proof of work limit on signet.
166    // Taken from Bitcoin Core but had lossy conversion to/from compact form.
167    // https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L348
168    pub const MAX_ATTAINABLE_SIGNET: Self = Target(U256(0x0377_ae00 << 80, 0));
169
170    /// The maximum **attainable** target value on Dogecoin mainnet.
171    ///
172    /// Not all target values are attainable because consensus code uses the compact format to
173    /// represent targets (see [`CompactTarget`]).
174    pub const MAX_ATTAINABLE_MAINNET_DOGE: Self = Target(U256(0xFFFF_F000u128 << (204 - 128), 0));
175
176    /// The proof of work limit on Dogecoin testnet.
177    // Taken from Dogecoin Core but had lossy conversion to/from compact form.
178    // https://github.com/dogecoin/dogecoin/blob/d7cc7f8bbb5f790942d0ed0617f62447e7675233/src/chainparams.cpp#L248
179    pub const MAX_ATTAINABLE_TESTNET_DOGE: Self = Target(U256(0xFFFF_F000u128 << (204 - 128), 0));
180
181    /// The proof of work limit on Dogecoin regtest.
182    // Taken from Dogecoin Core but had lossy conversion to/from compact form.
183    // https://github.com/dogecoin/dogecoin/blob/d7cc7f8bbb5f790942d0ed0617f62447e7675233/src/chainparams.cpp#L392
184    pub const MAX_ATTAINABLE_REGTEST_DOGE: Self = Target(U256(0x7FFF_FF00u128 << 96, 0));
185
186    /// Computes the [`Target`] value from a compact representation.
187    ///
188    /// ref: <https://developer.bitcoin.org/reference/block_chain.html#target-nbits>
189    pub fn from_compact(c: CompactTarget) -> Target {
190        let bits = c.0;
191        // This is a floating-point "compact" encoding originally used by
192        // OpenSSL, which satoshi put into consensus code, so we're stuck
193        // with it. The exponent needs to have 3 subtracted from it, hence
194        // this goofy decoding code. 3 is due to 3 bytes in the mantissa.
195        let (mant, expt) = {
196            let unshifted_expt = bits >> 24;
197            if unshifted_expt <= 3 {
198                ((bits & 0xFFFFFF) >> (8 * (3 - unshifted_expt as usize)), 0)
199            } else {
200                (bits & 0xFFFFFF, 8 * ((bits >> 24) - 3))
201            }
202        };
203
204        // The mantissa is signed but may not be negative.
205        if mant > 0x7F_FFFF {
206            Target::ZERO
207        } else {
208            Target(U256::from(mant) << expt)
209        }
210    }
211
212    /// Computes the compact value from a [`Target`] representation.
213    ///
214    /// The compact form is by definition lossy, this means that
215    /// `t == Target::from_compact(t.to_compact_lossy())` does not always hold.
216    pub fn to_compact_lossy(self) -> CompactTarget {
217        let mut size = (self.0.bits() + 7) / 8;
218        let mut compact = if size <= 3 {
219            (self.0.low_u64() << (8 * (3 - size))) as u32
220        } else {
221            let bn = self.0 >> (8 * (size - 3));
222            bn.low_u32()
223        };
224
225        if (compact & 0x0080_0000) != 0 {
226            compact >>= 8;
227            size += 1;
228        }
229
230        CompactTarget(compact | (size << 24))
231    }
232
233    /// Returns true if block hash is less than or equal to this [`Target`].
234    ///
235    /// Proof-of-work validity for a block requires the hash of the block to be less than or equal
236    /// to the target.
237    #[cfg_attr(all(test, mutate), mutate)]
238    pub fn is_met_by(&self, hash: BlockHash) -> bool {
239        use hashes::Hash;
240        let hash = U256::from_le_bytes(hash.to_byte_array());
241        hash <= self.0
242    }
243
244    /// Converts this [`Target`] to [`Work`].
245    ///
246    /// "Work" is defined as the work done to mine a block with this target value (recorded in the
247    /// block header in compact form as nBits). This is not the same as the difficulty to mine a
248    /// block with this target (see `Self::difficulty`).
249    pub fn to_work(self) -> Work { Work(self.0.inverse()) }
250
251    /// Computes the popular "difficulty" measure for mining.
252    ///
253    /// Difficulty represents how difficult the current target makes it to find a block, relative to
254    /// how difficult it would be at the highest possible target (highest target == lowest difficulty).
255    ///
256    /// For example, a difficulty of 6,695,826 means that at a given hash rate, it will, on average,
257    /// take ~6.6 million times as long to find a valid block as it would at a difficulty of 1, or
258    /// alternatively, it will take, again on average, ~6.6 million times as many hashes to find a
259    /// valid block
260    ///
261    /// # Note
262    ///
263    /// Difficulty is calculated using the following algorithm `max / current` where [max] is
264    /// defined for the Bitcoin network and `current` is the current [target] for this block. As
265    /// such, a low target implies a high difficulty. Since [`Target`] is represented as a 256 bit
266    /// integer but `difficulty()` returns only 128 bits this means for targets below approximately
267    /// `0xffff_ffff_ffff_ffff_ffff_ffff` `difficulty()` will saturate at `u128::MAX`.
268    ///
269    /// # Panics
270    ///
271    /// Panics if `self` is zero (divide by zero).
272    ///
273    /// [max]: Target::max
274    /// [target]: crate::blockdata::block::Header::target
275    #[cfg_attr(all(test, mutate), mutate)]
276    pub fn difficulty(&self, params: impl AsRef<Params>) -> u128 {
277        // Panic here may be eaiser to debug than during the actual division.
278        assert_ne!(self.0, U256::ZERO, "divide by zero");
279
280        let max = params.as_ref().max_attainable_target;
281        let d = max.0 / self.0;
282        d.saturating_to_u128()
283    }
284
285    /// Computes the popular "difficulty" measure for mining and returns a float value of f64.
286    ///
287    /// See [`difficulty`] for details.
288    ///
289    /// # Returns
290    ///
291    /// Returns [`f64::INFINITY`] if `self` is zero (caused by divide by zero).
292    ///
293    /// [`difficulty`]: Target::difficulty
294    #[cfg_attr(all(test, mutate), mutate)]
295    pub fn difficulty_float(&self) -> f64 { TARGET_MAX_F64 / self.0.to_f64() }
296
297    /// Computes the minimum valid [`Target`] threshold allowed for a block in which a difficulty
298    /// adjustment occurs.
299    #[deprecated(since = "0.32.0", note = "use min_transition_threshold instead")]
300    pub fn min_difficulty_transition_threshold(&self) -> Self { self.min_transition_threshold() }
301
302    /// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
303    /// adjustment occurs.
304    #[deprecated(since = "0.32.0", note = "use max_transition_threshold instead")]
305    pub fn max_difficulty_transition_threshold(&self) -> Self {
306        self.max_transition_threshold_unchecked()
307    }
308
309    /// Computes the minimum valid [`Target`] threshold allowed for a block in which a difficulty
310    /// adjustment occurs for Bitcoin.
311    ///
312    /// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
313    /// adjustment period.
314    ///
315    /// # Returns
316    ///
317    /// In line with Bitcoin Core this function may return a target value of zero.
318    pub fn min_transition_threshold(&self) -> Self { Self(self.0 >> 2) }
319
320    /// Computes the minimum valid [`Target`] threshold allowed for a block in which a difficulty
321    /// adjustment occurs for Dogecoin.
322    ///
323    /// Pre-Digishield: The target can only decrease by a factor of 4, 8, or 16 max in each
324    /// difficulty adjustment period, depending on the height.
325    ///
326    /// Digishield: The target can decrease by 25 % max of the previous target in one adjustment.
327    /// 
328    /// ref: <https://github.com/dogecoin/dogecoin/blob/2c513d0172e8bc86fe9a337693b26f2fdf68a013/src/dogecoin.cpp#L50-L66>
329    ///
330    /// # Returns
331    ///
332    /// In line with Dogecoin Core this function may return a target value of zero.
333    pub fn min_transition_threshold_dogecoin(&self, params: impl AsRef<DogecoinParams>, height: u32) -> Self {
334        if params.as_ref().is_digishield_activated(height) {
335            Self(self.0 - (self.0 >> 2))
336        } else {
337            match height {
338                0..=5_000 => Self(self.0 >> 4),
339                5_001..=10_000 => Self(self.0 >> 3),
340                _ => Self(self.0 >> 2),
341            }
342        }
343    }
344
345    /// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
346    /// adjustment occurs for Bitcoin.
347    ///
348    /// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
349    /// adjustment period.
350    ///
351    /// We also check that the calculated target is not greater than the maximum allowed target,
352    /// this value is network specific - hence the `params` parameter.
353    pub fn max_transition_threshold(&self, params: impl AsRef<Params>) -> Self {
354        let max_attainable = params.as_ref().max_attainable_target;
355        cmp::min(self.max_transition_threshold_unchecked(), max_attainable)
356    }
357
358    /// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
359    /// adjustment occurs for Dogecoin.
360    ///
361    /// Pre-Digishield: The target can only increase by a factor of 4 max in each difficulty
362    /// adjustment period.
363    ///
364    /// Digishield: The target can increase by 50 % max of the previous target in one adjustment.
365    ///
366    /// We also check that the calculated target is not greater than the maximum allowed target,
367    /// this value is network specific - hence the `params` parameter.
368    pub fn max_transition_threshold_dogecoin(&self, params: impl AsRef<DogecoinParams>, height: u32) -> Self {
369        let max_attainable = params.as_ref().max_attainable_target;
370        if params.as_ref().is_digishield_activated(height) {
371            cmp::min(Self(self.0 + (self.0 >> 1)), max_attainable)
372        } else {
373            cmp::min(self.max_transition_threshold_unchecked(), max_attainable)
374        }
375    }
376
377    /// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
378    /// adjustment occurs.
379    ///
380    /// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
381    /// adjustment period.
382    ///
383    /// # Returns
384    ///
385    /// This function may return a value greater than the maximum allowed target for this network.
386    ///
387    /// The return value should be checked against [`Params::max_attainable_target`] or use one of
388    /// the `Target::MAX_ATTAINABLE_FOO` constants.
389    pub fn max_transition_threshold_unchecked(&self) -> Self { Self(self.0 << 2) }
390}
391do_impl!(Target);
392
393/// Encoding of 256-bit target as 32-bit float.
394///
395/// This is used to encode a target into the block header. Satoshi made this part of consensus code
396/// in the original version of Bitcoin, likely copying an idea from OpenSSL.
397///
398/// OpenSSL's bignum (BN) type has an encoding, which is even called "compact" as in bitcoin, which
399/// is exactly this format.
400#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
401#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
402#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
403pub struct CompactTarget(u32);
404
405impl CompactTarget {
406    /// Creates a `CompactTarget` from an prefixed hex string.
407    pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
408        let stripped = if let Some(stripped) = s.strip_prefix("0x") {
409            stripped
410        } else if let Some(stripped) = s.strip_prefix("0X") {
411            stripped
412        } else {
413            return Err(MissingPrefixError::new(s).into());
414        };
415
416        let target = parse::hex_u32(stripped)?;
417        Ok(Self::from_consensus(target))
418    }
419
420    /// Creates a `CompactTarget` from an unprefixed hex string.
421    pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
422        if s.starts_with("0x") || s.starts_with("0X") {
423            return Err(ContainsPrefixError::new(s).into());
424        }
425        let lock_time = parse::hex_u32(s)?;
426        Ok(Self::from_consensus(lock_time))
427    }
428
429    /// Computes the [`CompactTarget`] from a difficulty adjustment.
430    ///
431    /// ref: <https://github.com/bitcoin/bitcoin/blob/0503cbea9aab47ec0a87d34611e5453158727169/src/pow.cpp>
432    ///
433    /// Given the previous Target, represented as a [`CompactTarget`], the difficulty is adjusted
434    /// by taking the timespan between them, and multipling the current [`CompactTarget`] by a factor
435    /// of the net timespan and expected timespan. The [`CompactTarget`] may not adjust by more than
436    /// a factor of 4, or adjust beyond the maximum threshold for the network.
437    ///
438    /// # Note
439    ///
440    /// Under the consensus rules, the difference in the number of blocks between the headers does
441    /// not equate to the `difficulty_adjustment_interval` of [`Params`]. This is due to an off-by-one
442    /// error, and, the expected number of blocks in between headers is `difficulty_adjustment_interval - 1`
443    /// when calculating the difficulty adjustment.
444    ///
445    /// Take the example of the first difficulty adjustment. Block 2016 introduces a new [`CompactTarget`],
446    /// which takes the net timespan between Block 2015 and Block 0, and recomputes the difficulty.
447    ///
448    /// # Returns
449    ///
450    /// The expected [`CompactTarget`] recalculation.
451    pub fn from_next_work_required(
452        last: CompactTarget,
453        timespan: u64,
454        params: impl AsRef<Params>,
455    ) -> CompactTarget {
456        let params = params.as_ref();
457        if params.no_pow_retargeting {
458            return last;
459        }
460        // Comments relate to the `pow.cpp` file from Core.
461        // ref: <https://github.com/bitcoin/bitcoin/blob/0503cbea9aab47ec0a87d34611e5453158727169/src/pow.cpp>
462        let min_timespan = params.pow_target_timespan >> 2; // Lines 56/57
463        let max_timespan = params.pow_target_timespan << 2; // Lines 58/59
464        let actual_timespan = timespan.clamp(min_timespan, max_timespan);
465        let prev_target: Target = last.into();
466        let maximum_retarget = prev_target.max_transition_threshold(params); // bnPowLimit
467        let retarget = prev_target.0; // bnNew
468        let retarget = retarget.mul(actual_timespan.into());
469        let retarget = retarget.div(params.pow_target_timespan.into());
470        let retarget = Target(retarget);
471        if retarget.ge(&maximum_retarget) {
472            return maximum_retarget.to_compact_lossy();
473        }
474        retarget.to_compact_lossy()
475    }
476
477    /// Computes the [`CompactTarget`] from a difficulty adjustment in Dogecoin.
478    ///
479    /// ref: <https://github.com/dogecoin/dogecoin/blob/51cbc1fd5d0d045dda2ad84f53572bbf524c6a8e/src/dogecoin.cpp>
480    ///
481    /// Given the previous Target, represented as a [`CompactTarget`], the difficulty is adjusted
482    /// by taking the timespan between them, and multiplying the current [`CompactTarget`] by a factor
483    /// of the net timespan and expected timespan. The [`CompactTarget`] may not increase by more than
484    /// a factor of 4, adjust beyond the maximum threshold for the network, or decrease by a factor
485    /// of 16, 8, or 4 depending on block height.
486    ///
487    /// # Returns
488    ///
489    /// The expected [`CompactTarget`] recalculation.
490    pub fn from_next_work_required_dogecoin(
491        last: CompactTarget,
492        timespan: i64,
493        params: impl AsRef<DogecoinParams>,
494        height: u32
495    ) -> CompactTarget {
496        let params = params.as_ref();
497        if params.no_pow_retargeting {
498            return last;
499        }
500        // Comments relate to the `pow.cpp` file from Core.
501        // ref: <https://github.com/dogecoin/dogecoin/blob/51cbc1fd5d0d045dda2ad84f53572bbf524c6a8e/src/dogecoin.cpp>
502        let retarget_timespan = params.pow_target_timespan(height); // Line 44
503        let mut modulated_timespan = timespan; // Lines 45-46
504        if params.is_digishield_activated(height) { // Lines 50-56
505            modulated_timespan = retarget_timespan + (modulated_timespan - retarget_timespan) / 8; // Line 53
506            let (min_timespan, max_timespan) = (
507                retarget_timespan - (retarget_timespan >> 2),
508                retarget_timespan + (retarget_timespan >> 1),
509            );
510            modulated_timespan = modulated_timespan.clamp(min_timespan, max_timespan); // Lines 69-72
511        } else { // Lines 57-66
512            let max_timespan = retarget_timespan << 2;
513            let min_timespan = match height {
514                0..=5_000 => retarget_timespan >> 4,
515                5_001..=10_000 => retarget_timespan >> 3,
516                _ => retarget_timespan >> 2,
517            };
518            modulated_timespan = modulated_timespan.clamp(min_timespan, max_timespan); // Lines 69-72
519        }
520        let prev_target: Target = last.into();
521        let maximum_retarget = prev_target.max_transition_threshold_dogecoin(params, height); // bnPowLimit
522        let retarget = prev_target.0; // bnNew
523        let retarget = retarget.mul((modulated_timespan as u64).into()); // Line 80
524        let retarget = retarget.div((retarget_timespan as u64).into()); // Line 81
525        let retarget = Target(retarget);
526        if retarget.ge(&maximum_retarget) {
527            return maximum_retarget.to_compact_lossy();
528        }
529        retarget.to_compact_lossy()
530    }
531
532    /// Computes the [`CompactTarget`] from a difficulty adjustment,
533    /// assuming these are the relevant block headers.
534    ///
535    /// Given two headers, representing the start and end of a difficulty adjustment epoch,
536    /// compute the [`CompactTarget`] based on the net time between them and the current
537    /// [`CompactTarget`].
538    ///
539    /// # Note
540    ///
541    /// See [`CompactTarget::from_next_work_required`]
542    ///
543    /// For example, to successfully compute the first difficulty adjustment on the Bitcoin network,
544    /// one would pass the header for Block 2015 as `current` and the header for Block 0 as
545    /// `last_epoch_boundary`.
546    ///
547    /// # Returns
548    ///
549    /// The expected [`CompactTarget`] recalculation.
550    pub fn from_header_difficulty_adjustment(
551        last_epoch_boundary: Header,
552        current: Header,
553        params: impl AsRef<Params>,
554    ) -> CompactTarget {
555        let timespan = current.time - last_epoch_boundary.time;
556        let bits = current.bits;
557        CompactTarget::from_next_work_required(bits, timespan.into(), params)
558    }
559
560    /// Computes the [`CompactTarget`] from a difficulty adjustment,
561    /// assuming these are the relevant block headers, in the Dogecoin network.
562    ///
563    /// Given two headers, representing the start and end of a difficulty adjustment epoch,
564    /// compute the [`CompactTarget`] based on the net time between them and the current
565    /// [`CompactTarget`].
566    ///
567    /// # Note
568    ///
569    /// See [`CompactTarget::from_next_work_required_dogecoin`].
570    /// 
571    /// Unlike Bitcoin, Dogecoin uses overlapping intervals (see Time Wrap Attack bug fix
572    /// introduced by Litecoin).
573    ///
574    /// For example, to successfully compute the first difficulty adjustments on the Dogecoin network,
575    /// one would pass the following headers:
576    ///     - `current`: Block 239, `last_epoch_boundary`: Block 0
577    ///     - `current`: Block 479, `last_epoch_boundary`: Block 239
578    ///     - `current`: Block 719, `last_epoch_boundary`: Block 479
579    ///     - `current`: Block 959, `last_epoch_boundary`: Block 719
580    ///
581    /// # Returns
582    ///
583    /// The expected [`CompactTarget`] recalculation.
584    pub fn from_header_difficulty_adjustment_dogecoin(
585        last_epoch_boundary: DogecoinHeader,
586        current: DogecoinHeader,
587        params: impl AsRef<DogecoinParams>,
588        height: u32
589    ) -> CompactTarget {
590        let timespan = (current.time as i64) - (last_epoch_boundary.time as i64);
591        let bits = current.bits;
592        CompactTarget::from_next_work_required_dogecoin(bits, timespan, params, height)
593    }
594
595    /// Creates a [`CompactTarget`] from a consensus encoded `u32`.
596    pub fn from_consensus(bits: u32) -> Self { Self(bits) }
597
598    /// Returns the consensus encoded `u32` representation of this [`CompactTarget`].
599    pub fn to_consensus(self) -> u32 { self.0 }
600}
601
602impl From<CompactTarget> for Target {
603    fn from(c: CompactTarget) -> Self { Target::from_compact(c) }
604}
605
606impl Encodable for CompactTarget {
607    #[inline]
608    fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
609        self.0.consensus_encode(w)
610    }
611}
612
613impl Decodable for CompactTarget {
614    #[inline]
615    fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
616        u32::consensus_decode(r).map(CompactTarget)
617    }
618}
619
620impl LowerHex for CompactTarget {
621    #[inline]
622    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { LowerHex::fmt(&self.0, f) }
623}
624
625impl UpperHex for CompactTarget {
626    #[inline]
627    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { UpperHex::fmt(&self.0, f) }
628}
629
630/// Big-endian 256 bit integer type.
631// (high, low): u.0 contains the high bits, u.1 contains the low bits.
632#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
633struct U256(u128, u128);
634
635impl U256 {
636    const MAX: U256 =
637        U256(0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
638
639    const ZERO: U256 = U256(0, 0);
640
641    const ONE: U256 = U256(0, 1);
642
643    /// Creates a `U256` from a prefixed hex string.
644    fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
645        let stripped = if let Some(stripped) = s.strip_prefix("0x") {
646            stripped
647        } else if let Some(stripped) = s.strip_prefix("0X") {
648            stripped
649        } else {
650            return Err(MissingPrefixError::new(s).into());
651        };
652        Ok(U256::from_hex_internal(stripped)?)
653    }
654
655    /// Creates a `U256` from an unprefixed hex string.
656    fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
657        if s.starts_with("0x") || s.starts_with("0X") {
658            return Err(ContainsPrefixError::new(s).into());
659        }
660        Ok(U256::from_hex_internal(s)?)
661    }
662
663    // Caller to ensure `s` does not contain a prefix.
664    fn from_hex_internal(s: &str) -> Result<Self, ParseIntError> {
665        let (high, low) = if s.len() <= 32 {
666            let low = parse::hex_u128(s)?;
667            (0, low)
668        } else {
669            let high_len = s.len() - 32;
670            let high_s = &s[..high_len];
671            let low_s = &s[high_len..];
672
673            let high = parse::hex_u128(high_s)?;
674            let low = parse::hex_u128(low_s)?;
675            (high, low)
676        };
677
678        Ok(U256(high, low))
679    }
680
681    /// Creates `U256` from a big-endian array of `u8`s.
682    #[cfg_attr(all(test, mutate), mutate)]
683    fn from_be_bytes(a: [u8; 32]) -> U256 {
684        let (high, low) = split_in_half(a);
685        let big = u128::from_be_bytes(high);
686        let little = u128::from_be_bytes(low);
687        U256(big, little)
688    }
689
690    /// Creates a `U256` from a little-endian array of `u8`s.
691    #[cfg_attr(all(test, mutate), mutate)]
692    fn from_le_bytes(a: [u8; 32]) -> U256 {
693        let (high, low) = split_in_half(a);
694        let little = u128::from_le_bytes(high);
695        let big = u128::from_le_bytes(low);
696        U256(big, little)
697    }
698
699    /// Converts `U256` to a big-endian array of `u8`s.
700    #[cfg_attr(all(test, mutate), mutate)]
701    fn to_be_bytes(self) -> [u8; 32] {
702        let mut out = [0; 32];
703        out[..16].copy_from_slice(&self.0.to_be_bytes());
704        out[16..].copy_from_slice(&self.1.to_be_bytes());
705        out
706    }
707
708    /// Converts `U256` to a little-endian array of `u8`s.
709    #[cfg_attr(all(test, mutate), mutate)]
710    fn to_le_bytes(self) -> [u8; 32] {
711        let mut out = [0; 32];
712        out[..16].copy_from_slice(&self.1.to_le_bytes());
713        out[16..].copy_from_slice(&self.0.to_le_bytes());
714        out
715    }
716
717    /// Calculates 2^256 / (x + 1) where x is a 256 bit unsigned integer.
718    ///
719    /// 2**256 / (x + 1) == ~x / (x + 1) + 1
720    ///
721    /// (Equation shamelessly stolen from bitcoind)
722    fn inverse(&self) -> U256 {
723        // We should never have a target/work of zero so this doesn't matter
724        // that much but we define the inverse of 0 as max.
725        if self.is_zero() {
726            return U256::MAX;
727        }
728        // We define the inverse of 1 as max.
729        if self.is_one() {
730            return U256::MAX;
731        }
732        // We define the inverse of max as 1.
733        if self.is_max() {
734            return U256::ONE;
735        }
736
737        let ret = !*self / self.wrapping_inc();
738        ret.wrapping_inc()
739    }
740
741    #[cfg_attr(all(test, mutate), mutate)]
742    fn is_zero(&self) -> bool { self.0 == 0 && self.1 == 0 }
743
744    #[cfg_attr(all(test, mutate), mutate)]
745    fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 }
746
747    #[cfg_attr(all(test, mutate), mutate)]
748    fn is_max(&self) -> bool { self.0 == u128::MAX && self.1 == u128::MAX }
749
750    /// Returns the low 32 bits.
751    fn low_u32(&self) -> u32 { self.low_u128() as u32 }
752
753    /// Returns the low 64 bits.
754    fn low_u64(&self) -> u64 { self.low_u128() as u64 }
755
756    /// Returns the low 128 bits.
757    fn low_u128(&self) -> u128 { self.1 }
758
759    /// Returns this `U256` as a `u128` saturating to `u128::MAX` if `self` is too big.
760    // Matagen gives false positive because >= and > both return u128::MAX
761    fn saturating_to_u128(&self) -> u128 {
762        if *self > U256::from(u128::MAX) {
763            u128::MAX
764        } else {
765            self.low_u128()
766        }
767    }
768
769    /// Returns the least number of bits needed to represent the number.
770    #[cfg_attr(all(test, mutate), mutate)]
771    fn bits(&self) -> u32 {
772        if self.0 > 0 {
773            256 - self.0.leading_zeros()
774        } else {
775            128 - self.1.leading_zeros()
776        }
777    }
778
779    /// Wrapping multiplication by `u64`.
780    ///
781    /// # Returns
782    ///
783    /// The multiplication result along with a boolean indicating whether an arithmetic overflow
784    /// occurred. If an overflow occurred then the wrapped value is returned.
785    // mutagen false pos mul_u64: replace `|` with `^` (XOR is same as OR when combined with <<)
786    // mutagen false pos mul_u64: replace `|` with `^`
787    #[cfg_attr(all(test, mutate), mutate)]
788    fn mul_u64(self, rhs: u64) -> (U256, bool) {
789        let mut carry: u128 = 0;
790        let mut split_le =
791            [self.1 as u64, (self.1 >> 64) as u64, self.0 as u64, (self.0 >> 64) as u64];
792
793        for word in &mut split_le {
794            // This will not overflow, for proof see https://github.com/rust-bitcoin/rust-bitcoin/pull/1496#issuecomment-1365938572
795            let n = carry + u128::from(rhs) * u128::from(*word);
796
797            *word = n as u64; // Intentional truncation, save the low bits
798            carry = n >> 64; // and carry the high bits.
799        }
800
801        let low = u128::from(split_le[0]) | u128::from(split_le[1]) << 64;
802        let high = u128::from(split_le[2]) | u128::from(split_le[3]) << 64;
803        (Self(high, low), carry != 0)
804    }
805
806    /// Calculates quotient and remainder.
807    ///
808    /// # Returns
809    ///
810    /// (quotient, remainder)
811    ///
812    /// # Panics
813    ///
814    /// If `rhs` is zero.
815    #[cfg_attr(all(test, mutate), mutate)]
816    fn div_rem(self, rhs: Self) -> (Self, Self) {
817        let mut sub_copy = self;
818        let mut shift_copy = rhs;
819        let mut ret = [0u128; 2];
820
821        let my_bits = self.bits();
822        let your_bits = rhs.bits();
823
824        // Check for division by 0
825        assert!(your_bits != 0, "attempted to divide {} by zero", self);
826
827        // Early return in case we are dividing by a larger number than us
828        if my_bits < your_bits {
829            return (U256::ZERO, sub_copy);
830        }
831
832        // Bitwise long division
833        let mut shift = my_bits - your_bits;
834        shift_copy = shift_copy << shift;
835        loop {
836            if sub_copy >= shift_copy {
837                ret[1 - (shift / 128) as usize] |= 1 << (shift % 128);
838                sub_copy = sub_copy.wrapping_sub(shift_copy);
839            }
840            shift_copy = shift_copy >> 1;
841            if shift == 0 {
842                break;
843            }
844            shift -= 1;
845        }
846
847        (U256(ret[0], ret[1]), sub_copy)
848    }
849
850    /// Calculates `self` + `rhs`
851    ///
852    /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic
853    /// overflow would occur. If an overflow would have occurred then the wrapped value is returned.
854    #[must_use = "this returns the result of the operation, without modifying the original"]
855    #[cfg_attr(all(test, mutate), mutate)]
856    fn overflowing_add(self, rhs: Self) -> (Self, bool) {
857        let mut ret = U256::ZERO;
858        let mut ret_overflow = false;
859
860        let (high, overflow) = self.0.overflowing_add(rhs.0);
861        ret.0 = high;
862        ret_overflow |= overflow;
863
864        let (low, overflow) = self.1.overflowing_add(rhs.1);
865        ret.1 = low;
866        if overflow {
867            let (high, overflow) = ret.0.overflowing_add(1);
868            ret.0 = high;
869            ret_overflow |= overflow;
870        }
871
872        (ret, ret_overflow)
873    }
874
875    /// Calculates `self` - `rhs`
876    ///
877    /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic
878    /// overflow would occur. If an overflow would have occurred then the wrapped value is returned.
879    #[must_use = "this returns the result of the operation, without modifying the original"]
880    #[cfg_attr(all(test, mutate), mutate)]
881    fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
882        let ret = self.wrapping_add(!rhs).wrapping_add(Self::ONE);
883        let overflow = rhs > self;
884        (ret, overflow)
885    }
886
887    /// Calculates the multiplication of `self` and `rhs`.
888    ///
889    /// Returns a tuple of the multiplication along with a boolean
890    /// indicating whether an arithmetic overflow would occur. If an
891    /// overflow would have occurred then the wrapped value is returned.
892    #[must_use = "this returns the result of the operation, without modifying the original"]
893    #[cfg_attr(all(test, mutate), mutate)]
894    fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
895        let mut ret = U256::ZERO;
896        let mut ret_overflow = false;
897
898        for i in 0..3 {
899            let to_mul = (rhs >> (64 * i)).low_u64();
900            let (mul_res, _) = self.mul_u64(to_mul);
901            ret = ret.wrapping_add(mul_res << (64 * i));
902        }
903
904        let to_mul = (rhs >> 192).low_u64();
905        let (mul_res, overflow) = self.mul_u64(to_mul);
906        ret_overflow |= overflow;
907        let (sum, overflow) = ret.overflowing_add(mul_res);
908        ret = sum;
909        ret_overflow |= overflow;
910
911        (ret, ret_overflow)
912    }
913
914    /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the
915    /// type.
916    #[must_use = "this returns the result of the operation, without modifying the original"]
917    fn wrapping_add(self, rhs: Self) -> Self {
918        let (ret, _overflow) = self.overflowing_add(rhs);
919        ret
920    }
921
922    /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of
923    /// the type.
924    #[must_use = "this returns the result of the operation, without modifying the original"]
925    fn wrapping_sub(self, rhs: Self) -> Self {
926        let (ret, _overflow) = self.overflowing_sub(rhs);
927        ret
928    }
929
930    /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at the boundary of
931    /// the type.
932    #[must_use = "this returns the result of the operation, without modifying the original"]
933    #[cfg(test)]
934    fn wrapping_mul(self, rhs: Self) -> Self {
935        let (ret, _overflow) = self.overflowing_mul(rhs);
936        ret
937    }
938
939    /// Returns `self` incremented by 1 wrapping around at the boundary of the type.
940    #[must_use = "this returns the result of the increment, without modifying the original"]
941    #[cfg_attr(all(test, mutate), mutate)]
942    fn wrapping_inc(&self) -> U256 {
943        let mut ret = U256::ZERO;
944
945        ret.1 = self.1.wrapping_add(1);
946        if ret.1 == 0 {
947            ret.0 = self.0.wrapping_add(1);
948        } else {
949            ret.0 = self.0;
950        }
951        ret
952    }
953
954    /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes any
955    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
956    ///
957    /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is
958    /// restricted to the range of the type, rather than the bits shifted out of the LHS being
959    /// returned to the other end. We do not currently support `rotate_left`.
960    #[must_use = "this returns the result of the operation, without modifying the original"]
961    #[cfg_attr(all(test, mutate), mutate)]
962    fn wrapping_shl(self, rhs: u32) -> Self {
963        let shift = rhs & 0x000000ff;
964
965        let mut ret = U256::ZERO;
966        let word_shift = shift >= 128;
967        let bit_shift = shift % 128;
968
969        if word_shift {
970            ret.0 = self.1 << bit_shift
971        } else {
972            ret.0 = self.0 << bit_shift;
973            if bit_shift > 0 {
974                ret.0 += self.1.wrapping_shr(128 - bit_shift);
975            }
976            ret.1 = self.1 << bit_shift;
977        }
978        ret
979    }
980
981    /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` removes any
982    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
983    ///
984    /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is
985    /// restricted to the range of the type, rather than the bits shifted out of the LHS being
986    /// returned to the other end. We do not currently support `rotate_right`.
987    #[must_use = "this returns the result of the operation, without modifying the original"]
988    #[cfg_attr(all(test, mutate), mutate)]
989    fn wrapping_shr(self, rhs: u32) -> Self {
990        let shift = rhs & 0x000000ff;
991
992        let mut ret = U256::ZERO;
993        let word_shift = shift >= 128;
994        let bit_shift = shift % 128;
995
996        if word_shift {
997            ret.1 = self.0 >> bit_shift
998        } else {
999            ret.0 = self.0 >> bit_shift;
1000            ret.1 = self.1 >> bit_shift;
1001            if bit_shift > 0 {
1002                ret.1 += self.0.wrapping_shl(128 - bit_shift);
1003            }
1004        }
1005        ret
1006    }
1007
1008    /// Format `self` to `f` as a decimal when value is known to be non-zero.
1009    fn fmt_decimal(&self, f: &mut fmt::Formatter) -> fmt::Result {
1010        const DIGITS: usize = 78; // U256::MAX has 78 base 10 digits.
1011        const TEN: U256 = U256(0, 10);
1012
1013        let mut buf = [0_u8; DIGITS];
1014        let mut i = DIGITS - 1; // We loop backwards.
1015        let mut cur = *self;
1016
1017        loop {
1018            let digit = (cur % TEN).low_u128() as u8; // Cast after rem 10 is lossless.
1019            buf[i] = digit + b'0';
1020            cur = cur / TEN;
1021            if cur.is_zero() {
1022                break;
1023            }
1024            i -= 1;
1025        }
1026        let s = core::str::from_utf8(&buf[i..]).expect("digits 0-9 are valid UTF8");
1027        f.pad_integral(true, "", s)
1028    }
1029
1030    /// Convert self to f64.
1031    #[inline]
1032    fn to_f64(self) -> f64 {
1033        // Reference: https://blog.m-ou.se/floats/
1034        // Step 1: Get leading zeroes
1035        let leading_zeroes = 256 - self.bits();
1036        // Step 2: Get msb to be farthest left bit
1037        let left_aligned = self.wrapping_shl(leading_zeroes);
1038        // Step 3: Shift msb to fit in lower 53 bits (128-53=75) to get the mantissa
1039        // * Shifting the border of the 2 u128s to line up with mantissa and dropped bits
1040        let middle_aligned = left_aligned >> 75;
1041        // * This is the 53 most significant bits as u128
1042        let mantissa = middle_aligned.0;
1043        // Step 4: Dropped bits (except for last 75 bits) are all in the second u128.
1044        // Bitwise OR the rest of the bits into it, preserving the highest bit,
1045        // so we take the lower 75 bits of middle_aligned.1 and mix it in. (See blog for explanation)
1046        let dropped_bits = middle_aligned.1 | (left_aligned.1 & 0x7FF_FFFF_FFFF_FFFF_FFFF);
1047        // Step 5: The msb of the dropped bits has been preserved, and all other bits
1048        // if any were set, would be set somewhere in the other 127 bits.
1049        // If msb of dropped bits is 0, it is mantissa + 0
1050        // If msb of dropped bits is 1, it is mantissa + 0 only if mantissa lowest bit is 0
1051        // and other bits of the dropped bits are all 0.
1052        // (This is why we only care if the other non-msb dropped bits are all 0 or not,
1053        // so we can just OR them to make sure any bits show up somewhere.)
1054        let mantissa =
1055            (mantissa + ((dropped_bits - (dropped_bits >> 127 & !mantissa)) >> 127)) as u64;
1056        // Step 6: Calculate the exponent
1057        // If self is 0, exponent should be 0 (special meaning) and mantissa will end up 0 too
1058        // Otherwise, (255 - n) + 1022 so it simplifies to 1277 - n
1059        // 1023 and 1022 are the cutoffs for the exponent having the msb next to the decimal point
1060        let exponent = if self == Self::ZERO { 0 } else { 1277 - leading_zeroes as u64 };
1061        // Step 7: sign bit is always 0, exponent is shifted into place
1062        // Use addition instead of bitwise OR to saturate the exponent if mantissa overflows
1063        f64::from_bits((exponent << 52) + mantissa)
1064    }
1065}
1066
1067// Target::MAX as a float value. Calculated with U256::to_f64.
1068// This is validated in the unit tests as well.
1069const TARGET_MAX_F64: f64 = 2.695953529101131e67;
1070
1071impl<T: Into<u128>> From<T> for U256 {
1072    fn from(x: T) -> Self { U256(0, x.into()) }
1073}
1074
1075impl Add for U256 {
1076    type Output = Self;
1077    fn add(self, rhs: Self) -> Self {
1078        let (res, overflow) = self.overflowing_add(rhs);
1079        debug_assert!(!overflow, "Addition of U256 values overflowed");
1080        res
1081    }
1082}
1083
1084impl Sub for U256 {
1085    type Output = Self;
1086    fn sub(self, rhs: Self) -> Self {
1087        let (res, overflow) = self.overflowing_sub(rhs);
1088        debug_assert!(!overflow, "Subtraction of U256 values overflowed");
1089        res
1090    }
1091}
1092
1093impl Mul for U256 {
1094    type Output = Self;
1095    fn mul(self, rhs: Self) -> Self {
1096        let (res, overflow) = self.overflowing_mul(rhs);
1097        debug_assert!(!overflow, "Multiplication of U256 values overflowed");
1098        res
1099    }
1100}
1101
1102impl Div for U256 {
1103    type Output = Self;
1104    fn div(self, rhs: Self) -> Self { self.div_rem(rhs).0 }
1105}
1106
1107impl Rem for U256 {
1108    type Output = Self;
1109    fn rem(self, rhs: Self) -> Self { self.div_rem(rhs).1 }
1110}
1111
1112impl Not for U256 {
1113    type Output = Self;
1114
1115    fn not(self) -> Self { U256(!self.0, !self.1) }
1116}
1117
1118impl Shl<u32> for U256 {
1119    type Output = Self;
1120    fn shl(self, shift: u32) -> U256 { self.wrapping_shl(shift) }
1121}
1122
1123impl Shr<u32> for U256 {
1124    type Output = Self;
1125    fn shr(self, shift: u32) -> U256 { self.wrapping_shr(shift) }
1126}
1127
1128impl fmt::Display for U256 {
1129    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1130        if self.is_zero() {
1131            f.pad_integral(true, "", "0")
1132        } else {
1133            self.fmt_decimal(f)
1134        }
1135    }
1136}
1137
1138impl fmt::Debug for U256 {
1139    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:#x}", self) }
1140}
1141
1142macro_rules! impl_hex {
1143    ($hex:ident, $case:expr) => {
1144        impl $hex for U256 {
1145            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
1146                hex::fmt_hex_exact!(f, 32, &self.to_be_bytes(), $case)
1147            }
1148        }
1149    };
1150}
1151impl_hex!(LowerHex, hex::Case::Lower);
1152impl_hex!(UpperHex, hex::Case::Upper);
1153
1154#[cfg(feature = "serde")]
1155impl crate::serde::Serialize for U256 {
1156    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1157    where
1158        S: crate::serde::Serializer,
1159    {
1160        struct DisplayHex(U256);
1161
1162        impl fmt::Display for DisplayHex {
1163            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:x}", self.0) }
1164        }
1165
1166        if serializer.is_human_readable() {
1167            serializer.collect_str(&DisplayHex(*self))
1168        } else {
1169            let bytes = self.to_be_bytes();
1170            serializer.serialize_bytes(&bytes)
1171        }
1172    }
1173}
1174
1175#[cfg(feature = "serde")]
1176impl<'de> crate::serde::Deserialize<'de> for U256 {
1177    fn deserialize<D: crate::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1178        use hex::FromHex;
1179
1180        use crate::serde::de;
1181
1182        if d.is_human_readable() {
1183            struct HexVisitor;
1184
1185            impl<'de> de::Visitor<'de> for HexVisitor {
1186                type Value = U256;
1187
1188                fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1189                    f.write_str("a 32 byte ASCII hex string")
1190                }
1191
1192                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1193                where
1194                    E: de::Error,
1195                {
1196                    if s.len() != 64 {
1197                        return Err(de::Error::invalid_length(s.len(), &self));
1198                    }
1199
1200                    let b = <[u8; 32]>::from_hex(s)
1201                        .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
1202
1203                    Ok(U256::from_be_bytes(b))
1204                }
1205
1206                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1207                where
1208                    E: de::Error,
1209                {
1210                    if let Ok(hex) = core::str::from_utf8(v) {
1211                        let b = <[u8; 32]>::from_hex(hex).map_err(|_| {
1212                            de::Error::invalid_value(de::Unexpected::Str(hex), &self)
1213                        })?;
1214
1215                        Ok(U256::from_be_bytes(b))
1216                    } else {
1217                        Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
1218                    }
1219                }
1220            }
1221            d.deserialize_str(HexVisitor)
1222        } else {
1223            struct BytesVisitor;
1224
1225            impl<'de> serde::de::Visitor<'de> for BytesVisitor {
1226                type Value = U256;
1227
1228                fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1229                    f.write_str("a sequence of bytes")
1230                }
1231
1232                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1233                where
1234                    E: serde::de::Error,
1235                {
1236                    let b = v.try_into().map_err(|_| de::Error::invalid_length(v.len(), &self))?;
1237                    Ok(U256::from_be_bytes(b))
1238                }
1239            }
1240
1241            d.deserialize_bytes(BytesVisitor)
1242        }
1243    }
1244}
1245
1246/// Splits a 32 byte array into two 16 byte arrays.
1247fn split_in_half(a: [u8; 32]) -> ([u8; 16], [u8; 16]) {
1248    let mut high = [0_u8; 16];
1249    let mut low = [0_u8; 16];
1250
1251    high.copy_from_slice(&a[..16]);
1252    low.copy_from_slice(&a[16..]);
1253
1254    (high, low)
1255}
1256
1257#[cfg(kani)]
1258impl kani::Arbitrary for U256 {
1259    fn any() -> Self {
1260        let high: u128 = kani::any();
1261        let low: u128 = kani::any();
1262        Self(high, low)
1263    }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268    use super::*;
1269
1270    impl<T: Into<u128>> From<T> for Target {
1271        fn from(x: T) -> Self { Self(U256::from(x)) }
1272    }
1273
1274    impl<T: Into<u128>> From<T> for Work {
1275        fn from(x: T) -> Self { Self(U256::from(x)) }
1276    }
1277
1278    impl U256 {
1279        fn bit_at(&self, index: usize) -> bool {
1280            if index > 255 {
1281                panic!("index out of bounds");
1282            }
1283
1284            let word = if index < 128 { self.1 } else { self.0 };
1285            (word & (1 << (index % 128))) != 0
1286        }
1287    }
1288
1289    impl U256 {
1290        /// Creates a U256 from a big-endian array of u64's
1291        fn from_array(a: [u64; 4]) -> Self {
1292            let mut ret = U256::ZERO;
1293            ret.0 = (a[0] as u128) << 64 ^ (a[1] as u128);
1294            ret.1 = (a[2] as u128) << 64 ^ (a[3] as u128);
1295            ret
1296        }
1297    }
1298
1299    #[test]
1300    fn u256_num_bits() {
1301        assert_eq!(U256::from(255_u64).bits(), 8);
1302        assert_eq!(U256::from(256_u64).bits(), 9);
1303        assert_eq!(U256::from(300_u64).bits(), 9);
1304        assert_eq!(U256::from(60000_u64).bits(), 16);
1305        assert_eq!(U256::from(70000_u64).bits(), 17);
1306
1307        let u = U256::from(u128::MAX) << 1;
1308        assert_eq!(u.bits(), 129);
1309
1310        // Try to read the following lines out loud quickly
1311        let mut shl = U256::from(70000_u64);
1312        shl = shl << 100;
1313        assert_eq!(shl.bits(), 117);
1314        shl = shl << 100;
1315        assert_eq!(shl.bits(), 217);
1316        shl = shl << 100;
1317        assert_eq!(shl.bits(), 0);
1318    }
1319
1320    #[test]
1321    fn u256_bit_at() {
1322        assert!(!U256::from(10_u64).bit_at(0));
1323        assert!(U256::from(10_u64).bit_at(1));
1324        assert!(!U256::from(10_u64).bit_at(2));
1325        assert!(U256::from(10_u64).bit_at(3));
1326        assert!(!U256::from(10_u64).bit_at(4));
1327
1328        let u = U256(0xa000_0000_0000_0000_0000_0000_0000_0000, 0);
1329        assert!(u.bit_at(255));
1330        assert!(!u.bit_at(254));
1331        assert!(u.bit_at(253));
1332        assert!(!u.bit_at(252));
1333    }
1334
1335    #[test]
1336    fn u256_lower_hex() {
1337        assert_eq!(
1338            format!("{:x}", U256::from(0xDEADBEEF_u64)),
1339            "00000000000000000000000000000000000000000000000000000000deadbeef",
1340        );
1341        assert_eq!(
1342            format!("{:#x}", U256::from(0xDEADBEEF_u64)),
1343            "0x00000000000000000000000000000000000000000000000000000000deadbeef",
1344        );
1345        assert_eq!(
1346            format!("{:x}", U256::MAX),
1347            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1348        );
1349        assert_eq!(
1350            format!("{:#x}", U256::MAX),
1351            "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1352        );
1353    }
1354
1355    #[test]
1356    fn u256_upper_hex() {
1357        assert_eq!(
1358            format!("{:X}", U256::from(0xDEADBEEF_u64)),
1359            "00000000000000000000000000000000000000000000000000000000DEADBEEF",
1360        );
1361        assert_eq!(
1362            format!("{:#X}", U256::from(0xDEADBEEF_u64)),
1363            "0x00000000000000000000000000000000000000000000000000000000DEADBEEF",
1364        );
1365        assert_eq!(
1366            format!("{:X}", U256::MAX),
1367            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1368        );
1369        assert_eq!(
1370            format!("{:#X}", U256::MAX),
1371            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1372        );
1373    }
1374
1375    #[test]
1376    fn u256_display() {
1377        assert_eq!(format!("{}", U256::from(100_u32)), "100",);
1378        assert_eq!(format!("{}", U256::ZERO), "0",);
1379        assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
1380        assert_eq!(
1381            format!("{}", U256::MAX),
1382            "115792089237316195423570985008687907853269984665640564039457584007913129639935",
1383        );
1384    }
1385
1386    macro_rules! check_format {
1387        ($($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
1388            $(
1389                #[test]
1390                fn $test_name() {
1391                    assert_eq!(format!($format_string, U256::from($val)), $expected);
1392                }
1393            )*
1394        }
1395    }
1396    check_format! {
1397        check_fmt_0, 0_u32, "{}", "0";
1398        check_fmt_1, 0_u32, "{:2}", " 0";
1399        check_fmt_2, 0_u32, "{:02}", "00";
1400
1401        check_fmt_3, 1_u32, "{}", "1";
1402        check_fmt_4, 1_u32, "{:2}", " 1";
1403        check_fmt_5, 1_u32, "{:02}", "01";
1404
1405        check_fmt_10, 10_u32, "{}", "10";
1406        check_fmt_11, 10_u32, "{:2}", "10";
1407        check_fmt_12, 10_u32, "{:02}", "10";
1408        check_fmt_13, 10_u32, "{:3}", " 10";
1409        check_fmt_14, 10_u32, "{:03}", "010";
1410
1411        check_fmt_20, 1_u32, "{:<2}", "1 ";
1412        check_fmt_21, 1_u32, "{:<02}", "01";
1413        check_fmt_22, 1_u32, "{:>2}", " 1"; // This is default but check it anyways.
1414        check_fmt_23, 1_u32, "{:>02}", "01";
1415        check_fmt_24, 1_u32, "{:^3}", " 1 ";
1416        check_fmt_25, 1_u32, "{:^03}", "001";
1417        // Sanity check, for integral types precision is ignored.
1418        check_fmt_30, 0_u32, "{:.1}", "0";
1419        check_fmt_31, 0_u32, "{:4.1}", "   0";
1420        check_fmt_32, 0_u32, "{:04.1}", "0000";
1421    }
1422
1423    #[test]
1424    fn u256_comp() {
1425        let small = U256::from_array([0, 0, 0, 10]);
1426        let big = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]);
1427        let bigger = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x9C8C_3EE7_0C64_4118]);
1428        let biggest = U256::from_array([1, 0, 0x0209_E737_8231_E632, 0x5C8C_3EE7_0C64_4118]);
1429
1430        assert!(small < big);
1431        assert!(big < bigger);
1432        assert!(bigger < biggest);
1433        assert!(bigger <= biggest);
1434        assert!(biggest <= biggest);
1435        assert!(bigger >= big);
1436        assert!(bigger >= small);
1437        assert!(small <= small);
1438    }
1439
1440    const WANT: U256 =
1441        U256(0x1bad_cafe_dead_beef_deaf_babe_2bed_feed, 0xbaad_f00d_defa_ceda_11fe_d2ba_d1c0_ffe0);
1442
1443    #[rustfmt::skip]
1444    const BE_BYTES: [u8; 32] = [
1445        0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed,
1446        0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba, 0xd1, 0xc0, 0xff, 0xe0,
1447    ];
1448
1449    #[rustfmt::skip]
1450    const LE_BYTES: [u8; 32] = [
1451        0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0, 0xad, 0xba,
1452        0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca, 0xad, 0x1b,
1453    ];
1454
1455    // Sanity check that we have the bytes in the correct big-endian order.
1456    #[test]
1457    fn sanity_be_bytes() {
1458        let mut out = [0_u8; 32];
1459        out[..16].copy_from_slice(&WANT.0.to_be_bytes());
1460        out[16..].copy_from_slice(&WANT.1.to_be_bytes());
1461        assert_eq!(out, BE_BYTES);
1462    }
1463
1464    // Sanity check that we have the bytes in the correct little-endian order.
1465    #[test]
1466    fn sanity_le_bytes() {
1467        let mut out = [0_u8; 32];
1468        out[..16].copy_from_slice(&WANT.1.to_le_bytes());
1469        out[16..].copy_from_slice(&WANT.0.to_le_bytes());
1470        assert_eq!(out, LE_BYTES);
1471    }
1472
1473    #[test]
1474    fn u256_to_be_bytes() {
1475        assert_eq!(WANT.to_be_bytes(), BE_BYTES);
1476    }
1477
1478    #[test]
1479    fn u256_from_be_bytes() {
1480        assert_eq!(U256::from_be_bytes(BE_BYTES), WANT);
1481    }
1482
1483    #[test]
1484    fn u256_to_le_bytes() {
1485        assert_eq!(WANT.to_le_bytes(), LE_BYTES);
1486    }
1487
1488    #[test]
1489    fn u256_from_le_bytes() {
1490        assert_eq!(U256::from_le_bytes(LE_BYTES), WANT);
1491    }
1492
1493    #[test]
1494    fn u256_from_u8() {
1495        let u = U256::from(0xbe_u8);
1496        assert_eq!(u, U256(0, 0xbe));
1497    }
1498
1499    #[test]
1500    fn u256_from_u16() {
1501        let u = U256::from(0xbeef_u16);
1502        assert_eq!(u, U256(0, 0xbeef));
1503    }
1504
1505    #[test]
1506    fn u256_from_u32() {
1507        let u = U256::from(0xdeadbeef_u32);
1508        assert_eq!(u, U256(0, 0xdeadbeef));
1509    }
1510
1511    #[test]
1512    fn u256_from_u64() {
1513        let u = U256::from(0xdead_beef_cafe_babe_u64);
1514        assert_eq!(u, U256(0, 0xdead_beef_cafe_babe));
1515    }
1516
1517    #[test]
1518    fn u256_from_u128() {
1519        let u = U256::from(0xdead_beef_cafe_babe_0123_4567_89ab_cdefu128);
1520        assert_eq!(u, U256(0, 0xdead_beef_cafe_babe_0123_4567_89ab_cdef));
1521    }
1522
1523    macro_rules! test_from_unsigned_integer_type {
1524        ($($test_name:ident, $ty:ident);* $(;)?) => {
1525            $(
1526                #[test]
1527                fn $test_name() {
1528                    // Internal representation is big-endian.
1529                    let want = U256(0, 0xAB);
1530
1531                    let x = 0xAB as $ty;
1532                    let got = U256::from(x);
1533
1534                    assert_eq!(got, want);
1535                }
1536            )*
1537        }
1538    }
1539    test_from_unsigned_integer_type! {
1540        from_unsigned_integer_type_u8, u8;
1541        from_unsigned_integer_type_u16, u16;
1542        from_unsigned_integer_type_u32, u32;
1543        from_unsigned_integer_type_u64, u64;
1544        from_unsigned_integer_type_u128, u128;
1545    }
1546
1547    #[test]
1548    fn u256_from_be_array_u64() {
1549        let array = [
1550            0x1bad_cafe_dead_beef,
1551            0xdeaf_babe_2bed_feed,
1552            0xbaad_f00d_defa_ceda,
1553            0x11fe_d2ba_d1c0_ffe0,
1554        ];
1555
1556        let uint = U256::from_array(array);
1557        assert_eq!(uint, WANT);
1558    }
1559
1560    #[test]
1561    fn u256_shift_left() {
1562        let u = U256::from(1_u32);
1563        assert_eq!(u << 0, u);
1564        assert_eq!(u << 1, U256::from(2_u64));
1565        assert_eq!(u << 63, U256::from(0x8000_0000_0000_0000_u64));
1566        assert_eq!(u << 64, U256::from_array([0, 0, 0x0000_0000_0000_0001, 0]));
1567        assert_eq!(u << 127, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1568        assert_eq!(u << 128, U256(1, 0));
1569
1570        let x = U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000);
1571        assert_eq!(x << 1, U256(1, 0));
1572    }
1573
1574    #[test]
1575    fn u256_shift_right() {
1576        let u = U256(1, 0);
1577        assert_eq!(u >> 0, u);
1578        assert_eq!(u >> 1, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1579        assert_eq!(u >> 127, U256(0, 2));
1580        assert_eq!(u >> 128, U256(0, 1));
1581    }
1582
1583    #[test]
1584    fn u256_arithmetic() {
1585        let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1586        let copy = init;
1587
1588        let add = init.wrapping_add(copy);
1589        assert_eq!(add, U256::from_array([0, 0, 1, 0xBD5B_7DDF_BD5B_7DDE]));
1590        // Bitshifts
1591        let shl = add << 88;
1592        assert_eq!(shl, U256::from_array([0, 0x01BD_5B7D, 0xDFBD_5B7D_DE00_0000, 0]));
1593        let shr = shl >> 40;
1594        assert_eq!(shr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0000]));
1595        // Increment
1596        let mut incr = shr;
1597        incr = incr.wrapping_inc();
1598        assert_eq!(incr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0001]));
1599        // Subtraction
1600        let sub = incr.wrapping_sub(init);
1601        assert_eq!(sub, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1602        // Multiplication
1603        let (mult, _) = sub.mul_u64(300);
1604        assert_eq!(mult, U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]));
1605        // Division
1606        assert_eq!(U256::from(105_u32) / U256::from(5_u32), U256::from(21_u32));
1607        let div = mult / U256::from(300_u32);
1608        assert_eq!(div, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1609
1610        assert_eq!(U256::from(105_u32) % U256::from(5_u32), U256::ZERO);
1611        assert_eq!(U256::from(35498456_u32) % U256::from(3435_u32), U256::from(1166_u32));
1612        let rem_src = mult.wrapping_mul(U256::from(39842_u32)).wrapping_add(U256::from(9054_u32));
1613        assert_eq!(rem_src % U256::from(39842_u32), U256::from(9054_u32));
1614    }
1615
1616    #[test]
1617    fn u256_bit_inversion() {
1618        let v = U256(1, 0);
1619        let want = U256(
1620            0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe,
1621            0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff,
1622        );
1623        assert_eq!(!v, want);
1624
1625        let v = U256(0x0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c, 0xeeee_eeee_eeee_eeee);
1626        let want = U256(
1627            0xf3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3,
1628            0xffff_ffff_ffff_ffff_1111_1111_1111_1111,
1629        );
1630        assert_eq!(!v, want);
1631    }
1632
1633    #[test]
1634    fn u256_mul_u64_by_one() {
1635        let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1636        assert_eq!(v, v.mul_u64(1_u64).0);
1637    }
1638
1639    #[test]
1640    fn u256_mul_u64_by_zero() {
1641        let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1642        assert_eq!(U256::ZERO, v.mul_u64(0_u64).0);
1643    }
1644
1645    #[test]
1646    fn u256_mul_u64() {
1647        let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1648
1649        let u96_res = u64_val.mul_u64(0xFFFF_FFFF).0;
1650        let u128_res = u96_res.mul_u64(0xFFFF_FFFF).0;
1651        let u160_res = u128_res.mul_u64(0xFFFF_FFFF).0;
1652        let u192_res = u160_res.mul_u64(0xFFFF_FFFF).0;
1653        let u224_res = u192_res.mul_u64(0xFFFF_FFFF).0;
1654        let u256_res = u224_res.mul_u64(0xFFFF_FFFF).0;
1655
1656        assert_eq!(u96_res, U256::from_array([0, 0, 0xDEAD_BEEE, 0xFFFF_FFFF_2152_4111]));
1657        assert_eq!(
1658            u128_res,
1659            U256::from_array([0, 0, 0xDEAD_BEEE_2152_4110, 0x2152_4111_DEAD_BEEF])
1660        );
1661        assert_eq!(
1662            u160_res,
1663            U256::from_array([0, 0xDEAD_BEED, 0x42A4_8222_0000_0001, 0xBD5B_7DDD_2152_4111])
1664        );
1665        assert_eq!(
1666            u192_res,
1667            U256::from_array([
1668                0,
1669                0xDEAD_BEEC_63F6_C334,
1670                0xBD5B_7DDF_BD5B_7DDB,
1671                0x63F6_C333_DEAD_BEEF
1672            ])
1673        );
1674        assert_eq!(
1675            u224_res,
1676            U256::from_array([
1677                0xDEAD_BEEB,
1678                0x8549_0448_5964_BAAA,
1679                0xFFFF_FFFB_A69B_4558,
1680                0x7AB6_FBBB_2152_4111
1681            ])
1682        );
1683        assert_eq!(
1684            u256_res,
1685            U256(
1686                0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1687                0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1688            )
1689        );
1690    }
1691
1692    #[test]
1693    fn u256_addition() {
1694        let x = U256::from(u128::MAX);
1695        let (add, overflow) = x.overflowing_add(U256::ONE);
1696        assert!(!overflow);
1697        assert_eq!(add, U256(1, 0));
1698
1699        let (add, _) = add.overflowing_add(U256::ONE);
1700        assert_eq!(add, U256(1, 1));
1701    }
1702
1703    #[test]
1704    fn u256_subtraction() {
1705        let (sub, overflow) = U256::ONE.overflowing_sub(U256::ONE);
1706        assert!(!overflow);
1707        assert_eq!(sub, U256::ZERO);
1708
1709        let x = U256(1, 0);
1710        let (sub, overflow) = x.overflowing_sub(U256::ONE);
1711        assert!(!overflow);
1712        assert_eq!(sub, U256::from(u128::MAX));
1713    }
1714
1715    #[test]
1716    fn u256_multiplication() {
1717        let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1718
1719        let u128_res = u64_val.wrapping_mul(u64_val);
1720
1721        assert_eq!(u128_res, U256(0, 0xC1B1_CD13_A4D1_3D46_048D_1354_216D_A321));
1722
1723        let u256_res = u128_res.wrapping_mul(u128_res);
1724
1725        assert_eq!(
1726            u256_res,
1727            U256(
1728                0x928D_92B4_D7F5_DF33_4AFC_FF6F_0375_C608,
1729                0xF5CF_7F36_18C2_C886_F4E1_66AA_D40D_0A41,
1730            )
1731        );
1732    }
1733
1734    #[test]
1735    fn u256_multiplication_bits_in_each_word() {
1736        // Put a digit in the least significant bit of each 64 bit word.
1737        let u = 1_u128 << 64 | 1_u128;
1738        let x = U256(u, u);
1739
1740        // Put a digit in the second least significant bit of each 64 bit word.
1741        let u = 2_u128 << 64 | 2_u128;
1742        let y = U256(u, u);
1743
1744        let (got, overflow) = x.overflowing_mul(y);
1745
1746        let want = U256(
1747            0x0000_0000_0000_0008_0000_0000_0000_0008,
1748            0x0000_0000_0000_0006_0000_0000_0000_0004,
1749        );
1750        assert!(!overflow);
1751        assert_eq!(got, want)
1752    }
1753
1754    #[test]
1755    fn u256_increment() {
1756        let mut val = U256(
1757            0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1758            0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
1759        );
1760        val = val.wrapping_inc();
1761        assert_eq!(
1762            val,
1763            U256(
1764                0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1765                0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1766            )
1767        );
1768        val = val.wrapping_inc();
1769        assert_eq!(
1770            val,
1771            U256(
1772                0xF000_0000_0000_0000_0000_0000_0000_0000,
1773                0x0000_0000_0000_0000_0000_0000_0000_0000,
1774            )
1775        );
1776
1777        assert_eq!(U256::MAX.wrapping_inc(), U256::ZERO);
1778    }
1779
1780    #[test]
1781    fn u256_extreme_bitshift() {
1782        // Shifting a u64 by 64 bits gives an undefined value, so make sure that
1783        // we're doing the Right Thing here
1784        let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1785
1786        assert_eq!(init << 64, U256(0, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000));
1787        let add = (init << 64).wrapping_add(init);
1788        assert_eq!(add, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1789        assert_eq!(add >> 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1790        assert_eq!(add << 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1791        assert_eq!(add >> 64, U256(0, 0x0000_0000_0000_0000_DEAD_BEEF_DEAD_BEEF));
1792        assert_eq!(
1793            add << 64,
1794            U256(0xDEAD_BEEF_DEAD_BEEF, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000)
1795        );
1796    }
1797
1798    #[test]
1799    fn u256_to_from_hex_roundtrips() {
1800        let val = U256(
1801            0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1802            0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1803        );
1804        let hex = format!("0x{:x}", val);
1805        let got = U256::from_hex(&hex).expect("failed to parse hex");
1806        assert_eq!(got, val);
1807    }
1808
1809    #[test]
1810    fn u256_to_from_unprefixed_hex_roundtrips() {
1811        let val = U256(
1812            0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1813            0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1814        );
1815        let hex = format!("{:x}", val);
1816        let got = U256::from_unprefixed_hex(&hex).expect("failed to parse hex");
1817        assert_eq!(got, val);
1818    }
1819
1820    #[test]
1821    fn u256_from_hex_32_characters_long() {
1822        let hex = "a69b455cd41bb662a69b4555deadbeef";
1823        let want = U256(0x00, 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF);
1824        let got = U256::from_unprefixed_hex(hex).expect("failed to parse hex");
1825        assert_eq!(got, want);
1826    }
1827
1828    #[cfg(feature = "serde")]
1829    #[test]
1830    fn u256_serde() {
1831        let check = |uint, hex| {
1832            let json = format!("\"{}\"", hex);
1833            assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
1834            assert_eq!(::serde_json::from_str::<U256>(&json).unwrap(), uint);
1835
1836            let bin_encoded = bincode::serialize(&uint).unwrap();
1837            let bin_decoded: U256 = bincode::deserialize(&bin_encoded).unwrap();
1838            assert_eq!(bin_decoded, uint);
1839        };
1840
1841        check(U256::ZERO, "0000000000000000000000000000000000000000000000000000000000000000");
1842        check(
1843            U256::from(0xDEADBEEF_u32),
1844            "00000000000000000000000000000000000000000000000000000000deadbeef",
1845        );
1846        check(
1847            U256::from_array([0xdd44, 0xcc33, 0xbb22, 0xaa11]),
1848            "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
1849        );
1850        check(U256::MAX, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1851        check(
1852            U256(
1853                0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1854                0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1855            ),
1856            "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
1857        );
1858
1859        assert!(::serde_json::from_str::<U256>(
1860            "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
1861        )
1862        .is_err()); // invalid char
1863        assert!(::serde_json::from_str::<U256>(
1864            "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1865        )
1866        .is_err()); // invalid length
1867        assert!(::serde_json::from_str::<U256>(
1868            "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1869        )
1870        .is_err()); // invalid length
1871    }
1872
1873    #[test]
1874    fn u256_is_max_correct_negative() {
1875        let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::MAX)];
1876        for t in tc {
1877            assert!(!t.is_max())
1878        }
1879    }
1880
1881    #[test]
1882    fn u256_is_max_correct_positive() {
1883        assert!(U256::MAX.is_max());
1884
1885        let u = u128::MAX;
1886        assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
1887    }
1888
1889    #[test]
1890    fn compact_target_from_hex_lower() {
1891        let target = CompactTarget::from_hex("0x010034ab").unwrap();
1892        assert_eq!(target, CompactTarget(0x010034ab));
1893    }
1894
1895    #[test]
1896    fn compact_target_from_hex_upper() {
1897        let target = CompactTarget::from_hex("0X010034AB").unwrap();
1898        assert_eq!(target, CompactTarget(0x010034ab));
1899    }
1900
1901    #[test]
1902    fn compact_target_from_unprefixed_hex_lower() {
1903        let target = CompactTarget::from_unprefixed_hex("010034ab").unwrap();
1904        assert_eq!(target, CompactTarget(0x010034ab));
1905    }
1906
1907    #[test]
1908    fn compact_target_from_unprefixed_hex_upper() {
1909        let target = CompactTarget::from_unprefixed_hex("010034AB").unwrap();
1910        assert_eq!(target, CompactTarget(0x010034ab));
1911    }
1912
1913    #[test]
1914    fn compact_target_from_hex_invalid_hex_should_err() {
1915        let hex = "0xzbf9";
1916        let result = CompactTarget::from_hex(hex);
1917        assert!(result.is_err());
1918    }
1919
1920    #[test]
1921    fn compact_target_lower_hex_and_upper_hex() {
1922        assert_eq!(format!("{:08x}", CompactTarget(0x01D0F456)), "01d0f456");
1923        assert_eq!(format!("{:08X}", CompactTarget(0x01d0f456)), "01D0F456");
1924    }
1925
1926    #[test]
1927    fn compact_target_from_upwards_difficulty_adjustment() {
1928        let params = Params::new(crate::Network::Signet);
1929        let starting_bits = CompactTarget::from_consensus(503543726); // Genesis compact target on Signet
1930        let start_time: u64 = 1598918400; // Genesis block unix time
1931        let end_time: u64 = 1599332177; // Block 2015 unix time
1932        let timespan = end_time - start_time; // Faster than expected
1933        let adjustment = CompactTarget::from_next_work_required(starting_bits, timespan, &params);
1934        let adjustment_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target
1935        assert_eq!(adjustment, adjustment_bits);
1936    }
1937
1938    #[test]
1939    fn compact_target_from_downwards_difficulty_adjustment() {
1940        let params = Params::new(crate::Network::Signet);
1941        let starting_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target
1942        let start_time: u64 = 1599332844; // Block 2016 unix time
1943        let end_time: u64 = 1600591200; // Block 4031 unix time
1944        let timespan = end_time - start_time; // Slower than expected
1945        let adjustment = CompactTarget::from_next_work_required(starting_bits, timespan, &params);
1946        let adjustment_bits = CompactTarget::from_consensus(503397348); // Block 4032 compact target
1947        assert_eq!(adjustment, adjustment_bits);
1948    }
1949
1950    #[test]
1951    fn compact_target_from_upwards_difficulty_adjustment_using_headers() {
1952        use crate::{block::Version, constants::genesis_block, TxMerkleNode};
1953        use hashes::Hash;
1954        let params = Params::new(crate::Network::Signet);
1955        let epoch_start = genesis_block(&params).header;
1956        // Block 2015, the only information used are `bits` and `time`
1957        let current = Header {
1958            version: Version::ONE,
1959            prev_blockhash: BlockHash::all_zeros(),
1960            merkle_root: TxMerkleNode::all_zeros(),
1961            time: 1599332177,
1962            bits: epoch_start.bits,
1963            nonce: epoch_start.nonce
1964        };
1965        let adjustment = CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params);
1966        let adjustment_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target
1967        assert_eq!(adjustment, adjustment_bits);
1968    }
1969
1970    #[test]
1971    fn compact_target_from_downwards_difficulty_adjustment_using_headers() {
1972        use crate::{block::Version, TxMerkleNode};
1973        use hashes::Hash;
1974        let params = Params::new(crate::Network::Signet);
1975        let starting_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target
1976        // Block 2016, the only information used is `time`
1977        let epoch_start = Header {
1978            version: Version::ONE,
1979            prev_blockhash: BlockHash::all_zeros(),
1980            merkle_root: TxMerkleNode::all_zeros(),
1981            time: 1599332844,
1982            bits: starting_bits,
1983            nonce: 0
1984        };
1985        // Block 4031, the only information used are `bits` and `time`
1986        let current = Header {
1987            version: Version::ONE,
1988            prev_blockhash: BlockHash::all_zeros(),
1989            merkle_root: TxMerkleNode::all_zeros(),
1990            time: 1600591200,
1991            bits: starting_bits,
1992            nonce: 0
1993        };
1994        let adjustment = CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params);
1995        let adjustment_bits = CompactTarget::from_consensus(503397348); // Block 4032 compact target
1996        assert_eq!(adjustment, adjustment_bits);
1997    }
1998
1999    #[test]
2000    fn compact_target_from_maximum_upward_difficulty_adjustment() {
2001        let params = Params::new(crate::Network::Signet);
2002        let starting_bits = CompactTarget::from_consensus(503403001);
2003        let timespan = (0.2 * params.pow_target_timespan as f64) as u64;
2004        let got = CompactTarget::from_next_work_required(starting_bits, timespan, params);
2005        let want = Target::from_compact(starting_bits)
2006            .min_transition_threshold()
2007            .to_compact_lossy();
2008        assert_eq!(got, want);
2009    }
2010
2011    #[test]
2012    fn compact_target_from_minimum_downward_difficulty_adjustment() {
2013        let params = Params::new(crate::Network::Signet);
2014        let starting_bits = CompactTarget::from_consensus(403403001); // High difficulty for Signet
2015        let timespan =  5 * params.pow_target_timespan; // Really slow.
2016        let got = CompactTarget::from_next_work_required(starting_bits, timespan, &params);
2017        let want = Target::from_compact(starting_bits)
2018            .max_transition_threshold(params)
2019            .to_compact_lossy();
2020        assert_eq!(got, want);
2021    }
2022
2023    #[test]
2024    fn compact_target_from_adjustment_is_max_target() {
2025        let params = Params::new(crate::Network::Signet);
2026        let starting_bits = CompactTarget::from_consensus(503543726); // Genesis compact target on Signet
2027        let timespan =  5 * params.pow_target_timespan; // Really slow.
2028        let got = CompactTarget::from_next_work_required(starting_bits, timespan, &params);
2029        let want = params.max_attainable_target.to_compact_lossy();
2030        assert_eq!(got, want);
2031    }
2032
2033    #[test]
2034    fn target_from_compact() {
2035        // (nBits, target)
2036        let tests = vec![
2037            (0x0100_3456_u32, 0x00_u64), // High bit set.
2038            (0x0112_3456_u32, 0x12_u64),
2039            (0x0200_8000_u32, 0x80_u64),
2040            (0x0500_9234_u32, 0x9234_0000_u64),
2041            (0x0492_3456_u32, 0x00_u64), // High bit set (0x80 in 0x92).
2042            (0x0412_3456_u32, 0x1234_5600_u64), // Inverse of above; no high bit.
2043        ];
2044
2045        for (n_bits, target) in tests {
2046            let want = Target::from(target);
2047            let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
2048            assert_eq!(got, want);
2049        }
2050    }
2051
2052    #[test]
2053    fn target_is_met_by_for_target_equals_hash() {
2054        use std::str::FromStr;
2055
2056        use hashes::Hash;
2057
2058        let hash =
2059            BlockHash::from_str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")
2060                .expect("failed to parse block hash");
2061        let target = Target(U256::from_le_bytes(hash.to_byte_array()));
2062        assert!(target.is_met_by(hash));
2063    }
2064
2065    #[test]
2066    fn max_target_from_compact() {
2067        // The highest possible target is defined as 0x1d00ffff
2068        let bits = 0x1d00ffff_u32;
2069        let want = Target::MAX;
2070        let got = Target::from_compact(CompactTarget::from_consensus(bits));
2071        assert_eq!(got, want)
2072    }
2073
2074    #[test]
2075    fn target_difficulty_float() {
2076        assert_eq!(Target::MAX.difficulty_float(), 1.0_f64);
2077        assert_eq!(
2078            Target::from_compact(CompactTarget::from_consensus(0x1c00ffff_u32)).difficulty_float(),
2079            256.0_f64
2080        );
2081        assert_eq!(
2082            Target::from_compact(CompactTarget::from_consensus(0x1b00ffff_u32)).difficulty_float(),
2083            65536.0_f64
2084        );
2085        assert_eq!(
2086            Target::from_compact(CompactTarget::from_consensus(0x1a00f3a2_u32)).difficulty_float(),
2087            17628585.065897066_f64
2088        );
2089    }
2090
2091    #[test]
2092    fn roundtrip_compact_target() {
2093        let consensus = 0x1d00_ffff;
2094        let compact = CompactTarget::from_consensus(consensus);
2095        let t = Target::from_compact(CompactTarget::from_consensus(consensus));
2096        assert_eq!(t, Target::from(compact)); // From/Into sanity check.
2097
2098        let back = t.to_compact_lossy();
2099        assert_eq!(back, compact); // From/Into sanity check.
2100
2101        assert_eq!(back.to_consensus(), consensus);
2102    }
2103
2104    #[test]
2105    fn roundtrip_target_work() {
2106        let target = Target::from(0xdeadbeef_u32);
2107        let work = target.to_work();
2108        let back = work.to_target();
2109        assert_eq!(back, target)
2110    }
2111
2112    #[cfg(feature = "std")]
2113    #[test]
2114    fn work_log2() {
2115        // Compare work log2 to historical Bitcoin Core values found in Core logs.
2116        let tests: Vec<(u128, f64)> = vec![
2117            // (chainwork, core log2)                // height
2118            (0x200020002, 33.000022),                // 1
2119            (0xa97d67041c5e51596ee7, 79.405055),     // 308004
2120            (0x1dc45d79394baa8ab18b20, 84.895644),   // 418141
2121            (0x8c85acb73287e335d525b98, 91.134654),  // 596624
2122            (0x2ef447e01d1642c40a184ada, 93.553183), // 738965
2123        ];
2124
2125        for (chainwork, core_log2) in tests {
2126            // Core log2 in the logs is rounded to 6 decimal places.
2127            let log2 = (Work::from(chainwork).log2() * 1e6).round() / 1e6;
2128            assert_eq!(log2, core_log2)
2129        }
2130
2131        assert_eq!(Work(U256::ONE).log2(), 0.0);
2132        assert_eq!(Work(U256::MAX).log2(), 256.0);
2133    }
2134
2135    #[test]
2136    fn u256_zero_min_max_inverse() {
2137        assert_eq!(U256::MAX.inverse(), U256::ONE);
2138        assert_eq!(U256::ONE.inverse(), U256::MAX);
2139        assert_eq!(U256::ZERO.inverse(), U256::MAX);
2140    }
2141
2142    #[test]
2143    fn u256_max_min_inverse_roundtrip() {
2144        let max = U256::MAX;
2145
2146        for min in [U256::ZERO, U256::ONE].iter() {
2147            // lower target means more work required.
2148            assert_eq!(Target(max).to_work(), Work(U256::ONE));
2149            assert_eq!(Target(*min).to_work(), Work(max));
2150
2151            assert_eq!(Work(max).to_target(), Target(U256::ONE));
2152            assert_eq!(Work(*min).to_target(), Target(max));
2153        }
2154    }
2155
2156    #[test]
2157    fn u256_wrapping_add_wraps_at_boundary() {
2158        assert_eq!(U256::MAX.wrapping_add(U256::ONE), U256::ZERO);
2159        assert_eq!(U256::MAX.wrapping_add(U256::from(2_u8)), U256::ONE);
2160    }
2161
2162    #[test]
2163    fn u256_wrapping_sub_wraps_at_boundary() {
2164        assert_eq!(U256::ZERO.wrapping_sub(U256::ONE), U256::MAX);
2165        assert_eq!(U256::ONE.wrapping_sub(U256::from(2_u8)), U256::MAX);
2166    }
2167
2168    #[test]
2169    fn mul_u64_overflows() {
2170        let (_, overflow) = U256::MAX.mul_u64(2);
2171        assert!(overflow, "max * 2 should overflow");
2172    }
2173
2174    #[test]
2175    #[cfg(debug_assertions)]
2176    #[should_panic]
2177    fn u256_overflowing_addition_panics() { let _ = U256::MAX + U256::ONE; }
2178
2179    #[test]
2180    #[cfg(debug_assertions)]
2181    #[should_panic]
2182    fn u256_overflowing_subtraction_panics() { let _ = U256::ZERO - U256::ONE; }
2183
2184    #[test]
2185    #[cfg(debug_assertions)]
2186    #[should_panic]
2187    fn u256_multiplication_by_max_panics() { let _ = U256::MAX * U256::MAX; }
2188
2189    #[test]
2190    #[cfg(debug_assertions)]
2191    #[should_panic]
2192    fn work_overflowing_addition_panics() { let _ = Work(U256::MAX) + Work(U256::ONE); }
2193
2194    #[test]
2195    #[cfg(debug_assertions)]
2196    #[should_panic]
2197    fn work_overflowing_subtraction_panics() { let _ = Work(U256::ZERO) - Work(U256::ONE); }
2198
2199    #[test]
2200    fn u256_to_f64() {
2201        // Validate that the Target::MAX value matches the constant also used in difficulty calculation.
2202        assert_eq!(Target::MAX.0.to_f64(), TARGET_MAX_F64);
2203        assert_eq!(U256::ZERO.to_f64(), 0.0_f64);
2204        assert_eq!(U256::ONE.to_f64(), 1.0_f64);
2205        assert_eq!(U256::MAX.to_f64(), 1.157920892373162e77_f64);
2206        assert_eq!((U256::MAX >> 1).to_f64(), 5.78960446186581e76_f64);
2207        assert_eq!((U256::MAX >> 128).to_f64(), 3.402823669209385e38_f64);
2208        assert_eq!((U256::MAX >> (256 - 54)).to_f64(), 1.8014398509481984e16_f64);
2209        // 53 bits and below should not use exponents
2210        assert_eq!((U256::MAX >> (256 - 53)).to_f64(), 9007199254740991.0_f64);
2211        assert_eq!((U256::MAX >> (256 - 32)).to_f64(), 4294967295.0_f64);
2212        assert_eq!((U256::MAX >> (256 - 16)).to_f64(), 65535.0_f64);
2213        assert_eq!((U256::MAX >> (256 - 8)).to_f64(), 255.0_f64);
2214    }
2215}
2216
2217#[cfg(kani)]
2218mod verification {
2219    use super::*;
2220
2221    #[kani::unwind(5)] // mul_u64 loops over 4 64 bit ints so use one more than 4
2222    #[kani::proof]
2223    fn check_mul_u64() {
2224        let x: U256 = kani::any();
2225        let y: u64 = kani::any();
2226
2227        let _ = x.mul_u64(y);
2228    }
2229}