1use 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::error::{
23 ContainsPrefixError, MissingPrefixError, ParseIntError, PrefixedHexError, UnprefixedHexError,
24};
25
26macro_rules! do_impl {
28 ($ty:ident) => {
29 impl $ty {
30 #[doc = "Creates `"]
31 #[doc = stringify!($ty)]
32 #[doc = "` from a prefixed hex string."]
33 pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
34 Ok($ty(U256::from_hex(s)?))
35 }
36
37 #[doc = "Creates `"]
38 #[doc = stringify!($ty)]
39 #[doc = "` from an unprefixed hex string."]
40 pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
41 Ok($ty(U256::from_unprefixed_hex(s)?))
42 }
43
44 #[doc = "Creates `"]
45 #[doc = stringify!($ty)]
46 #[doc = "` from a big-endian byte array."]
47 #[inline]
48 pub fn from_be_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_be_bytes(bytes)) }
49
50 #[doc = "Creates `"]
51 #[doc = stringify!($ty)]
52 #[doc = "` from a little-endian byte array."]
53 #[inline]
54 pub fn from_le_bytes(bytes: [u8; 32]) -> $ty { $ty(U256::from_le_bytes(bytes)) }
55
56 #[doc = "Converts `"]
57 #[doc = stringify!($ty)]
58 #[doc = "` to a big-endian byte array."]
59 #[inline]
60 pub fn to_be_bytes(self) -> [u8; 32] { self.0.to_be_bytes() }
61
62 #[doc = "Converts `"]
63 #[doc = stringify!($ty)]
64 #[doc = "` to a little-endian byte array."]
65 #[inline]
66 pub fn to_le_bytes(self) -> [u8; 32] { self.0.to_le_bytes() }
67 }
68
69 impl fmt::Display for $ty {
70 #[inline]
71 fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
72 fmt::Display::fmt(&self.0, f)
73 }
74 }
75
76 impl fmt::LowerHex for $ty {
77 #[inline]
78 fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
79 fmt::LowerHex::fmt(&self.0, f)
80 }
81 }
82
83 impl fmt::UpperHex for $ty {
84 #[inline]
85 fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
86 fmt::UpperHex::fmt(&self.0, f)
87 }
88 }
89 };
90}
91
92#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
96#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
97#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
98pub struct Work(U256);
99
100impl Work {
101 pub fn to_target(self) -> Target { Target(self.0.inverse()) }
103
104 #[cfg(feature = "std")]
110 pub fn log2(self) -> f64 { self.0.to_f64().log2() }
111}
112do_impl!(Work);
113
114impl Add for Work {
115 type Output = Work;
116 fn add(self, rhs: Self) -> Self { Work(self.0 + rhs.0) }
117}
118
119impl Sub for Work {
120 type Output = Work;
121 fn sub(self, rhs: Self) -> Self { Work(self.0 - rhs.0) }
122}
123
124#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
132#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
133#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
134pub struct Target(U256);
135
136impl Target {
137 pub const ZERO: Target = Target(U256::ZERO);
139 pub const MAX: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
149
150 pub const MAX_ATTAINABLE_MAINNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
155
156 pub const MAX_ATTAINABLE_TESTNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
160
161 pub const MAX_ATTAINABLE_REGTEST: Self = Target(U256(0x7FFF_FF00u128 << 96, 0));
165
166 pub const MAX_ATTAINABLE_SIGNET: Self = Target(U256(0x0377_ae00 << 80, 0));
170
171 pub fn from_compact(c: CompactTarget) -> Target {
175 let bits = c.0;
176 let (mant, expt) = {
181 let unshifted_expt = bits >> 24;
182 if unshifted_expt <= 3 {
183 ((bits & 0xFFFFFF) >> (8 * (3 - unshifted_expt as usize)), 0)
184 } else {
185 (bits & 0xFFFFFF, 8 * ((bits >> 24) - 3))
186 }
187 };
188
189 if mant > 0x7F_FFFF {
191 Target::ZERO
192 } else {
193 Target(U256::from(mant) << expt)
194 }
195 }
196
197 pub fn to_compact_lossy(self) -> CompactTarget {
202 let mut size = (self.0.bits() + 7) / 8;
203 let mut compact = if size <= 3 {
204 (self.0.low_u64() << (8 * (3 - size))) as u32
205 } else {
206 let bn = self.0 >> (8 * (size - 3));
207 bn.low_u32()
208 };
209
210 if (compact & 0x0080_0000) != 0 {
211 compact >>= 8;
212 size += 1;
213 }
214
215 CompactTarget(compact | (size << 24))
216 }
217
218 #[cfg_attr(all(test, mutate), mutate)]
223 pub fn is_met_by(&self, hash: BlockHash) -> bool {
224 use hashes::Hash;
225 let hash = U256::from_le_bytes(hash.to_byte_array());
226 hash <= self.0
227 }
228
229 pub fn to_work(self) -> Work { Work(self.0.inverse()) }
235
236 #[cfg_attr(all(test, mutate), mutate)]
261 pub fn difficulty(&self, params: impl AsRef<Params>) -> u128 {
262 assert_ne!(self.0, U256::ZERO, "divide by zero");
264
265 let max = params.as_ref().max_attainable_target;
266 let d = max.0 / self.0;
267 d.saturating_to_u128()
268 }
269
270 #[cfg_attr(all(test, mutate), mutate)]
280 pub fn difficulty_float(&self) -> f64 { TARGET_MAX_F64 / self.0.to_f64() }
281
282 #[deprecated(since = "0.32.0", note = "use min_transition_threshold instead")]
285 pub fn min_difficulty_transition_threshold(&self) -> Self { self.min_transition_threshold() }
286
287 #[deprecated(since = "0.32.0", note = "use max_transition_threshold instead")]
290 pub fn max_difficulty_transition_threshold(&self) -> Self {
291 self.max_transition_threshold_unchecked()
292 }
293
294 pub fn min_transition_threshold(&self) -> Self { Self(self.0 >> 2) }
304
305 pub fn max_transition_threshold(&self, params: impl AsRef<Params>) -> Self {
314 let max_attainable = params.as_ref().max_attainable_target;
315 cmp::min(self.max_transition_threshold_unchecked(), max_attainable)
316 }
317
318 pub fn max_transition_threshold_unchecked(&self) -> Self { Self(self.0 << 2) }
331}
332do_impl!(Target);
333
334#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
342#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
343#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
344pub struct CompactTarget(u32);
345
346impl CompactTarget {
347 pub fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
349 let stripped = if let Some(stripped) = s.strip_prefix("0x") {
350 stripped
351 } else if let Some(stripped) = s.strip_prefix("0X") {
352 stripped
353 } else {
354 return Err(MissingPrefixError::new(s).into());
355 };
356
357 let target = parse::hex_u32(stripped)?;
358 Ok(Self::from_consensus(target))
359 }
360
361 pub fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
363 if s.starts_with("0x") || s.starts_with("0X") {
364 return Err(ContainsPrefixError::new(s).into());
365 }
366 let lock_time = parse::hex_u32(s)?;
367 Ok(Self::from_consensus(lock_time))
368 }
369
370 pub fn from_next_work_required(
393 last: CompactTarget,
394 timespan: u64,
395 params: impl AsRef<Params>,
396 ) -> CompactTarget {
397 let params = params.as_ref();
398 if params.no_pow_retargeting {
399 return last;
400 }
401 let min_timespan = params.pow_target_timespan >> 2; let max_timespan = params.pow_target_timespan << 2; let actual_timespan = timespan.clamp(min_timespan, max_timespan);
406 let prev_target: Target = last.into();
407 let maximum_retarget = prev_target.max_transition_threshold(params); let retarget = prev_target.0; let retarget = retarget.mul(actual_timespan.into());
410 let retarget = retarget.div(params.pow_target_timespan.into());
411 let retarget = Target(retarget);
412 if retarget.ge(&maximum_retarget) {
413 return maximum_retarget.to_compact_lossy();
414 }
415 retarget.to_compact_lossy()
416 }
417
418 pub fn from_header_difficulty_adjustment(
437 last_epoch_boundary: Header,
438 current: Header,
439 params: impl AsRef<Params>,
440 ) -> CompactTarget {
441 let timespan = current.time - last_epoch_boundary.time;
442 let bits = current.bits;
443 CompactTarget::from_next_work_required(bits, timespan.into(), params)
444 }
445
446 pub fn from_consensus(bits: u32) -> Self { Self(bits) }
448
449 pub fn to_consensus(self) -> u32 { self.0 }
451}
452
453impl From<CompactTarget> for Target {
454 fn from(c: CompactTarget) -> Self { Target::from_compact(c) }
455}
456
457impl Encodable for CompactTarget {
458 #[inline]
459 fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
460 self.0.consensus_encode(w)
461 }
462}
463
464impl Decodable for CompactTarget {
465 #[inline]
466 fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
467 u32::consensus_decode(r).map(CompactTarget)
468 }
469}
470
471impl LowerHex for CompactTarget {
472 #[inline]
473 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { LowerHex::fmt(&self.0, f) }
474}
475
476impl UpperHex for CompactTarget {
477 #[inline]
478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { UpperHex::fmt(&self.0, f) }
479}
480
481#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
484struct U256(u128, u128);
485
486impl U256 {
487 const MAX: U256 =
488 U256(0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
489
490 const ZERO: U256 = U256(0, 0);
491
492 const ONE: U256 = U256(0, 1);
493
494 fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
496 let stripped = if let Some(stripped) = s.strip_prefix("0x") {
497 stripped
498 } else if let Some(stripped) = s.strip_prefix("0X") {
499 stripped
500 } else {
501 return Err(MissingPrefixError::new(s).into());
502 };
503 Ok(U256::from_hex_internal(stripped)?)
504 }
505
506 fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
508 if s.starts_with("0x") || s.starts_with("0X") {
509 return Err(ContainsPrefixError::new(s).into());
510 }
511 Ok(U256::from_hex_internal(s)?)
512 }
513
514 fn from_hex_internal(s: &str) -> Result<Self, ParseIntError> {
516 let (high, low) = if s.len() <= 32 {
517 let low = parse::hex_u128(s)?;
518 (0, low)
519 } else {
520 let high_len = s.len() - 32;
521 let high_s = &s[..high_len];
522 let low_s = &s[high_len..];
523
524 let high = parse::hex_u128(high_s)?;
525 let low = parse::hex_u128(low_s)?;
526 (high, low)
527 };
528
529 Ok(U256(high, low))
530 }
531
532 #[cfg_attr(all(test, mutate), mutate)]
534 fn from_be_bytes(a: [u8; 32]) -> U256 {
535 let (high, low) = split_in_half(a);
536 let big = u128::from_be_bytes(high);
537 let little = u128::from_be_bytes(low);
538 U256(big, little)
539 }
540
541 #[cfg_attr(all(test, mutate), mutate)]
543 fn from_le_bytes(a: [u8; 32]) -> U256 {
544 let (high, low) = split_in_half(a);
545 let little = u128::from_le_bytes(high);
546 let big = u128::from_le_bytes(low);
547 U256(big, little)
548 }
549
550 #[cfg_attr(all(test, mutate), mutate)]
552 fn to_be_bytes(self) -> [u8; 32] {
553 let mut out = [0; 32];
554 out[..16].copy_from_slice(&self.0.to_be_bytes());
555 out[16..].copy_from_slice(&self.1.to_be_bytes());
556 out
557 }
558
559 #[cfg_attr(all(test, mutate), mutate)]
561 fn to_le_bytes(self) -> [u8; 32] {
562 let mut out = [0; 32];
563 out[..16].copy_from_slice(&self.1.to_le_bytes());
564 out[16..].copy_from_slice(&self.0.to_le_bytes());
565 out
566 }
567
568 fn inverse(&self) -> U256 {
574 if self.is_zero() {
577 return U256::MAX;
578 }
579 if self.is_one() {
581 return U256::MAX;
582 }
583 if self.is_max() {
585 return U256::ONE;
586 }
587
588 let ret = !*self / self.wrapping_inc();
589 ret.wrapping_inc()
590 }
591
592 #[cfg_attr(all(test, mutate), mutate)]
593 fn is_zero(&self) -> bool { self.0 == 0 && self.1 == 0 }
594
595 #[cfg_attr(all(test, mutate), mutate)]
596 fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 }
597
598 #[cfg_attr(all(test, mutate), mutate)]
599 fn is_max(&self) -> bool { self.0 == u128::MAX && self.1 == u128::MAX }
600
601 fn low_u32(&self) -> u32 { self.low_u128() as u32 }
603
604 fn low_u64(&self) -> u64 { self.low_u128() as u64 }
606
607 fn low_u128(&self) -> u128 { self.1 }
609
610 fn saturating_to_u128(&self) -> u128 {
613 if *self > U256::from(u128::MAX) {
614 u128::MAX
615 } else {
616 self.low_u128()
617 }
618 }
619
620 #[cfg_attr(all(test, mutate), mutate)]
622 fn bits(&self) -> u32 {
623 if self.0 > 0 {
624 256 - self.0.leading_zeros()
625 } else {
626 128 - self.1.leading_zeros()
627 }
628 }
629
630 #[cfg_attr(all(test, mutate), mutate)]
639 fn mul_u64(self, rhs: u64) -> (U256, bool) {
640 let mut carry: u128 = 0;
641 let mut split_le =
642 [self.1 as u64, (self.1 >> 64) as u64, self.0 as u64, (self.0 >> 64) as u64];
643
644 for word in &mut split_le {
645 let n = carry + u128::from(rhs) * u128::from(*word);
647
648 *word = n as u64; carry = n >> 64; }
651
652 let low = u128::from(split_le[0]) | u128::from(split_le[1]) << 64;
653 let high = u128::from(split_le[2]) | u128::from(split_le[3]) << 64;
654 (Self(high, low), carry != 0)
655 }
656
657 #[cfg_attr(all(test, mutate), mutate)]
667 fn div_rem(self, rhs: Self) -> (Self, Self) {
668 let mut sub_copy = self;
669 let mut shift_copy = rhs;
670 let mut ret = [0u128; 2];
671
672 let my_bits = self.bits();
673 let your_bits = rhs.bits();
674
675 assert!(your_bits != 0, "attempted to divide {} by zero", self);
677
678 if my_bits < your_bits {
680 return (U256::ZERO, sub_copy);
681 }
682
683 let mut shift = my_bits - your_bits;
685 shift_copy = shift_copy << shift;
686 loop {
687 if sub_copy >= shift_copy {
688 ret[1 - (shift / 128) as usize] |= 1 << (shift % 128);
689 sub_copy = sub_copy.wrapping_sub(shift_copy);
690 }
691 shift_copy = shift_copy >> 1;
692 if shift == 0 {
693 break;
694 }
695 shift -= 1;
696 }
697
698 (U256(ret[0], ret[1]), sub_copy)
699 }
700
701 #[must_use = "this returns the result of the operation, without modifying the original"]
706 #[cfg_attr(all(test, mutate), mutate)]
707 fn overflowing_add(self, rhs: Self) -> (Self, bool) {
708 let mut ret = U256::ZERO;
709 let mut ret_overflow = false;
710
711 let (high, overflow) = self.0.overflowing_add(rhs.0);
712 ret.0 = high;
713 ret_overflow |= overflow;
714
715 let (low, overflow) = self.1.overflowing_add(rhs.1);
716 ret.1 = low;
717 if overflow {
718 let (high, overflow) = ret.0.overflowing_add(1);
719 ret.0 = high;
720 ret_overflow |= overflow;
721 }
722
723 (ret, ret_overflow)
724 }
725
726 #[must_use = "this returns the result of the operation, without modifying the original"]
731 #[cfg_attr(all(test, mutate), mutate)]
732 fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
733 let ret = self.wrapping_add(!rhs).wrapping_add(Self::ONE);
734 let overflow = rhs > self;
735 (ret, overflow)
736 }
737
738 #[must_use = "this returns the result of the operation, without modifying the original"]
744 #[cfg_attr(all(test, mutate), mutate)]
745 fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
746 let mut ret = U256::ZERO;
747 let mut ret_overflow = false;
748
749 for i in 0..3 {
750 let to_mul = (rhs >> (64 * i)).low_u64();
751 let (mul_res, _) = self.mul_u64(to_mul);
752 ret = ret.wrapping_add(mul_res << (64 * i));
753 }
754
755 let to_mul = (rhs >> 192).low_u64();
756 let (mul_res, overflow) = self.mul_u64(to_mul);
757 ret_overflow |= overflow;
758 let (sum, overflow) = ret.overflowing_add(mul_res);
759 ret = sum;
760 ret_overflow |= overflow;
761
762 (ret, ret_overflow)
763 }
764
765 #[must_use = "this returns the result of the operation, without modifying the original"]
768 fn wrapping_add(self, rhs: Self) -> Self {
769 let (ret, _overflow) = self.overflowing_add(rhs);
770 ret
771 }
772
773 #[must_use = "this returns the result of the operation, without modifying the original"]
776 fn wrapping_sub(self, rhs: Self) -> Self {
777 let (ret, _overflow) = self.overflowing_sub(rhs);
778 ret
779 }
780
781 #[must_use = "this returns the result of the operation, without modifying the original"]
784 #[cfg(test)]
785 fn wrapping_mul(self, rhs: Self) -> Self {
786 let (ret, _overflow) = self.overflowing_mul(rhs);
787 ret
788 }
789
790 #[must_use = "this returns the result of the increment, without modifying the original"]
792 #[cfg_attr(all(test, mutate), mutate)]
793 fn wrapping_inc(&self) -> U256 {
794 let mut ret = U256::ZERO;
795
796 ret.1 = self.1.wrapping_add(1);
797 if ret.1 == 0 {
798 ret.0 = self.0.wrapping_add(1);
799 } else {
800 ret.0 = self.0;
801 }
802 ret
803 }
804
805 #[must_use = "this returns the result of the operation, without modifying the original"]
812 #[cfg_attr(all(test, mutate), mutate)]
813 fn wrapping_shl(self, rhs: u32) -> Self {
814 let shift = rhs & 0x000000ff;
815
816 let mut ret = U256::ZERO;
817 let word_shift = shift >= 128;
818 let bit_shift = shift % 128;
819
820 if word_shift {
821 ret.0 = self.1 << bit_shift
822 } else {
823 ret.0 = self.0 << bit_shift;
824 if bit_shift > 0 {
825 ret.0 += self.1.wrapping_shr(128 - bit_shift);
826 }
827 ret.1 = self.1 << bit_shift;
828 }
829 ret
830 }
831
832 #[must_use = "this returns the result of the operation, without modifying the original"]
839 #[cfg_attr(all(test, mutate), mutate)]
840 fn wrapping_shr(self, rhs: u32) -> Self {
841 let shift = rhs & 0x000000ff;
842
843 let mut ret = U256::ZERO;
844 let word_shift = shift >= 128;
845 let bit_shift = shift % 128;
846
847 if word_shift {
848 ret.1 = self.0 >> bit_shift
849 } else {
850 ret.0 = self.0 >> bit_shift;
851 ret.1 = self.1 >> bit_shift;
852 if bit_shift > 0 {
853 ret.1 += self.0.wrapping_shl(128 - bit_shift);
854 }
855 }
856 ret
857 }
858
859 fn fmt_decimal(&self, f: &mut fmt::Formatter) -> fmt::Result {
861 const DIGITS: usize = 78; const TEN: U256 = U256(0, 10);
863
864 let mut buf = [0_u8; DIGITS];
865 let mut i = DIGITS - 1; let mut cur = *self;
867
868 loop {
869 let digit = (cur % TEN).low_u128() as u8; buf[i] = digit + b'0';
871 cur = cur / TEN;
872 if cur.is_zero() {
873 break;
874 }
875 i -= 1;
876 }
877 let s = core::str::from_utf8(&buf[i..]).expect("digits 0-9 are valid UTF8");
878 f.pad_integral(true, "", s)
879 }
880
881 #[inline]
883 fn to_f64(self) -> f64 {
884 let leading_zeroes = 256 - self.bits();
887 let left_aligned = self.wrapping_shl(leading_zeroes);
889 let middle_aligned = left_aligned >> 75;
892 let mantissa = middle_aligned.0;
894 let dropped_bits = middle_aligned.1 | (left_aligned.1 & 0x7FF_FFFF_FFFF_FFFF_FFFF);
898 let mantissa =
906 (mantissa + ((dropped_bits - (dropped_bits >> 127 & !mantissa)) >> 127)) as u64;
907 let exponent = if self == Self::ZERO { 0 } else { 1277 - leading_zeroes as u64 };
912 f64::from_bits((exponent << 52) + mantissa)
915 }
916}
917
918const TARGET_MAX_F64: f64 = 2.695953529101131e67;
921
922impl<T: Into<u128>> From<T> for U256 {
923 fn from(x: T) -> Self { U256(0, x.into()) }
924}
925
926impl Add for U256 {
927 type Output = Self;
928 fn add(self, rhs: Self) -> Self {
929 let (res, overflow) = self.overflowing_add(rhs);
930 debug_assert!(!overflow, "Addition of U256 values overflowed");
931 res
932 }
933}
934
935impl Sub for U256 {
936 type Output = Self;
937 fn sub(self, rhs: Self) -> Self {
938 let (res, overflow) = self.overflowing_sub(rhs);
939 debug_assert!(!overflow, "Subtraction of U256 values overflowed");
940 res
941 }
942}
943
944impl Mul for U256 {
945 type Output = Self;
946 fn mul(self, rhs: Self) -> Self {
947 let (res, overflow) = self.overflowing_mul(rhs);
948 debug_assert!(!overflow, "Multiplication of U256 values overflowed");
949 res
950 }
951}
952
953impl Div for U256 {
954 type Output = Self;
955 fn div(self, rhs: Self) -> Self { self.div_rem(rhs).0 }
956}
957
958impl Rem for U256 {
959 type Output = Self;
960 fn rem(self, rhs: Self) -> Self { self.div_rem(rhs).1 }
961}
962
963impl Not for U256 {
964 type Output = Self;
965
966 fn not(self) -> Self { U256(!self.0, !self.1) }
967}
968
969impl Shl<u32> for U256 {
970 type Output = Self;
971 fn shl(self, shift: u32) -> U256 { self.wrapping_shl(shift) }
972}
973
974impl Shr<u32> for U256 {
975 type Output = Self;
976 fn shr(self, shift: u32) -> U256 { self.wrapping_shr(shift) }
977}
978
979impl fmt::Display for U256 {
980 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
981 if self.is_zero() {
982 f.pad_integral(true, "", "0")
983 } else {
984 self.fmt_decimal(f)
985 }
986 }
987}
988
989impl fmt::Debug for U256 {
990 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:#x}", self) }
991}
992
993macro_rules! impl_hex {
994 ($hex:ident, $case:expr) => {
995 impl $hex for U256 {
996 fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
997 hex::fmt_hex_exact!(f, 32, &self.to_be_bytes(), $case)
998 }
999 }
1000 };
1001}
1002impl_hex!(LowerHex, hex::Case::Lower);
1003impl_hex!(UpperHex, hex::Case::Upper);
1004
1005#[cfg(feature = "serde")]
1006impl crate::serde::Serialize for U256 {
1007 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1008 where
1009 S: crate::serde::Serializer,
1010 {
1011 struct DisplayHex(U256);
1012
1013 impl fmt::Display for DisplayHex {
1014 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:x}", self.0) }
1015 }
1016
1017 if serializer.is_human_readable() {
1018 serializer.collect_str(&DisplayHex(*self))
1019 } else {
1020 let bytes = self.to_be_bytes();
1021 serializer.serialize_bytes(&bytes)
1022 }
1023 }
1024}
1025
1026#[cfg(feature = "serde")]
1027impl<'de> crate::serde::Deserialize<'de> for U256 {
1028 fn deserialize<D: crate::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1029 use hex::FromHex;
1030
1031 use crate::serde::de;
1032
1033 if d.is_human_readable() {
1034 struct HexVisitor;
1035
1036 impl<'de> de::Visitor<'de> for HexVisitor {
1037 type Value = U256;
1038
1039 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040 f.write_str("a 32 byte ASCII hex string")
1041 }
1042
1043 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1044 where
1045 E: de::Error,
1046 {
1047 if s.len() != 64 {
1048 return Err(de::Error::invalid_length(s.len(), &self));
1049 }
1050
1051 let b = <[u8; 32]>::from_hex(s)
1052 .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
1053
1054 Ok(U256::from_be_bytes(b))
1055 }
1056
1057 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1058 where
1059 E: de::Error,
1060 {
1061 if let Ok(hex) = core::str::from_utf8(v) {
1062 let b = <[u8; 32]>::from_hex(hex).map_err(|_| {
1063 de::Error::invalid_value(de::Unexpected::Str(hex), &self)
1064 })?;
1065
1066 Ok(U256::from_be_bytes(b))
1067 } else {
1068 Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
1069 }
1070 }
1071 }
1072 d.deserialize_str(HexVisitor)
1073 } else {
1074 struct BytesVisitor;
1075
1076 impl<'de> serde::de::Visitor<'de> for BytesVisitor {
1077 type Value = U256;
1078
1079 fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1080 f.write_str("a sequence of bytes")
1081 }
1082
1083 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1084 where
1085 E: serde::de::Error,
1086 {
1087 let b = v.try_into().map_err(|_| de::Error::invalid_length(v.len(), &self))?;
1088 Ok(U256::from_be_bytes(b))
1089 }
1090 }
1091
1092 d.deserialize_bytes(BytesVisitor)
1093 }
1094 }
1095}
1096
1097fn split_in_half(a: [u8; 32]) -> ([u8; 16], [u8; 16]) {
1099 let mut high = [0_u8; 16];
1100 let mut low = [0_u8; 16];
1101
1102 high.copy_from_slice(&a[..16]);
1103 low.copy_from_slice(&a[16..]);
1104
1105 (high, low)
1106}
1107
1108#[cfg(kani)]
1109impl kani::Arbitrary for U256 {
1110 fn any() -> Self {
1111 let high: u128 = kani::any();
1112 let low: u128 = kani::any();
1113 Self(high, low)
1114 }
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120
1121 impl<T: Into<u128>> From<T> for Target {
1122 fn from(x: T) -> Self { Self(U256::from(x)) }
1123 }
1124
1125 impl<T: Into<u128>> From<T> for Work {
1126 fn from(x: T) -> Self { Self(U256::from(x)) }
1127 }
1128
1129 impl U256 {
1130 fn bit_at(&self, index: usize) -> bool {
1131 if index > 255 {
1132 panic!("index out of bounds");
1133 }
1134
1135 let word = if index < 128 { self.1 } else { self.0 };
1136 (word & (1 << (index % 128))) != 0
1137 }
1138 }
1139
1140 impl U256 {
1141 fn from_array(a: [u64; 4]) -> Self {
1143 let mut ret = U256::ZERO;
1144 ret.0 = (a[0] as u128) << 64 ^ (a[1] as u128);
1145 ret.1 = (a[2] as u128) << 64 ^ (a[3] as u128);
1146 ret
1147 }
1148 }
1149
1150 #[test]
1151 fn u256_num_bits() {
1152 assert_eq!(U256::from(255_u64).bits(), 8);
1153 assert_eq!(U256::from(256_u64).bits(), 9);
1154 assert_eq!(U256::from(300_u64).bits(), 9);
1155 assert_eq!(U256::from(60000_u64).bits(), 16);
1156 assert_eq!(U256::from(70000_u64).bits(), 17);
1157
1158 let u = U256::from(u128::MAX) << 1;
1159 assert_eq!(u.bits(), 129);
1160
1161 let mut shl = U256::from(70000_u64);
1163 shl = shl << 100;
1164 assert_eq!(shl.bits(), 117);
1165 shl = shl << 100;
1166 assert_eq!(shl.bits(), 217);
1167 shl = shl << 100;
1168 assert_eq!(shl.bits(), 0);
1169 }
1170
1171 #[test]
1172 fn u256_bit_at() {
1173 assert!(!U256::from(10_u64).bit_at(0));
1174 assert!(U256::from(10_u64).bit_at(1));
1175 assert!(!U256::from(10_u64).bit_at(2));
1176 assert!(U256::from(10_u64).bit_at(3));
1177 assert!(!U256::from(10_u64).bit_at(4));
1178
1179 let u = U256(0xa000_0000_0000_0000_0000_0000_0000_0000, 0);
1180 assert!(u.bit_at(255));
1181 assert!(!u.bit_at(254));
1182 assert!(u.bit_at(253));
1183 assert!(!u.bit_at(252));
1184 }
1185
1186 #[test]
1187 fn u256_lower_hex() {
1188 assert_eq!(
1189 format!("{:x}", U256::from(0xDEADBEEF_u64)),
1190 "00000000000000000000000000000000000000000000000000000000deadbeef",
1191 );
1192 assert_eq!(
1193 format!("{:#x}", U256::from(0xDEADBEEF_u64)),
1194 "0x00000000000000000000000000000000000000000000000000000000deadbeef",
1195 );
1196 assert_eq!(
1197 format!("{:x}", U256::MAX),
1198 "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1199 );
1200 assert_eq!(
1201 format!("{:#x}", U256::MAX),
1202 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1203 );
1204 }
1205
1206 #[test]
1207 fn u256_upper_hex() {
1208 assert_eq!(
1209 format!("{:X}", U256::from(0xDEADBEEF_u64)),
1210 "00000000000000000000000000000000000000000000000000000000DEADBEEF",
1211 );
1212 assert_eq!(
1213 format!("{:#X}", U256::from(0xDEADBEEF_u64)),
1214 "0x00000000000000000000000000000000000000000000000000000000DEADBEEF",
1215 );
1216 assert_eq!(
1217 format!("{:X}", U256::MAX),
1218 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1219 );
1220 assert_eq!(
1221 format!("{:#X}", U256::MAX),
1222 "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
1223 );
1224 }
1225
1226 #[test]
1227 fn u256_display() {
1228 assert_eq!(format!("{}", U256::from(100_u32)), "100",);
1229 assert_eq!(format!("{}", U256::ZERO), "0",);
1230 assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
1231 assert_eq!(
1232 format!("{}", U256::MAX),
1233 "115792089237316195423570985008687907853269984665640564039457584007913129639935",
1234 );
1235 }
1236
1237 macro_rules! check_format {
1238 ($($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
1239 $(
1240 #[test]
1241 fn $test_name() {
1242 assert_eq!(format!($format_string, U256::from($val)), $expected);
1243 }
1244 )*
1245 }
1246 }
1247 check_format! {
1248 check_fmt_0, 0_u32, "{}", "0";
1249 check_fmt_1, 0_u32, "{:2}", " 0";
1250 check_fmt_2, 0_u32, "{:02}", "00";
1251
1252 check_fmt_3, 1_u32, "{}", "1";
1253 check_fmt_4, 1_u32, "{:2}", " 1";
1254 check_fmt_5, 1_u32, "{:02}", "01";
1255
1256 check_fmt_10, 10_u32, "{}", "10";
1257 check_fmt_11, 10_u32, "{:2}", "10";
1258 check_fmt_12, 10_u32, "{:02}", "10";
1259 check_fmt_13, 10_u32, "{:3}", " 10";
1260 check_fmt_14, 10_u32, "{:03}", "010";
1261
1262 check_fmt_20, 1_u32, "{:<2}", "1 ";
1263 check_fmt_21, 1_u32, "{:<02}", "01";
1264 check_fmt_22, 1_u32, "{:>2}", " 1"; check_fmt_23, 1_u32, "{:>02}", "01";
1266 check_fmt_24, 1_u32, "{:^3}", " 1 ";
1267 check_fmt_25, 1_u32, "{:^03}", "001";
1268 check_fmt_30, 0_u32, "{:.1}", "0";
1270 check_fmt_31, 0_u32, "{:4.1}", " 0";
1271 check_fmt_32, 0_u32, "{:04.1}", "0000";
1272 }
1273
1274 #[test]
1275 fn u256_comp() {
1276 let small = U256::from_array([0, 0, 0, 10]);
1277 let big = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]);
1278 let bigger = U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x9C8C_3EE7_0C64_4118]);
1279 let biggest = U256::from_array([1, 0, 0x0209_E737_8231_E632, 0x5C8C_3EE7_0C64_4118]);
1280
1281 assert!(small < big);
1282 assert!(big < bigger);
1283 assert!(bigger < biggest);
1284 assert!(bigger <= biggest);
1285 assert!(biggest <= biggest);
1286 assert!(bigger >= big);
1287 assert!(bigger >= small);
1288 assert!(small <= small);
1289 }
1290
1291 const WANT: U256 =
1292 U256(0x1bad_cafe_dead_beef_deaf_babe_2bed_feed, 0xbaad_f00d_defa_ceda_11fe_d2ba_d1c0_ffe0);
1293
1294 #[rustfmt::skip]
1295 const BE_BYTES: [u8; 32] = [
1296 0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed,
1297 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba, 0xd1, 0xc0, 0xff, 0xe0,
1298 ];
1299
1300 #[rustfmt::skip]
1301 const LE_BYTES: [u8; 32] = [
1302 0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0, 0xad, 0xba,
1303 0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca, 0xad, 0x1b,
1304 ];
1305
1306 #[test]
1308 fn sanity_be_bytes() {
1309 let mut out = [0_u8; 32];
1310 out[..16].copy_from_slice(&WANT.0.to_be_bytes());
1311 out[16..].copy_from_slice(&WANT.1.to_be_bytes());
1312 assert_eq!(out, BE_BYTES);
1313 }
1314
1315 #[test]
1317 fn sanity_le_bytes() {
1318 let mut out = [0_u8; 32];
1319 out[..16].copy_from_slice(&WANT.1.to_le_bytes());
1320 out[16..].copy_from_slice(&WANT.0.to_le_bytes());
1321 assert_eq!(out, LE_BYTES);
1322 }
1323
1324 #[test]
1325 fn u256_to_be_bytes() {
1326 assert_eq!(WANT.to_be_bytes(), BE_BYTES);
1327 }
1328
1329 #[test]
1330 fn u256_from_be_bytes() {
1331 assert_eq!(U256::from_be_bytes(BE_BYTES), WANT);
1332 }
1333
1334 #[test]
1335 fn u256_to_le_bytes() {
1336 assert_eq!(WANT.to_le_bytes(), LE_BYTES);
1337 }
1338
1339 #[test]
1340 fn u256_from_le_bytes() {
1341 assert_eq!(U256::from_le_bytes(LE_BYTES), WANT);
1342 }
1343
1344 #[test]
1345 fn u256_from_u8() {
1346 let u = U256::from(0xbe_u8);
1347 assert_eq!(u, U256(0, 0xbe));
1348 }
1349
1350 #[test]
1351 fn u256_from_u16() {
1352 let u = U256::from(0xbeef_u16);
1353 assert_eq!(u, U256(0, 0xbeef));
1354 }
1355
1356 #[test]
1357 fn u256_from_u32() {
1358 let u = U256::from(0xdeadbeef_u32);
1359 assert_eq!(u, U256(0, 0xdeadbeef));
1360 }
1361
1362 #[test]
1363 fn u256_from_u64() {
1364 let u = U256::from(0xdead_beef_cafe_babe_u64);
1365 assert_eq!(u, U256(0, 0xdead_beef_cafe_babe));
1366 }
1367
1368 #[test]
1369 fn u256_from_u128() {
1370 let u = U256::from(0xdead_beef_cafe_babe_0123_4567_89ab_cdefu128);
1371 assert_eq!(u, U256(0, 0xdead_beef_cafe_babe_0123_4567_89ab_cdef));
1372 }
1373
1374 macro_rules! test_from_unsigned_integer_type {
1375 ($($test_name:ident, $ty:ident);* $(;)?) => {
1376 $(
1377 #[test]
1378 fn $test_name() {
1379 let want = U256(0, 0xAB);
1381
1382 let x = 0xAB as $ty;
1383 let got = U256::from(x);
1384
1385 assert_eq!(got, want);
1386 }
1387 )*
1388 }
1389 }
1390 test_from_unsigned_integer_type! {
1391 from_unsigned_integer_type_u8, u8;
1392 from_unsigned_integer_type_u16, u16;
1393 from_unsigned_integer_type_u32, u32;
1394 from_unsigned_integer_type_u64, u64;
1395 from_unsigned_integer_type_u128, u128;
1396 }
1397
1398 #[test]
1399 fn u256_from_be_array_u64() {
1400 let array = [
1401 0x1bad_cafe_dead_beef,
1402 0xdeaf_babe_2bed_feed,
1403 0xbaad_f00d_defa_ceda,
1404 0x11fe_d2ba_d1c0_ffe0,
1405 ];
1406
1407 let uint = U256::from_array(array);
1408 assert_eq!(uint, WANT);
1409 }
1410
1411 #[test]
1412 fn u256_shift_left() {
1413 let u = U256::from(1_u32);
1414 assert_eq!(u << 0, u);
1415 assert_eq!(u << 1, U256::from(2_u64));
1416 assert_eq!(u << 63, U256::from(0x8000_0000_0000_0000_u64));
1417 assert_eq!(u << 64, U256::from_array([0, 0, 0x0000_0000_0000_0001, 0]));
1418 assert_eq!(u << 127, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1419 assert_eq!(u << 128, U256(1, 0));
1420
1421 let x = U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000);
1422 assert_eq!(x << 1, U256(1, 0));
1423 }
1424
1425 #[test]
1426 fn u256_shift_right() {
1427 let u = U256(1, 0);
1428 assert_eq!(u >> 0, u);
1429 assert_eq!(u >> 1, U256(0, 0x8000_0000_0000_0000_0000_0000_0000_0000));
1430 assert_eq!(u >> 127, U256(0, 2));
1431 assert_eq!(u >> 128, U256(0, 1));
1432 }
1433
1434 #[test]
1435 fn u256_arithmetic() {
1436 let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1437 let copy = init;
1438
1439 let add = init.wrapping_add(copy);
1440 assert_eq!(add, U256::from_array([0, 0, 1, 0xBD5B_7DDF_BD5B_7DDE]));
1441 let shl = add << 88;
1443 assert_eq!(shl, U256::from_array([0, 0x01BD_5B7D, 0xDFBD_5B7D_DE00_0000, 0]));
1444 let shr = shl >> 40;
1445 assert_eq!(shr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0000]));
1446 let mut incr = shr;
1448 incr = incr.wrapping_inc();
1449 assert_eq!(incr, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5B, 0x7DDE_0000_0000_0001]));
1450 let sub = incr.wrapping_sub(init);
1452 assert_eq!(sub, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1453 let (mult, _) = sub.mul_u64(300);
1455 assert_eq!(mult, U256::from_array([0, 0, 0x0209_E737_8231_E632, 0x8C8C_3EE7_0C64_4118]));
1456 assert_eq!(U256::from(105_u32) / U256::from(5_u32), U256::from(21_u32));
1458 let div = mult / U256::from(300_u32);
1459 assert_eq!(div, U256::from_array([0, 0, 0x0001_BD5B_7DDF_BD5A, 0x9F30_4110_2152_4112]));
1460
1461 assert_eq!(U256::from(105_u32) % U256::from(5_u32), U256::ZERO);
1462 assert_eq!(U256::from(35498456_u32) % U256::from(3435_u32), U256::from(1166_u32));
1463 let rem_src = mult.wrapping_mul(U256::from(39842_u32)).wrapping_add(U256::from(9054_u32));
1464 assert_eq!(rem_src % U256::from(39842_u32), U256::from(9054_u32));
1465 }
1466
1467 #[test]
1468 fn u256_bit_inversion() {
1469 let v = U256(1, 0);
1470 let want = U256(
1471 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe,
1472 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff,
1473 );
1474 assert_eq!(!v, want);
1475
1476 let v = U256(0x0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c_0c0c, 0xeeee_eeee_eeee_eeee);
1477 let want = U256(
1478 0xf3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3_f3f3,
1479 0xffff_ffff_ffff_ffff_1111_1111_1111_1111,
1480 );
1481 assert_eq!(!v, want);
1482 }
1483
1484 #[test]
1485 fn u256_mul_u64_by_one() {
1486 let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1487 assert_eq!(v, v.mul_u64(1_u64).0);
1488 }
1489
1490 #[test]
1491 fn u256_mul_u64_by_zero() {
1492 let v = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1493 assert_eq!(U256::ZERO, v.mul_u64(0_u64).0);
1494 }
1495
1496 #[test]
1497 fn u256_mul_u64() {
1498 let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1499
1500 let u96_res = u64_val.mul_u64(0xFFFF_FFFF).0;
1501 let u128_res = u96_res.mul_u64(0xFFFF_FFFF).0;
1502 let u160_res = u128_res.mul_u64(0xFFFF_FFFF).0;
1503 let u192_res = u160_res.mul_u64(0xFFFF_FFFF).0;
1504 let u224_res = u192_res.mul_u64(0xFFFF_FFFF).0;
1505 let u256_res = u224_res.mul_u64(0xFFFF_FFFF).0;
1506
1507 assert_eq!(u96_res, U256::from_array([0, 0, 0xDEAD_BEEE, 0xFFFF_FFFF_2152_4111]));
1508 assert_eq!(
1509 u128_res,
1510 U256::from_array([0, 0, 0xDEAD_BEEE_2152_4110, 0x2152_4111_DEAD_BEEF])
1511 );
1512 assert_eq!(
1513 u160_res,
1514 U256::from_array([0, 0xDEAD_BEED, 0x42A4_8222_0000_0001, 0xBD5B_7DDD_2152_4111])
1515 );
1516 assert_eq!(
1517 u192_res,
1518 U256::from_array([
1519 0,
1520 0xDEAD_BEEC_63F6_C334,
1521 0xBD5B_7DDF_BD5B_7DDB,
1522 0x63F6_C333_DEAD_BEEF
1523 ])
1524 );
1525 assert_eq!(
1526 u224_res,
1527 U256::from_array([
1528 0xDEAD_BEEB,
1529 0x8549_0448_5964_BAAA,
1530 0xFFFF_FFFB_A69B_4558,
1531 0x7AB6_FBBB_2152_4111
1532 ])
1533 );
1534 assert_eq!(
1535 u256_res,
1536 U256(
1537 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1538 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1539 )
1540 );
1541 }
1542
1543 #[test]
1544 fn u256_addition() {
1545 let x = U256::from(u128::MAX);
1546 let (add, overflow) = x.overflowing_add(U256::ONE);
1547 assert!(!overflow);
1548 assert_eq!(add, U256(1, 0));
1549
1550 let (add, _) = add.overflowing_add(U256::ONE);
1551 assert_eq!(add, U256(1, 1));
1552 }
1553
1554 #[test]
1555 fn u256_subtraction() {
1556 let (sub, overflow) = U256::ONE.overflowing_sub(U256::ONE);
1557 assert!(!overflow);
1558 assert_eq!(sub, U256::ZERO);
1559
1560 let x = U256(1, 0);
1561 let (sub, overflow) = x.overflowing_sub(U256::ONE);
1562 assert!(!overflow);
1563 assert_eq!(sub, U256::from(u128::MAX));
1564 }
1565
1566 #[test]
1567 fn u256_multiplication() {
1568 let u64_val = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1569
1570 let u128_res = u64_val.wrapping_mul(u64_val);
1571
1572 assert_eq!(u128_res, U256(0, 0xC1B1_CD13_A4D1_3D46_048D_1354_216D_A321));
1573
1574 let u256_res = u128_res.wrapping_mul(u128_res);
1575
1576 assert_eq!(
1577 u256_res,
1578 U256(
1579 0x928D_92B4_D7F5_DF33_4AFC_FF6F_0375_C608,
1580 0xF5CF_7F36_18C2_C886_F4E1_66AA_D40D_0A41,
1581 )
1582 );
1583 }
1584
1585 #[test]
1586 fn u256_multiplication_bits_in_each_word() {
1587 let u = 1_u128 << 64 | 1_u128;
1589 let x = U256(u, u);
1590
1591 let u = 2_u128 << 64 | 2_u128;
1593 let y = U256(u, u);
1594
1595 let (got, overflow) = x.overflowing_mul(y);
1596
1597 let want = U256(
1598 0x0000_0000_0000_0008_0000_0000_0000_0008,
1599 0x0000_0000_0000_0006_0000_0000_0000_0004,
1600 );
1601 assert!(!overflow);
1602 assert_eq!(got, want)
1603 }
1604
1605 #[test]
1606 fn u256_increment() {
1607 let mut val = U256(
1608 0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1609 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
1610 );
1611 val = val.wrapping_inc();
1612 assert_eq!(
1613 val,
1614 U256(
1615 0xEFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1616 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
1617 )
1618 );
1619 val = val.wrapping_inc();
1620 assert_eq!(
1621 val,
1622 U256(
1623 0xF000_0000_0000_0000_0000_0000_0000_0000,
1624 0x0000_0000_0000_0000_0000_0000_0000_0000,
1625 )
1626 );
1627
1628 assert_eq!(U256::MAX.wrapping_inc(), U256::ZERO);
1629 }
1630
1631 #[test]
1632 fn u256_extreme_bitshift() {
1633 let init = U256::from(0xDEAD_BEEF_DEAD_BEEF_u64);
1636
1637 assert_eq!(init << 64, U256(0, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000));
1638 let add = (init << 64).wrapping_add(init);
1639 assert_eq!(add, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1640 assert_eq!(add >> 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1641 assert_eq!(add << 0, U256(0, 0xDEAD_BEEF_DEAD_BEEF_DEAD_BEEF_DEAD_BEEF));
1642 assert_eq!(add >> 64, U256(0, 0x0000_0000_0000_0000_DEAD_BEEF_DEAD_BEEF));
1643 assert_eq!(
1644 add << 64,
1645 U256(0xDEAD_BEEF_DEAD_BEEF, 0xDEAD_BEEF_DEAD_BEEF_0000_0000_0000_0000)
1646 );
1647 }
1648
1649 #[test]
1650 fn u256_to_from_hex_roundtrips() {
1651 let val = U256(
1652 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1653 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1654 );
1655 let hex = format!("0x{:x}", val);
1656 let got = U256::from_hex(&hex).expect("failed to parse hex");
1657 assert_eq!(got, val);
1658 }
1659
1660 #[test]
1661 fn u256_to_from_unprefixed_hex_roundtrips() {
1662 let val = U256(
1663 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1664 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1665 );
1666 let hex = format!("{:x}", val);
1667 let got = U256::from_unprefixed_hex(&hex).expect("failed to parse hex");
1668 assert_eq!(got, val);
1669 }
1670
1671 #[test]
1672 fn u256_from_hex_32_characters_long() {
1673 let hex = "a69b455cd41bb662a69b4555deadbeef";
1674 let want = U256(0x00, 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF);
1675 let got = U256::from_unprefixed_hex(hex).expect("failed to parse hex");
1676 assert_eq!(got, want);
1677 }
1678
1679 #[cfg(feature = "serde")]
1680 #[test]
1681 fn u256_serde() {
1682 let check = |uint, hex| {
1683 let json = format!("\"{}\"", hex);
1684 assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
1685 assert_eq!(::serde_json::from_str::<U256>(&json).unwrap(), uint);
1686
1687 let bin_encoded = bincode::serialize(&uint).unwrap();
1688 let bin_decoded: U256 = bincode::deserialize(&bin_encoded).unwrap();
1689 assert_eq!(bin_decoded, uint);
1690 };
1691
1692 check(U256::ZERO, "0000000000000000000000000000000000000000000000000000000000000000");
1693 check(
1694 U256::from(0xDEADBEEF_u32),
1695 "00000000000000000000000000000000000000000000000000000000deadbeef",
1696 );
1697 check(
1698 U256::from_array([0xdd44, 0xcc33, 0xbb22, 0xaa11]),
1699 "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
1700 );
1701 check(U256::MAX, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
1702 check(
1703 U256(
1704 0xDEAD_BEEA_A69B_455C_D41B_B662_A69B_4550,
1705 0xA69B_455C_D41B_B662_A69B_4555_DEAD_BEEF,
1706 ),
1707 "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
1708 );
1709
1710 assert!(::serde_json::from_str::<U256>(
1711 "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
1712 )
1713 .is_err()); assert!(::serde_json::from_str::<U256>(
1715 "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1716 )
1717 .is_err()); assert!(::serde_json::from_str::<U256>(
1719 "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
1720 )
1721 .is_err()); }
1723
1724 #[test]
1725 fn u256_is_max_correct_negative() {
1726 let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::MAX)];
1727 for t in tc {
1728 assert!(!t.is_max())
1729 }
1730 }
1731
1732 #[test]
1733 fn u256_is_max_correct_positive() {
1734 assert!(U256::MAX.is_max());
1735
1736 let u = u128::MAX;
1737 assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
1738 }
1739
1740 #[test]
1741 fn compact_target_from_hex_lower() {
1742 let target = CompactTarget::from_hex("0x010034ab").unwrap();
1743 assert_eq!(target, CompactTarget(0x010034ab));
1744 }
1745
1746 #[test]
1747 fn compact_target_from_hex_upper() {
1748 let target = CompactTarget::from_hex("0X010034AB").unwrap();
1749 assert_eq!(target, CompactTarget(0x010034ab));
1750 }
1751
1752 #[test]
1753 fn compact_target_from_unprefixed_hex_lower() {
1754 let target = CompactTarget::from_unprefixed_hex("010034ab").unwrap();
1755 assert_eq!(target, CompactTarget(0x010034ab));
1756 }
1757
1758 #[test]
1759 fn compact_target_from_unprefixed_hex_upper() {
1760 let target = CompactTarget::from_unprefixed_hex("010034AB").unwrap();
1761 assert_eq!(target, CompactTarget(0x010034ab));
1762 }
1763
1764 #[test]
1765 fn compact_target_from_hex_invalid_hex_should_err() {
1766 let hex = "0xzbf9";
1767 let result = CompactTarget::from_hex(hex);
1768 assert!(result.is_err());
1769 }
1770
1771 #[test]
1772 fn compact_target_lower_hex_and_upper_hex() {
1773 assert_eq!(format!("{:08x}", CompactTarget(0x01D0F456)), "01d0f456");
1774 assert_eq!(format!("{:08X}", CompactTarget(0x01d0f456)), "01D0F456");
1775 }
1776
1777 #[test]
1778 fn compact_target_from_upwards_difficulty_adjustment() {
1779 let params = Params::new(crate::Network::Signet);
1780 let starting_bits = CompactTarget::from_consensus(503543726); let start_time: u64 = 1598918400; let end_time: u64 = 1599332177; let timespan = end_time - start_time; let adjustment = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms);
1785 let adjustment_bits = CompactTarget::from_consensus(503394215); assert_eq!(adjustment, adjustment_bits);
1787 }
1788
1789 #[test]
1790 fn compact_target_from_downwards_difficulty_adjustment() {
1791 let params = Params::new(crate::Network::Signet);
1792 let starting_bits = CompactTarget::from_consensus(503394215); let start_time: u64 = 1599332844; let end_time: u64 = 1600591200; let timespan = end_time - start_time; let adjustment = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms);
1797 let adjustment_bits = CompactTarget::from_consensus(503397348); assert_eq!(adjustment, adjustment_bits);
1799 }
1800
1801 #[test]
1802 fn compact_target_from_upwards_difficulty_adjustment_using_headers() {
1803 use hashes::Hash;
1804
1805 use crate::block::Version;
1806 use crate::constants::genesis_block;
1807 use crate::TxMerkleNode;
1808 let params = Params::new(crate::Network::Signet);
1809 let epoch_start = genesis_block(¶ms).header;
1810 let current = Header {
1812 version: Version::ONE,
1813 prev_blockhash: BlockHash::all_zeros(),
1814 merkle_root: TxMerkleNode::all_zeros(),
1815 time: 1599332177,
1816 bits: epoch_start.bits,
1817 nonce: epoch_start.nonce,
1818 };
1819 let adjustment =
1820 CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params);
1821 let adjustment_bits = CompactTarget::from_consensus(503394215); assert_eq!(adjustment, adjustment_bits);
1823 }
1824
1825 #[test]
1826 fn compact_target_from_downwards_difficulty_adjustment_using_headers() {
1827 use hashes::Hash;
1828
1829 use crate::block::Version;
1830 use crate::TxMerkleNode;
1831 let params = Params::new(crate::Network::Signet);
1832 let starting_bits = CompactTarget::from_consensus(503394215); let epoch_start = Header {
1835 version: Version::ONE,
1836 prev_blockhash: BlockHash::all_zeros(),
1837 merkle_root: TxMerkleNode::all_zeros(),
1838 time: 1599332844,
1839 bits: starting_bits,
1840 nonce: 0,
1841 };
1842 let current = Header {
1844 version: Version::ONE,
1845 prev_blockhash: BlockHash::all_zeros(),
1846 merkle_root: TxMerkleNode::all_zeros(),
1847 time: 1600591200,
1848 bits: starting_bits,
1849 nonce: 0,
1850 };
1851 let adjustment =
1852 CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params);
1853 let adjustment_bits = CompactTarget::from_consensus(503397348); assert_eq!(adjustment, adjustment_bits);
1855 }
1856
1857 #[test]
1858 fn compact_target_from_maximum_upward_difficulty_adjustment() {
1859 let params = Params::new(crate::Network::Signet);
1860 let starting_bits = CompactTarget::from_consensus(503403001);
1861 let timespan = (0.2 * params.pow_target_timespan as f64) as u64;
1862 let got = CompactTarget::from_next_work_required(starting_bits, timespan, params);
1863 let want =
1864 Target::from_compact(starting_bits).min_transition_threshold().to_compact_lossy();
1865 assert_eq!(got, want);
1866 }
1867
1868 #[test]
1869 fn compact_target_from_minimum_downward_difficulty_adjustment() {
1870 let params = Params::new(crate::Network::Signet);
1871 let starting_bits = CompactTarget::from_consensus(403403001); let timespan = 5 * params.pow_target_timespan; let got = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms);
1874 let want =
1875 Target::from_compact(starting_bits).max_transition_threshold(params).to_compact_lossy();
1876 assert_eq!(got, want);
1877 }
1878
1879 #[test]
1880 fn compact_target_from_adjustment_is_max_target() {
1881 let params = Params::new(crate::Network::Signet);
1882 let starting_bits = CompactTarget::from_consensus(503543726); let timespan = 5 * params.pow_target_timespan; let got = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms);
1885 let want = params.max_attainable_target.to_compact_lossy();
1886 assert_eq!(got, want);
1887 }
1888
1889 #[test]
1890 fn target_from_compact() {
1891 let tests = vec![
1893 (0x0100_3456_u32, 0x00_u64), (0x0112_3456_u32, 0x12_u64),
1895 (0x0200_8000_u32, 0x80_u64),
1896 (0x0500_9234_u32, 0x9234_0000_u64),
1897 (0x0492_3456_u32, 0x00_u64), (0x0412_3456_u32, 0x1234_5600_u64), ];
1900
1901 for (n_bits, target) in tests {
1902 let want = Target::from(target);
1903 let got = Target::from_compact(CompactTarget::from_consensus(n_bits));
1904 assert_eq!(got, want);
1905 }
1906 }
1907
1908 #[test]
1909 fn target_is_met_by_for_target_equals_hash() {
1910 use std::str::FromStr;
1911
1912 use hashes::Hash;
1913
1914 let hash =
1915 BlockHash::from_str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")
1916 .expect("failed to parse block hash");
1917 let target = Target(U256::from_le_bytes(hash.to_byte_array()));
1918 assert!(target.is_met_by(hash));
1919 }
1920
1921 #[test]
1922 fn max_target_from_compact() {
1923 let bits = 0x1d00ffff_u32;
1925 let want = Target::MAX;
1926 let got = Target::from_compact(CompactTarget::from_consensus(bits));
1927 assert_eq!(got, want)
1928 }
1929
1930 #[test]
1931 fn target_difficulty_float() {
1932 assert_eq!(Target::MAX.difficulty_float(), 1.0_f64);
1933 assert_eq!(
1934 Target::from_compact(CompactTarget::from_consensus(0x1c00ffff_u32)).difficulty_float(),
1935 256.0_f64
1936 );
1937 assert_eq!(
1938 Target::from_compact(CompactTarget::from_consensus(0x1b00ffff_u32)).difficulty_float(),
1939 65536.0_f64
1940 );
1941 assert_eq!(
1942 Target::from_compact(CompactTarget::from_consensus(0x1a00f3a2_u32)).difficulty_float(),
1943 17628585.065897066_f64
1944 );
1945 }
1946
1947 #[test]
1948 fn roundtrip_compact_target() {
1949 let consensus = 0x1d00_ffff;
1950 let compact = CompactTarget::from_consensus(consensus);
1951 let t = Target::from_compact(CompactTarget::from_consensus(consensus));
1952 assert_eq!(t, Target::from(compact)); let back = t.to_compact_lossy();
1955 assert_eq!(back, compact); assert_eq!(back.to_consensus(), consensus);
1958 }
1959
1960 #[test]
1961 fn roundtrip_target_work() {
1962 let target = Target::from(0xdeadbeef_u32);
1963 let work = target.to_work();
1964 let back = work.to_target();
1965 assert_eq!(back, target)
1966 }
1967
1968 #[cfg(feature = "std")]
1969 #[test]
1970 fn work_log2() {
1971 let tests: Vec<(u128, f64)> = vec![
1973 (0x200020002, 33.000022), (0xa97d67041c5e51596ee7, 79.405055), (0x1dc45d79394baa8ab18b20, 84.895644), (0x8c85acb73287e335d525b98, 91.134654), (0x2ef447e01d1642c40a184ada, 93.553183), ];
1980
1981 for (chainwork, core_log2) in tests {
1982 let log2 = (Work::from(chainwork).log2() * 1e6).round() / 1e6;
1984 assert_eq!(log2, core_log2)
1985 }
1986
1987 assert_eq!(Work(U256::ONE).log2(), 0.0);
1988 assert_eq!(Work(U256::MAX).log2(), 256.0);
1989 }
1990
1991 #[test]
1992 fn u256_zero_min_max_inverse() {
1993 assert_eq!(U256::MAX.inverse(), U256::ONE);
1994 assert_eq!(U256::ONE.inverse(), U256::MAX);
1995 assert_eq!(U256::ZERO.inverse(), U256::MAX);
1996 }
1997
1998 #[test]
1999 fn u256_max_min_inverse_roundtrip() {
2000 let max = U256::MAX;
2001
2002 for min in [U256::ZERO, U256::ONE].iter() {
2003 assert_eq!(Target(max).to_work(), Work(U256::ONE));
2005 assert_eq!(Target(*min).to_work(), Work(max));
2006
2007 assert_eq!(Work(max).to_target(), Target(U256::ONE));
2008 assert_eq!(Work(*min).to_target(), Target(max));
2009 }
2010 }
2011
2012 #[test]
2013 fn u256_wrapping_add_wraps_at_boundary() {
2014 assert_eq!(U256::MAX.wrapping_add(U256::ONE), U256::ZERO);
2015 assert_eq!(U256::MAX.wrapping_add(U256::from(2_u8)), U256::ONE);
2016 }
2017
2018 #[test]
2019 fn u256_wrapping_sub_wraps_at_boundary() {
2020 assert_eq!(U256::ZERO.wrapping_sub(U256::ONE), U256::MAX);
2021 assert_eq!(U256::ONE.wrapping_sub(U256::from(2_u8)), U256::MAX);
2022 }
2023
2024 #[test]
2025 fn mul_u64_overflows() {
2026 let (_, overflow) = U256::MAX.mul_u64(2);
2027 assert!(overflow, "max * 2 should overflow");
2028 }
2029
2030 #[test]
2031 #[cfg(debug_assertions)]
2032 #[should_panic]
2033 fn u256_overflowing_addition_panics() { let _ = U256::MAX + U256::ONE; }
2034
2035 #[test]
2036 #[cfg(debug_assertions)]
2037 #[should_panic]
2038 fn u256_overflowing_subtraction_panics() { let _ = U256::ZERO - U256::ONE; }
2039
2040 #[test]
2041 #[cfg(debug_assertions)]
2042 #[should_panic]
2043 fn u256_multiplication_by_max_panics() { let _ = U256::MAX * U256::MAX; }
2044
2045 #[test]
2046 #[cfg(debug_assertions)]
2047 #[should_panic]
2048 fn work_overflowing_addition_panics() { let _ = Work(U256::MAX) + Work(U256::ONE); }
2049
2050 #[test]
2051 #[cfg(debug_assertions)]
2052 #[should_panic]
2053 fn work_overflowing_subtraction_panics() { let _ = Work(U256::ZERO) - Work(U256::ONE); }
2054
2055 #[test]
2056 fn u256_to_f64() {
2057 assert_eq!(Target::MAX.0.to_f64(), TARGET_MAX_F64);
2059 assert_eq!(U256::ZERO.to_f64(), 0.0_f64);
2060 assert_eq!(U256::ONE.to_f64(), 1.0_f64);
2061 assert_eq!(U256::MAX.to_f64(), 1.157920892373162e77_f64);
2062 assert_eq!((U256::MAX >> 1).to_f64(), 5.78960446186581e76_f64);
2063 assert_eq!((U256::MAX >> 128).to_f64(), 3.402823669209385e38_f64);
2064 assert_eq!((U256::MAX >> (256 - 54)).to_f64(), 1.8014398509481984e16_f64);
2065 assert_eq!((U256::MAX >> (256 - 53)).to_f64(), 9007199254740991.0_f64);
2067 assert_eq!((U256::MAX >> (256 - 32)).to_f64(), 4294967295.0_f64);
2068 assert_eq!((U256::MAX >> (256 - 16)).to_f64(), 65535.0_f64);
2069 assert_eq!((U256::MAX >> (256 - 8)).to_f64(), 255.0_f64);
2070 }
2071}
2072
2073#[cfg(kani)]
2074mod verification {
2075 use super::*;
2076
2077 #[kani::unwind(5)] #[kani::proof]
2079 fn check_mul_u64() {
2080 let x: U256 = kani::any();
2081 let y: u64 = kani::any();
2082
2083 let _ = x.mul_u64(y);
2084 }
2085}