1use core::fmt::{self, LowerHex, UpperHex};
10use core::ops::{Add, Div, Mul, Not, Rem, Shl, Shr, Sub};
11
12#[cfg(all(test, mutate))]
13use mutagen::mutate;
14
15use crate::consensus::encode::{self, Decodable, Encodable};
16#[cfg(doc)]
17use crate::consensus::Params;
18use crate::hash_types::BlockHash;
19use crate::io::{self, Read, Write};
20use crate::prelude::String;
21use crate::string::FromHexStr;
22
23macro_rules! do_impl {
25 ($ty:ident) => {
26 impl $ty {
27 #[inline]
29 pub fn from_be_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_be_bytes(bytes)) }
30
31 #[inline]
33 pub fn from_le_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_le_bytes(bytes)) }
34
35 #[inline]
37 pub fn to_be_bytes(self) -> [u8; 32] { self.0.to_be_bytes() }
38
39 #[inline]
41 pub fn to_le_bytes(self) -> [u8; 32] { self.0.to_le_bytes() }
42 }
43
44 impl fmt::Display for $ty {
45 #[inline]
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
47 }
48
49 impl fmt::LowerHex for $ty {
50 #[inline]
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
52 }
53
54 impl fmt::UpperHex for $ty {
55 #[inline]
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) }
57 }
58 };
59}
60
61#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
65#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
66#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
67pub struct Work(U256);
68
69impl Work {
70 pub fn to_target(self) -> Target { Target(self.0.inverse()) }
72
73 #[cfg(feature = "std")]
79 pub fn log2(self) -> f64 { self.0.to_f64().log2() }
80}
81do_impl!(Work);
82
83impl Add for Work {
84 type Output = Work;
85 fn add(self, rhs: Self) -> Self { Work(self.0 + rhs.0) }
86}
87
88impl Sub for Work {
89 type Output = Work;
90 fn sub(self, rhs: Self) -> Self { Work(self.0 - rhs.0) }
91}
92
93#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
102#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
103pub struct Target(U256);
104
105impl Target {
106 pub const ZERO: Target = Target(U256::ZERO);
108 pub const MAX: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
118
119 pub const MAX_ATTAINABLE_MAINNET: Self = Target(U256(0x0FFF_FFFF_FFFF_u128 << (208 - 128), 0));
124
125 pub const MAX_ATTAINABLE_TESTNET: Self = Target(U256(0x00FF_FFFF_FFFF_FFFF_u128 << (208 - 128), 0));
129
130 pub const MAX_ATTAINABLE_REGTEST: Self = Target(U256(0x00FF_FFFF_FFFF_FFFF_u128 << 96, 0));
134
135 pub const MAX_ATTAINABLE_SIGNET: Self = Target(U256(0x0377_ae00_u128 << 80, 0));
139
140 #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
144 pub const fn max_value() -> Self { Target::MAX }
145
146 pub fn from_compact(c: CompactTarget) -> Target {
150 let bits = c.0;
151 let (mant, expt) = {
156 let unshifted_expt = bits >> 24;
157 if unshifted_expt <= 3 {
158 ((bits & 0xFFFFFF) >> (8 * (3 - unshifted_expt as usize)), 0)
159 } else {
160 (bits & 0xFFFFFF, 8 * ((bits >> 24) - 3))
161 }
162 };
163
164 if mant > 0x7F_FFFF {
166 Target::ZERO
167 } else {
168 Target(U256::from(mant) << expt)
169 }
170 }
171
172 pub fn to_compact_lossy(self) -> CompactTarget {
177 let mut size = (self.0.bits() + 7) / 8;
178 let mut compact = if size <= 3 {
179 (self.0.low_u64() << (8 * (3 - size))) as u32
180 } else {
181 let bn = self.0 >> (8 * (size - 3));
182 bn.low_u32()
183 };
184
185 if (compact & 0x0080_0000) != 0 {
186 compact >>= 8;
187 size += 1;
188 }
189
190 CompactTarget(compact | (size << 24))
191 }
192
193 #[cfg_attr(all(test, mutate), mutate)]
198 pub fn is_met_by(&self, hash: BlockHash) -> bool {
199 use hashes::Hash;
200 let hash = U256::from_le_bytes(hash.to_byte_array());
201 hash <= self.0
202 }
203
204 pub fn to_work(self) -> Work { Work(self.0.inverse()) }
210
211 #[cfg_attr(all(test, mutate), mutate)]
232 pub fn difficulty(&self) -> u128 {
233 let d = Target::MAX.0 / self.0;
234 d.saturating_to_u128()
235 }
236
237 #[cfg_attr(all(test, mutate), mutate)]
243 pub fn difficulty_float(&self) -> f64 { TARGET_MAX_F64 / self.0.to_f64() }
244
245 pub fn min_difficulty_transition_threshold(&self) -> Self { Self(self.0 >> 2) }
251
252 pub fn max_difficulty_transition_threshold(&self) -> Self { Self(self.0 << 2) }
258}
259do_impl!(Target);
260
261#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
269#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
270#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
271pub struct CompactTarget(u32);
272
273impl CompactTarget {
274 pub fn from_consensus(bits: u32) -> Self { Self(bits) }
276
277 pub fn to_consensus(self) -> u32 { self.0 }
279}
280
281impl From<CompactTarget> for Target {
282 fn from(c: CompactTarget) -> Self { Target::from_compact(c) }
283}
284
285impl FromHexStr for CompactTarget {
286 type Error = crate::parse::ParseIntError;
287
288 fn from_hex_str_no_prefix<S: AsRef<str> + Into<String>>(s: S) -> Result<Self, Self::Error> {
289 let compact_target = crate::parse::hex_u32(s)?;
290 Ok(Self::from_consensus(compact_target))
291 }
292}
293
294impl Encodable for CompactTarget {
295 #[inline]
296 fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
297 self.0.consensus_encode(w)
298 }
299}
300
301impl Decodable for CompactTarget {
302 #[inline]
303 fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
304 u32::consensus_decode(r).map(CompactTarget)
305 }
306}
307
308#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
311struct U256(u128, u128);
312
313impl U256 {
314 const MAX: U256 =
315 U256(0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
316
317 const ZERO: U256 = U256(0, 0);
318
319 const ONE: U256 = U256(0, 1);
320
321 #[cfg_attr(all(test, mutate), mutate)]
323 fn from_be_bytes(a: [u8; 32]) -> U256 {
324 let (high, low) = split_in_half(a);
325 let big = u128::from_be_bytes(high);
326 let little = u128::from_be_bytes(low);
327 U256(big, little)
328 }
329
330 #[cfg_attr(all(test, mutate), mutate)]
332 fn from_le_bytes(a: [u8; 32]) -> U256 {
333 let (high, low) = split_in_half(a);
334 let little = u128::from_le_bytes(high);
335 let big = u128::from_le_bytes(low);
336 U256(big, little)
337 }
338
339 #[cfg_attr(all(test, mutate), mutate)]
341 fn to_be_bytes(self) -> [u8; 32] {
342 let mut out = [0; 32];
343 out[..16].copy_from_slice(&self.0.to_be_bytes());
344 out[16..].copy_from_slice(&self.1.to_be_bytes());
345 out
346 }
347
348 #[cfg_attr(all(test, mutate), mutate)]
350 fn to_le_bytes(self) -> [u8; 32] {
351 let mut out = [0; 32];
352 out[..16].copy_from_slice(&self.1.to_le_bytes());
353 out[16..].copy_from_slice(&self.0.to_le_bytes());
354 out
355 }
356
357 fn inverse(&self) -> U256 {
363 if self.is_zero() {
366 return U256::MAX;
367 }
368 if self.is_one() {
370 return U256::MAX;
371 }
372 if self.is_max() {
374 return U256::ONE;
375 }
376
377 let ret = !*self / self.wrapping_inc();
378 ret.wrapping_inc()
379 }
380
381 #[cfg_attr(all(test, mutate), mutate)]
382 fn is_zero(&self) -> bool { self.0 == 0 && self.1 == 0 }
383
384 #[cfg_attr(all(test, mutate), mutate)]
385 fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 }
386
387 #[cfg_attr(all(test, mutate), mutate)]
388 fn is_max(&self) -> bool { self.0 == u128::MAX && self.1 == u128::MAX }
389
390 fn low_u32(&self) -> u32 { self.low_u128() as u32 }
392
393 fn low_u64(&self) -> u64 { self.low_u128() as u64 }
395
396 fn low_u128(&self) -> u128 { self.1 }
398
399 fn saturating_to_u128(&self) -> u128 {
402 if *self > U256::from(u128::MAX) {
403 u128::MAX
404 } else {
405 self.low_u128()
406 }
407 }
408
409 #[cfg_attr(all(test, mutate), mutate)]
411 fn bits(&self) -> u32 {
412 if self.0 > 0 {
413 256 - self.0.leading_zeros()
414 } else {
415 128 - self.1.leading_zeros()
416 }
417 }
418
419 #[cfg_attr(all(test, mutate), mutate)]
428 fn mul_u64(self, rhs: u64) -> (U256, bool) {
429 let mut carry: u128 = 0;
430 let mut split_le =
431 [self.1 as u64, (self.1 >> 64) as u64, self.0 as u64, (self.0 >> 64) as u64];
432
433 for word in &mut split_le {
434 let n = carry + u128::from(rhs) * u128::from(*word);
437
438 *word = n as u64; carry = n >> 64; }
441
442 let low = u128::from(split_le[0]) | u128::from(split_le[1]) << 64;
443 let high = u128::from(split_le[2]) | u128::from(split_le[3]) << 64;
444 (Self(high, low), carry != 0)
445 }
446
447 #[cfg_attr(all(test, mutate), mutate)]
457 fn div_rem(self, rhs: Self) -> (Self, Self) {
458 let mut sub_copy = self;
459 let mut shift_copy = rhs;
460 let mut ret = [0u128; 2];
461
462 let my_bits = self.bits();
463 let your_bits = rhs.bits();
464
465 assert!(your_bits != 0, "attempted to divide {} by zero", self);
467
468 if my_bits < your_bits {
470 return (U256::ZERO, sub_copy);
471 }
472
473 let mut shift = my_bits - your_bits;
475 shift_copy = shift_copy << shift;
476 loop {
477 if sub_copy >= shift_copy {
478 ret[1 - (shift / 128) as usize] |= 1 << (shift % 128);
479 sub_copy = sub_copy.wrapping_sub(shift_copy);
480 }
481 shift_copy = shift_copy >> 1;
482 if shift == 0 {
483 break;
484 }
485 shift -= 1;
486 }
487
488 (U256(ret[0], ret[1]), sub_copy)
489 }
490
491 #[must_use = "this returns the result of the operation, without modifying the original"]
496 #[cfg_attr(all(test, mutate), mutate)]
497 fn overflowing_add(self, rhs: Self) -> (Self, bool) {
498 let mut ret = U256::ZERO;
499 let mut ret_overflow = false;
500
501 let (high, overflow) = self.0.overflowing_add(rhs.0);
502 ret.0 = high;
503 ret_overflow |= overflow;
504
505 let (low, overflow) = self.1.overflowing_add(rhs.1);
506 ret.1 = low;
507 if overflow {
508 let (high, overflow) = ret.0.overflowing_add(1);
509 ret.0 = high;
510 ret_overflow |= overflow;
511 }
512
513 (ret, ret_overflow)
514 }
515
516 #[must_use = "this returns the result of the operation, without modifying the original"]
521 #[cfg_attr(all(test, mutate), mutate)]
522 fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
523 let ret = self.wrapping_add(!rhs).wrapping_add(Self::ONE);
524 let overflow = rhs > self;
525 (ret, overflow)
526 }
527
528 #[must_use = "this returns the result of the operation, without modifying the original"]
534 #[cfg_attr(all(test, mutate), mutate)]
535 fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
536 let mut ret = U256::ZERO;
537 let mut ret_overflow = false;
538
539 for i in 0..3 {
540 let to_mul = (rhs >> (64 * i)).low_u64();
541 let (mul_res, _) = self.mul_u64(to_mul);
542 ret = ret.wrapping_add(mul_res << (64 * i));
543 }
544
545 let to_mul = (rhs >> 192).low_u64();
546 let (mul_res, overflow) = self.mul_u64(to_mul);
547 ret_overflow |= overflow;
548 let (sum, overflow) = ret.overflowing_add(mul_res);
549 ret = sum;
550 ret_overflow |= overflow;
551
552 (ret, ret_overflow)
553 }
554
555 #[must_use = "this returns the result of the operation, without modifying the original"]
558 fn wrapping_add(self, rhs: Self) -> Self {
559 let (ret, _overflow) = self.overflowing_add(rhs);
560 ret
561 }
562
563 #[must_use = "this returns the result of the operation, without modifying the original"]
566 fn wrapping_sub(self, rhs: Self) -> Self {
567 let (ret, _overflow) = self.overflowing_sub(rhs);
568 ret
569 }
570
571 #[must_use = "this returns the result of the operation, without modifying the original"]
574 #[cfg(test)]
575 fn wrapping_mul(self, rhs: Self) -> Self {
576 let (ret, _overflow) = self.overflowing_mul(rhs);
577 ret
578 }
579
580 #[must_use = "this returns the result of the increment, without modifying the original"]
582 #[cfg_attr(all(test, mutate), mutate)]
583 fn wrapping_inc(&self) -> U256 {
584 let mut ret = U256::ZERO;
585
586 ret.1 = self.1.wrapping_add(1);
587 if ret.1 == 0 {
588 ret.0 = self.0.wrapping_add(1);
589 } else {
590 ret.0 = self.0;
591 }
592 ret
593 }
594
595 #[must_use = "this returns the result of the operation, without modifying the original"]
602 #[cfg_attr(all(test, mutate), mutate)]
603 fn wrapping_shl(self, rhs: u32) -> Self {
604 let shift = rhs & 0x000000ff;
605
606 let mut ret = U256::ZERO;
607 let word_shift = shift >= 128;
608 let bit_shift = shift % 128;
609
610 if word_shift {
611 ret.0 = self.1 << bit_shift
612 } else {
613 ret.0 = self.0 << bit_shift;
614 if bit_shift > 0 {
615 ret.0 += self.1.wrapping_shr(128 - bit_shift);
616 }
617 ret.1 = self.1 << bit_shift;
618 }
619 ret
620 }
621
622 #[must_use = "this returns the result of the operation, without modifying the original"]
629 #[cfg_attr(all(test, mutate), mutate)]
630 fn wrapping_shr(self, rhs: u32) -> Self {
631 let shift = rhs & 0x000000ff;
632
633 let mut ret = U256::ZERO;
634 let word_shift = shift >= 128;
635 let bit_shift = shift % 128;
636
637 if word_shift {
638 ret.1 = self.0 >> bit_shift
639 } else {
640 ret.0 = self.0 >> bit_shift;
641 ret.1 = self.1 >> bit_shift;
642 if bit_shift > 0 {
643 ret.1 += self.0.wrapping_shl(128 - bit_shift);
644 }
645 }
646 ret
647 }
648
649 fn fmt_decimal(&self, f: &mut fmt::Formatter) -> fmt::Result {
651 const DIGITS: usize = 78; const TEN: U256 = U256(0, 10);
653
654 let mut buf = [0_u8; DIGITS];
655 let mut i = DIGITS - 1; let mut cur = *self;
657
658 loop {
659 let digit = (cur % TEN).low_u128() as u8; buf[i] = digit + b'0';
661 cur = cur / TEN;
662 if cur.is_zero() {
663 break;
664 }
665 i -= 1;
666 }
667 let s = core::str::from_utf8(&buf[i..]).expect("digits 0-9 are valid UTF8");
668 f.pad_integral(true, "", s)
669 }
670
671 #[inline]
673 fn to_f64(self) -> f64 {
674 let leading_zeroes = 256 - self.bits();
677 let left_aligned = self.wrapping_shl(leading_zeroes);
679 let middle_aligned = left_aligned >> 75;
682 let mantissa = middle_aligned.0;
684 let dropped_bits = middle_aligned.1 | (left_aligned.1 & 0x7FF_FFFF_FFFF_FFFF_FFFF);
688 let mantissa =
696 (mantissa + ((dropped_bits - (dropped_bits >> 127 & !mantissa)) >> 127)) as u64;
697 let exponent = if self == Self::ZERO { 0 } else { 1277 - leading_zeroes as u64 };
702 f64::from_bits((exponent << 52) + mantissa)
705 }
706}
707
708const TARGET_MAX_F64: f64 = 2.695953529101131e67;
711
712impl<T: Into<u128>> From<T> for U256 {
713 fn from(x: T) -> Self { U256(0, x.into()) }
714}
715
716#[derive(Debug, Clone, PartialEq, Eq)]
718#[non_exhaustive]
719pub struct TryFromError(i128);
720
721impl fmt::Display for TryFromError {
722 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
723 write!(f, "attempt to create unsigned integer type from negative number: {}", self.0)
724 }
725}
726
727#[cfg(feature = "std")]
728impl std::error::Error for TryFromError {
729 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None }
730}
731
732impl Add for U256 {
733 type Output = Self;
734 fn add(self, rhs: Self) -> Self {
735 let (res, overflow) = self.overflowing_add(rhs);
736 debug_assert!(!overflow, "Addition of U256 values overflowed");
737 res
738 }
739}
740
741impl Sub for U256 {
742 type Output = Self;
743 fn sub(self, rhs: Self) -> Self {
744 let (res, overflow) = self.overflowing_sub(rhs);
745 debug_assert!(!overflow, "Subtraction of U256 values overflowed");
746 res
747 }
748}
749
750impl Mul for U256 {
751 type Output = Self;
752 fn mul(self, rhs: Self) -> Self {
753 let (res, overflow) = self.overflowing_mul(rhs);
754 debug_assert!(!overflow, "Multiplication of U256 values overflowed");
755 res
756 }
757}
758
759impl Div for U256 {
760 type Output = Self;
761 fn div(self, rhs: Self) -> Self { self.div_rem(rhs).0 }
762}
763
764impl Rem for U256 {
765 type Output = Self;
766 fn rem(self, rhs: Self) -> Self { self.div_rem(rhs).1 }
767}
768
769impl Not for U256 {
770 type Output = Self;
771
772 fn not(self) -> Self { U256(!self.0, !self.1) }
773}
774
775impl Shl<u32> for U256 {
776 type Output = Self;
777 fn shl(self, shift: u32) -> U256 { self.wrapping_shl(shift) }
778}
779
780impl Shr<u32> for U256 {
781 type Output = Self;
782 fn shr(self, shift: u32) -> U256 { self.wrapping_shr(shift) }
783}
784
785impl fmt::Display for U256 {
786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 if self.is_zero() {
788 f.pad_integral(true, "", "0")
789 } else {
790 self.fmt_decimal(f)
791 }
792 }
793}
794
795impl fmt::Debug for U256 {
796 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:#x}", self) }
797}
798
799macro_rules! impl_hex {
800 ($hex:ident, $case:expr) => {
801 impl $hex for U256 {
802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
803 hex::fmt_hex_exact!(f, 32, &self.to_be_bytes(), $case)
804 }
805 }
806 };
807}
808impl_hex!(LowerHex, hex::Case::Lower);
809impl_hex!(UpperHex, hex::Case::Upper);
810
811#[cfg(feature = "serde")]
812impl crate::serde::Serialize for U256 {
813 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
814 where
815 S: crate::serde::Serializer,
816 {
817 struct DisplayHex(U256);
818
819 impl fmt::Display for DisplayHex {
820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:x}", self.0) }
821 }
822
823 if serializer.is_human_readable() {
824 serializer.collect_str(&DisplayHex(*self))
826 } else {
827 let bytes = self.to_be_bytes();
828 serializer.serialize_bytes(&bytes)
829 }
830 }
831}
832
833#[cfg(feature = "serde")]
834impl<'de> crate::serde::Deserialize<'de> for U256 {
835 fn deserialize<D: crate::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
836 use core::convert::TryInto;
837
838 use hex::FromHex;
839
840 use crate::serde::de;
841
842 if d.is_human_readable() {
843 struct HexVisitor;
844
845 impl<'de> de::Visitor<'de> for HexVisitor {
846 type Value = U256;
847
848 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
849 f.write_str("a 32 byte ASCII hex string")
850 }
851
852 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
853 where
854 E: de::Error,
855 {
856 if s.len() != 64 {
857 return Err(de::Error::invalid_length(s.len(), &self));
858 }
859
860 let b = <[u8; 32]>::from_hex(s)
861 .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
862
863 Ok(U256::from_be_bytes(b))
864 }
865
866 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
867 where
868 E: de::Error,
869 {
870 if let Ok(hex) = core::str::from_utf8(v) {
871 let b = <[u8; 32]>::from_hex(hex).map_err(|_| {
872 de::Error::invalid_value(de::Unexpected::Str(hex), &self)
873 })?;
874
875 Ok(U256::from_be_bytes(b))
876 } else {
877 Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
878 }
879 }
880 }
881 d.deserialize_str(HexVisitor)
882 } else {
883 struct BytesVisitor;
884
885 impl<'de> serde::de::Visitor<'de> for BytesVisitor {
886 type Value = U256;
887
888 fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
889 f.write_str("a sequence of bytes")
890 }
891
892 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
893 where
894 E: serde::de::Error,
895 {
896 let b = v.try_into().map_err(|_| de::Error::invalid_length(v.len(), &self))?;
897 Ok(U256::from_be_bytes(b))
898 }
899 }
900
901 d.deserialize_bytes(BytesVisitor)
902 }
903 }
904}
905
906fn split_in_half(a: [u8; 32]) -> ([u8; 16], [u8; 16]) {
908 let mut high = [0_u8; 16];
909 let mut low = [0_u8; 16];
910
911 high.copy_from_slice(&a[..16]);
912 low.copy_from_slice(&a[16..]);
913
914 (high, low)
915}
916
917#[cfg(kani)]
918impl kani::Arbitrary for U256 {
919 fn any() -> Self {
920 let high: u128 = kani::any();
921 let low: u128 = kani::any();
922 Self(high, low)
923 }
924}
925
926#[cfg(test)]
927mod tests {
928 use super::*;
929
930 impl<T: Into<u128>> From<T> for Target {
931 fn from(x: T) -> Self { Self(U256::from(x)) }
932 }
933
934 impl<T: Into<u128>> From<T> for Work {
935 fn from(x: T) -> Self { Self(U256::from(x)) }
936 }
937
938 impl U256 {
939 fn bit_at(&self, index: usize) -> bool {
940 if index > 255 {
941 panic!("index out of bounds");
942 }
943
944 let word = if index < 128 { self.1 } else { self.0 };
945 (word & (1 << (index % 128))) != 0
946 }
947 }
948
949 impl U256 {
950 fn from_array(a: [u64; 4]) -> Self {
952 let mut ret = U256::ZERO;
953 ret.0 = (a[0] as u128) << 64 ^ (a[1] as u128);
954 ret.1 = (a[2] as u128) << 64 ^ (a[3] as u128);
955 ret
956 }
957 }
958
959 #[test]
960 fn u256_num_bits() {
961 assert_eq!(U256::from(255_u64).bits(), 8);
962 assert_eq!(U256::from(256_u64).bits(), 9);
963 assert_eq!(U256::from(300_u64).bits(), 9);
964 assert_eq!(U256::from(60000_u64).bits(), 16);
965 assert_eq!(U256::from(70000_u64).bits(), 17);
966
967 let u = U256::from(u128::MAX) << 1;
968 assert_eq!(u.bits(), 129);
969
970 let mut shl = U256::from(70000_u64);
972 shl = shl << 100;
973 assert_eq!(shl.bits(), 117);
974 shl = shl << 100;
975 assert_eq!(shl.bits(), 217);
976 shl = shl << 100;
977 assert_eq!(shl.bits(), 0);
978 }
979
980 #[test]
981 fn u256_bit_at() {
982 assert!(!U256::from(10_u64).bit_at(0));
983 assert!(U256::from(10_u64).bit_at(1));
984 assert!(!U256::from(10_u64).bit_at(2));
985 assert!(U256::from(10_u64).bit_at(3));
986 assert!(!U256::from(10_u64).bit_at(4));
987
988 let u = U256(0xa000_0000_0000_0000_0000_0000_0000_0000, 0);
989 assert!(u.bit_at(255));
990 assert!(!u.bit_at(254));
991 assert!(u.bit_at(253));
992 assert!(!u.bit_at(252));
993 }
994
995 #[test]
996 fn u256_lower_hex() {
997 assert_eq!(
998 format!("{:x}", U256::from(0xDEADBEEF_u64)),
999 "00000000000000000000000000000000000000000000000000000000deadbeef",
1000 );
1001 assert_eq!(
1002 format!("{:#x}", U256::from(0xDEADBEEF_u64)),
1003 "0x00000000000000000000000000000000000000000000000000000000deadbeef",
1004 );
1005 assert_eq!(
1006 format!("{:x}", U256::MAX),
1007 "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1008 );
1009 assert_eq!(
1010 format!("{:#x}", U256::MAX),
1011 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1012 );
1013 }
1014
1015 #[test]
1016 fn u256_upper_hex() {
1017 assert_eq!(
1018 format!("{:X}", U256::from(0xDEADBEEF_u64)),
1019 "00000000000000000000000000000000000000000000000000000000DEADBEEF",
1020 );
1021 assert_eq!(
1022 format!("{:#X}", U256::from(0xDEADBEEF_u64)),
1023 "0x00000000000000000000000000000000000000000000000000000000DEADBEEF",
1024 );
1025 assert_eq!(
1026 format!("{:X}", U256::MAX),
1027 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1028 );
1029 assert_eq!(
1030 format!("{:#X}", U256::MAX),
1031 "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1032 );
1033 }
1034
1035 #[test]
1036 fn u256_display() {
1037 assert_eq!(format!("{}", U256::from(100_u32)), "100",);
1038 assert_eq!(format!("{}", U256::ZERO), "0",);
1039 assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
1040 assert_eq!(
1041 format!("{}", U256::MAX),
1042 "115792089237316195423570985008687907853269984665640564039457584007913129639935",
1043 );
1044 }
1045
1046 macro_rules! check_format {
1047 ($($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
1048 $(
1049 #[test]
1050 fn $test_name() {
1051 assert_eq!(format!($format_string, U256::from($val)), $expected);
1052 }
1053 )*
1054 }
1055 }
1056 check_format! {
1057 check_fmt_0, 0_u32, "{}", "0";
1058 check_fmt_1, 0_u32, "{:2}", " 0";
1059 check_fmt_2, 0_u32, "{:02}", "00";
1060
1061 check_fmt_3, 1_u32, "{}", "1";
1062 check_fmt_4, 1_u32, "{:2}", " 1";
1063 check_fmt_5, 1_u32, "{:02}", "01";
1064
1065 check_fmt_10, 10_u32, "{}", "10";
1066 check_fmt_11, 10_u32, "{:2}", "10";
1067 check_fmt_12, 10_u32, "{:02}", "10";
1068 check_fmt_13, 10_u32, "{:3}", " 10";
1069 check_fmt_14, 10_u32, "{:03}", "010";
1070
1071 check_fmt_20, 1_u32, "{:<2}", "1 ";
1072 check_fmt_21, 1_u32, "{:<02}", "01";
1073 check_fmt_22, 1_u32, "{:>2}", " 1"; check_fmt_23, 1_u32, "{:>02}", "01";
1075 check_fmt_24, 1_u32, "{:^3}", " 1 ";
1076 check_fmt_25, 1_u32, "{:^03}", "001";
1077 check_fmt_30, 0_u32, "{:.1}", "0";
1079 check_fmt_31, 0_u32, "{:4.1}", " 0";
1080 check_fmt_32, 0_u32, "{:04.1}", "0000";
1081 }
1082
1083 #[test]
1084 fn u256_comp() {
1085 let small = U256::from_array([0, 0, 0, 10]);
1086 let big = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]);
1087 let bigger = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x9C8C_3EE7_0C64_4118]);
1088 let biggest = U256::from_array([1, 0, 0x0209_E737_8231_E632, 0x5C8C_3EE7_0C64_4118]);
1089
1090 assert!(small < big);
1091 assert!(big < bigger);
1092 assert!(bigger < biggest);
1093 assert!(bigger <= biggest);
1094 assert!(biggest <= biggest);
1095 assert!(bigger >= big);
1096 assert!(bigger >= small);
1097 assert!(small <= small);
1098 }
1099
1100 const WANT: U256 =
1101 U256(0x1bad_cafe_dead_beef_deaf_babe_2bed_feed, 0xbaad_f00d_defa_ceda_11fe_d2ba_d1c0_ffe0);
1102
1103 #[rustfmt::skip]
1104 const BE_BYTES: [u8; 32] = [
1105 0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed,
1106 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba, 0xd1, 0xc0, 0xff, 0xe0,
1107 ];
1108
1109 #[rustfmt::skip]
1110 const LE_BYTES: [u8; 32] = [
1111 0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0, 0xad, 0xba,
1112 0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca, 0xad, 0x1b,
1113 ];
1114
1115 #[test]
1117 fn sanity_be_bytes() {
1118 let mut out = [0_u8; 32];
1119 out[..16].copy_from_slice(&WANT.0.to_be_bytes());
1120 out[16..].copy_from_slice(&WANT.1.to_be_bytes());
1121 assert_eq!(out, BE_BYTES);
1122 }
1123
1124 #[test]
1126 fn sanity_le_bytes() {
1127 let mut out = [0_u8; 32];
1128 out[..16].copy_from_slice(&WANT.1.to_le_bytes());
1129 out[16..].copy_from_slice(&WANT.0.to_le_bytes());
1130 assert_eq!(out, LE_BYTES);
1131 }
1132
1133 #[test]
1134 fn u256_to_be_bytes() {
1135 assert_eq!(WANT.to_be_bytes(), BE_BYTES);
1136 }
1137
1138 #[test]
1139 fn u256_from_be_bytes() {
1140 assert_eq!(U256::from_be_bytes(BE_BYTES), WANT);
1141 }
1142
1143 #[test]
1144 fn u256_to_le_bytes() {
1145 assert_eq!(WANT.to_le_bytes(), LE_BYTES);
1146 }
1147
1148 #[test]
1149 fn u256_from_le_bytes() {
1150 assert_eq!(U256::from_le_bytes(LE_BYTES), WANT);
1151 }
1152
1153 #[test]
1154 fn u256_from_u8() {
1155 let u = U256::from(0xbe_u8);
1156 assert_eq!(u, U256(0, 0xbe));
1157 }
1158
1159 #[test]
1160 fn u256_from_u16() {
1161 let u = U256::from(0xbeef_u16);
1162 assert_eq!(u, U256(0, 0xbeef));
1163 }
1164
1165 #[test]
1166 fn u256_from_u32() {
1167 let u = U256::from(0xdeadbeef_u32);
1168 assert_eq!(u, U256(0, 0xdeadbeef));
1169 }
1170
1171 #[test]
1172 fn u256_from_u64() {
1173 let u = U256::from(0xdead_beef_cafe_babe_u64);
1174 assert_eq!(u, U256(0, 0xdead_beef_cafe_babe));
1175 }
1176
1177 #[test]
1178 fn u256_from_u128() {
1179 let u = U256::from(0xdead_beef_cafe_babe_0123_4567_89ab_cdefu128);
1180 assert_eq!(u, U256(0, 0xdead_beef_cafe_babe_0123_4567_89ab_cdef));
1181 }
1182
1183 macro_rules! test_from_unsigned_integer_type {
1184 ($($test_name:ident, $ty:ident);* $(;)?) => {
1185 $(
1186 #[test]
1187 fn $test_name() {
1188 let want = U256(0, 0xAB);
1190
1191 let x = 0xAB as $ty;
1192 let got = U256::from(x);
1193
1194 assert_eq!(got, want);
1195 }
1196 )*
1197 }
1198 }
1199 test_from_unsigned_integer_type! {
1200 from_unsigned_integer_type_u8, u8;
1201 from_unsigned_integer_type_u16, u16;
1202 from_unsigned_integer_type_u32, u32;
1203 from_unsigned_integer_type_u64, u64;
1204 from_unsigned_integer_type_u128, u128;
1205 }
1206
1207 #[test]
1208 fn u256_from_be_array_u64() {
1209 let array = [
1210 0x1bad_cafe_dead_beef,
1211 0xdeaf_babe_2bed_feed,
1212 0xbaad_f00d_defa_ceda,
1213 0x11fe_d2ba_d1c0_ffe0,
1214 ];
1215
1216 let uint = U256::from_array(array);
1217 assert_eq!(uint, WANT);
1218 }
1219
1220 #[test]
1221 fn u256_shift_left() {
1222 let u = U256::from(1_u32);
1223 assert_eq!(u << 0, u);
1224 assert_eq!(u << 1, U256::from(2_u64));
1225 assert_eq!(u << 63, U256::from(0x8000_0000_0000_0000_u64));
1226 assert_eq!(u << 64, U256::from_array([0, 0, 0x0000_0000_0000_0001, 0]));
1227 assert_eq!(u << 127, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1228 assert_eq!(u << 128, U256(1, 0));
1229
1230 let x = U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000);
1231 assert_eq!(x << 1, U256(1, 0));
1232 }
1233
1234 #[test]
1235 fn u256_shift_right() {
1236 let u = U256(1, 0);
1237 assert_eq!(u >> 0, u);
1238 assert_eq!(u >> 1, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1239 assert_eq!(u >> 127, U256(0, 2));
1240 assert_eq!(u >> 128, U256(0, 1));
1241 }
1242
1243 #[test]
1244 fn u256_arithmetic() {
1245 let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1246 let copy = init;
1247
1248 let add = init.wrapping_add(copy);
1249 assert_eq!(add, U256::from_array([0, 0, 1, 0xBD5B_7DDF_BD5B_7DDE]));
1250 let shl = add << 88;
1252 assert_eq!(shl, U256::from_array([0, 0x01BD_5B7D, 0xDFBD_5B7D_DE00_0000, 0]));
1253 let shr = shl >> 40;
1254 assert_eq!(shr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0000]));
1255 let mut incr = shr;
1257 incr = incr.wrapping_inc();
1258 assert_eq!(incr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0001]));
1259 let sub = incr.wrapping_sub(init);
1261 assert_eq!(sub, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1262 let (mult, _) = sub.mul_u64(300);
1264 assert_eq!(mult, U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]));
1265 assert_eq!(U256::from(105_u32) / U256::from(5_u32), U256::from(21_u32));
1267 let div = mult / U256::from(300_u32);
1268 assert_eq!(div, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1269
1270 assert_eq!(U256::from(105_u32) % U256::from(5_u32), U256::ZERO);
1271 assert_eq!(U256::from(35498456_u32) % U256::from(3435_u32), U256::from(1166_u32));
1272 let rem_src = mult.wrapping_mul(U256::from(39842_u32)).wrapping_add(U256::from(9054_u32));
1273 assert_eq!(rem_src % U256::from(39842_u32), U256::from(9054_u32));
1274 }
1275
1276 #[test]
1277 fn u256_bit_inversion() {
1278 let v = U256(1, 0);
1279 let want = U256(
1280 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe,
1281 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff,
1282 );
1283 assert_eq!(!v, want);
1284
1285 let v = U256(0x0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c, 0xeeee_eeee_eeee_eeee);
1286 let want = U256(
1287 0xf3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3,
1288 0xffff_ffff_ffff_ffff_1111_1111_1111_1111,
1289 );
1290 assert_eq!(!v, want);
1291 }
1292
1293 #[test]
1294 fn u256_mul_u64_by_one() {
1295 let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1296 assert_eq!(v, v.mul_u64(1_u64).0);
1297 }
1298
1299 #[test]
1300 fn u256_mul_u64_by_zero() {
1301 let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1302 assert_eq!(U256::ZERO, v.mul_u64(0_u64).0);
1303 }
1304
1305 #[test]
1306 fn u256_mul_u64() {
1307 let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1308
1309 let u96_res = u64_val.mul_u64(0xFFFF_FFFF).0;
1310 let u128_res = u96_res.mul_u64(0xFFFF_FFFF).0;
1311 let u160_res = u128_res.mul_u64(0xFFFF_FFFF).0;
1312 let u192_res = u160_res.mul_u64(0xFFFF_FFFF).0;
1313 let u224_res = u192_res.mul_u64(0xFFFF_FFFF).0;
1314 let u256_res = u224_res.mul_u64(0xFFFF_FFFF).0;
1315
1316 assert_eq!(u96_res, U256::from_array([0, 0, 0xDEAD_BEEE, 0xFFFF_FFFF_2152_4111]));
1317 assert_eq!(
1318 u128_res,
1319 U256::from_array([0, 0, 0xDEAD_BEEE_2152_4110, 0x2152_4111_DEAD_BEEF])
1320 );
1321 assert_eq!(
1322 u160_res,
1323 U256::from_array([0, 0xDEAD_BEED, 0x42A4_8222_0000_0001, 0xBD5B_7DDD_2152_4111])
1324 );
1325 assert_eq!(
1326 u192_res,
1327 U256::from_array([
1328 0,
1329 0xDEAD_BEEC_63F6_C334,
1330 0xBD5B_7DDF_BD5B_7DDB,
1331 0x63F6_C333_DEAD_BEEF
1332 ])
1333 );
1334 assert_eq!(
1335 u224_res,
1336 U256::from_array([
1337 0xDEAD_BEEB,
1338 0x8549_0448_5964_BAAA,
1339 0xFFFF_FFFB_A69B_4558,
1340 0x7AB6_FBBB_2152_4111
1341 ])
1342 );
1343 assert_eq!(
1344 u256_res,
1345 U256(
1346 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1347 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1348 )
1349 );
1350 }
1351
1352 #[test]
1353 fn u256_addition() {
1354 let x = U256::from(u128::MAX);
1355 let (add, overflow) = x.overflowing_add(U256::ONE);
1356 assert!(!overflow);
1357 assert_eq!(add, U256(1, 0));
1358
1359 let (add, _) = add.overflowing_add(U256::ONE);
1360 assert_eq!(add, U256(1, 1));
1361 }
1362
1363 #[test]
1364 fn u256_subtraction() {
1365 let (sub, overflow) = U256::ONE.overflowing_sub(U256::ONE);
1366 assert!(!overflow);
1367 assert_eq!(sub, U256::ZERO);
1368
1369 let x = U256(1, 0);
1370 let (sub, overflow) = x.overflowing_sub(U256::ONE);
1371 assert!(!overflow);
1372 assert_eq!(sub, U256::from(u128::MAX));
1373 }
1374
1375 #[test]
1376 fn u256_multiplication() {
1377 let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1378
1379 let u128_res = u64_val.wrapping_mul(u64_val);
1380
1381 assert_eq!(u128_res, U256(0, 0xC1B1_CD13_A4D1_3D46_048D_1354_216D_A321));
1382
1383 let u256_res = u128_res.wrapping_mul(u128_res);
1384
1385 assert_eq!(
1386 u256_res,
1387 U256(
1388 0x928D_92B4_D7F5_DF33_4AFC_FF6F_0375_C608,
1389 0xF5CF_7F36_18C2_C886_F4E1_66AA_D40D_0A41,
1390 )
1391 );
1392 }
1393
1394 #[test]
1395 fn u256_multiplication_bits_in_each_word() {
1396 let u = 1_u128 << 64 | 1_u128;
1398 let x = U256(u, u);
1399
1400 let u = 2_u128 << 64 | 2_u128;
1402 let y = U256(u, u);
1403
1404 let (got, overflow) = x.overflowing_mul(y);
1405
1406 let want = U256(
1407 0x0000_0000_0000_0008_0000_0000_0000_0008,
1408 0x0000_0000_0000_0006_0000_0000_0000_0004,
1409 );
1410 assert!(!overflow);
1411 assert_eq!(got, want)
1412 }
1413
1414 #[test]
1415 fn u256_increment() {
1416 let mut val = U256(
1417 0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1418 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
1419 );
1420 val = val.wrapping_inc();
1421 assert_eq!(
1422 val,
1423 U256(
1424 0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1425 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1426 )
1427 );
1428 val = val.wrapping_inc();
1429 assert_eq!(
1430 val,
1431 U256(
1432 0xF000_0000_0000_0000_0000_0000_0000_0000,
1433 0x0000_0000_0000_0000_0000_0000_0000_0000,
1434 )
1435 );
1436
1437 assert_eq!(U256::MAX.wrapping_inc(), U256::ZERO);
1438 }
1439
1440 #[test]
1441 fn u256_extreme_bitshift() {
1442 let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1445
1446 assert_eq!(init << 64, U256(0, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000));
1447 let add = (init << 64).wrapping_add(init);
1448 assert_eq!(add, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1449 assert_eq!(add >> 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1450 assert_eq!(add << 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1451 assert_eq!(add >> 64, U256(0, 0x0000_0000_0000_0000_DEAD_BEEF_DEAD_BEEF));
1452 assert_eq!(
1453 add << 64,
1454 U256(0xDEAD_BEEF_DEAD_BEEF, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000)
1455 );
1456 }
1457
1458 #[cfg(feature = "serde")]
1459 #[test]
1460 fn u256_serde() {
1461 let check = |uint, hex| {
1462 let json = format!("\"{}\"", hex);
1463 assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
1464 assert_eq!(::serde_json::from_str::<U256>(&json).unwrap(), uint);
1465
1466 let bin_encoded = bincode::serialize(&uint).unwrap();
1467 let bin_decoded: U256 = bincode::deserialize(&bin_encoded).unwrap();
1468 assert_eq!(bin_decoded, uint);
1469 };
1470
1471 check(U256::ZERO, "0000000000000000000000000000000000000000000000000000000000000000");
1472 check(
1473 U256::from(0xDEADBEEF_u32),
1474 "00000000000000000000000000000000000000000000000000000000deadbeef",
1475 );
1476 check(
1477 U256::from_array([0xdd44, 0xcc33, 0xbb22, 0xaa11]),
1478 "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
1479 );
1480 check(U256::MAX, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1481 check(
1482 U256(
1483 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1484 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1485 ),
1486 "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
1487 );
1488
1489 assert!(::serde_json::from_str::<U256>(
1490 "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
1491 )
1492 .is_err()); assert!(::serde_json::from_str::<U256>(
1494 "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1495 )
1496 .is_err()); assert!(::serde_json::from_str::<U256>(
1498 "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1499 )
1500 .is_err()); }
1502
1503 #[test]
1504 fn u256_is_max_correct_negative() {
1505 let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::MAX)];
1506 for t in tc {
1507 assert!(!t.is_max())
1508 }
1509 }
1510
1511 #[test]
1512 fn u256_is_max_correct_positive() {
1513 assert!(U256::MAX.is_max());
1514
1515 let u = u128::MAX;
1516 assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
1517 }
1518
1519 #[test]
1520 fn compact_target_from_hex_str_happy_path() {
1521 let actual = CompactTarget::from_hex_str("0x01003456").unwrap();
1522 let expected = CompactTarget(0x01003456);
1523 assert_eq!(actual, expected);
1524 }
1525
1526 #[test]
1527 fn compact_target_from_hex_str_no_prefix_happy_path() {
1528 let actual = CompactTarget::from_hex_str_no_prefix("01003456").unwrap();
1529 let expected = CompactTarget(0x01003456);
1530 assert_eq!(actual, expected);
1531 }
1532
1533 #[test]
1534 fn compact_target_from_hex_invalid_hex_should_err() {
1535 let hex = "0xzbf9";
1536 let result = CompactTarget::from_hex_str(hex);
1537 assert!(result.is_err());
1538 }
1539
1540 #[test]
1541 fn target_from_compact() {
1542 let tests = vec![
1544 (0x0100_3456_u32, 0x00_u64), (0x0112_3456_u32, 0x12_u64),
1546 (0x0200_8000_u32, 0x80_u64),
1547 (0x0500_9234_u32, 0x9234_0000_u64),
1548 (0x0492_3456_u32, 0x00_u64), (0x0412_3456_u32, 0x1234_5600_u64), ];
1551
1552 for (n_bits, target) in tests {
1553 let want = Target::from(target);
1554 let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
1555 assert_eq!(got, want);
1556 }
1557 }
1558
1559 #[test]
1560 fn target_is_met_by_for_target_equals_hash() {
1561 use std::str::FromStr;
1562
1563 use hashes::Hash;
1564
1565 let hash =
1566 BlockHash::from_str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")
1567 .expect("failed to parse block hash");
1568 let target = Target(U256::from_le_bytes(hash.to_byte_array()));
1569 assert!(target.is_met_by(hash));
1570 }
1571
1572 #[test]
1573 fn max_target_from_compact() {
1574 let bits = 0x1d00ffff_u32;
1576 let want = Target::MAX;
1577 let got = Target::from_compact(CompactTarget::from_consensus(bits));
1578 assert_eq!(got, want)
1579 }
1580
1581 #[test]
1582 fn target_difficulty_float() {
1583 assert_eq!(Target::MAX.difficulty_float(), 1.0_f64);
1584 assert_eq!(
1585 Target::from_compact(CompactTarget::from_consensus(0x1c00ffff_u32)).difficulty_float(),
1586 256.0_f64
1587 );
1588 assert_eq!(
1589 Target::from_compact(CompactTarget::from_consensus(0x1b00ffff_u32)).difficulty_float(),
1590 65536.0_f64
1591 );
1592 assert_eq!(
1593 Target::from_compact(CompactTarget::from_consensus(0x1a00f3a2_u32)).difficulty_float(),
1594 17628585.065897066_f64
1595 );
1596 }
1597
1598 #[test]
1599 fn roundtrip_compact_target() {
1600 let consensus = 0x1d00_ffff;
1601 let compact = CompactTarget::from_consensus(consensus);
1602 let t = Target::from_compact(CompactTarget::from_consensus(consensus));
1603 assert_eq!(t, Target::from(compact)); let back = t.to_compact_lossy();
1606 assert_eq!(back, compact); assert_eq!(back.to_consensus(), consensus);
1609 }
1610
1611 #[test]
1612 fn roundtrip_target_work() {
1613 let target = Target::from(0xdeadbeef_u32);
1614 let work = target.to_work();
1615 let back = work.to_target();
1616 assert_eq!(back, target)
1617 }
1618
1619 #[cfg(feature = "std")]
1620 #[test]
1621 fn work_log2() {
1622 let tests: Vec<(u128, f64)> = vec![
1624 (0x200020002, 33.000022), (0xa97d67041c5e51596ee7, 79.405055), (0x1dc45d79394baa8ab18b20, 84.895644), (0x8c85acb73287e335d525b98, 91.134654), (0x2ef447e01d1642c40a184ada, 93.553183), ];
1631
1632 for (chainwork, core_log2) in tests {
1633 let log2 = (Work::from(chainwork).log2() * 1e6).round() / 1e6;
1635 assert_eq!(log2, core_log2)
1636 }
1637
1638 assert_eq!(Work(U256::ONE).log2(), 0.0);
1639 assert_eq!(Work(U256::MAX).log2(), 256.0);
1640 }
1641
1642 #[test]
1643 fn u256_zero_min_max_inverse() {
1644 assert_eq!(U256::MAX.inverse(), U256::ONE);
1645 assert_eq!(U256::ONE.inverse(), U256::MAX);
1646 assert_eq!(U256::ZERO.inverse(), U256::MAX);
1647 }
1648
1649 #[test]
1650 fn u256_max_min_inverse_roundtrip() {
1651 let max = U256::MAX;
1652
1653 for min in [U256::ZERO, U256::ONE].iter() {
1654 assert_eq!(Target(max).to_work(), Work(U256::ONE));
1656 assert_eq!(Target(*min).to_work(), Work(max));
1657
1658 assert_eq!(Work(max).to_target(), Target(U256::ONE));
1659 assert_eq!(Work(*min).to_target(), Target(max));
1660 }
1661 }
1662
1663 #[test]
1664 fn u256_wrapping_add_wraps_at_boundry() {
1665 assert_eq!(U256::MAX.wrapping_add(U256::ONE), U256::ZERO);
1666 assert_eq!(U256::MAX.wrapping_add(U256::from(2_u8)), U256::ONE);
1667 }
1668
1669 #[test]
1670 fn u256_wrapping_sub_wraps_at_boundry() {
1671 assert_eq!(U256::ZERO.wrapping_sub(U256::ONE), U256::MAX);
1672 assert_eq!(U256::ONE.wrapping_sub(U256::from(2_u8)), U256::MAX);
1673 }
1674
1675 #[test]
1676 fn mul_u64_overflows() {
1677 let (_, overflow) = U256::MAX.mul_u64(2);
1678 assert!(overflow, "max * 2 should overflow");
1679 }
1680
1681 #[test]
1682 #[should_panic]
1683 fn u256_overflowing_addition_panics() { let _ = U256::MAX + U256::ONE; }
1684
1685 #[test]
1686 #[should_panic]
1687 fn u256_overflowing_subtraction_panics() { let _ = U256::ZERO - U256::ONE; }
1688
1689 #[test]
1690 #[should_panic]
1691 fn u256_multiplication_by_max_panics() { let _ = U256::MAX * U256::MAX; }
1692
1693 #[test]
1694 #[should_panic]
1695 fn work_overflowing_addition_panics() { let _ = Work(U256::MAX) + Work(U256::ONE); }
1696
1697 #[test]
1698 #[should_panic]
1699 fn work_overflowing_subtraction_panics() { let _ = Work(U256::ZERO) - Work(U256::ONE); }
1700
1701 #[test]
1702 fn u256_to_f64() {
1703 assert_eq!(Target::MAX.0.to_f64(), TARGET_MAX_F64);
1705 assert_eq!(U256::ZERO.to_f64(), 0.0_f64);
1706 assert_eq!(U256::ONE.to_f64(), 1.0_f64);
1707 assert_eq!(U256::MAX.to_f64(), 1.157920892373162e77_f64);
1708 assert_eq!((U256::MAX >> 1).to_f64(), 5.78960446186581e76_f64);
1709 assert_eq!((U256::MAX >> 128).to_f64(), 3.402823669209385e38_f64);
1710 assert_eq!((U256::MAX >> (256 - 54)).to_f64(), 1.8014398509481984e16_f64);
1711 assert_eq!((U256::MAX >> (256 - 53)).to_f64(), 9007199254740991.0_f64);
1713 assert_eq!((U256::MAX >> (256 - 32)).to_f64(), 4294967295.0_f64);
1714 assert_eq!((U256::MAX >> (256 - 16)).to_f64(), 65535.0_f64);
1715 assert_eq!((U256::MAX >> (256 - 8)).to_f64(), 255.0_f64);
1716 }
1717}
1718
1719#[cfg(kani)]
1720mod verification {
1721 use super::*;
1722
1723 #[kani::unwind(5)] #[kani::proof]
1726 fn check_mul_u64() {
1727 let x: U256 = kani::any();
1728 let y: u64 = kani::any();
1729
1730 let _ = x.mul_u64(y);
1731 }
1732}