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