ckb_types/utilities/
difficulty.rsuse numext_fixed_uint::prelude::UintConvert;
use numext_fixed_uint::{u512, U256, U512};
pub const DIFF_TWO: u32 = 0x2080_0000;
const ONE: U256 = U256::one();
const HSPACE: U512 = u512!("0x10000000000000000000000000000000000000000000000000000000000000000");
fn target_to_difficulty(target: &U256) -> U256 {
if target == &ONE {
U256::max_value()
} else {
let (target, _): (U512, bool) = target.convert_into();
(HSPACE / target).convert_into().0
}
}
fn difficulty_to_target(difficulty: &U256) -> U256 {
if difficulty == &ONE {
U256::max_value()
} else {
let (difficulty, _): (U512, bool) = difficulty.convert_into();
(HSPACE / difficulty).convert_into().0
}
}
fn get_low64(target: &U256) -> u64 {
target.0[0]
}
pub fn target_to_compact(target: U256) -> u32 {
let bits = 256 - target.leading_zeros();
let exponent = u64::from((bits + 7) / 8);
let mut compact = if exponent <= 3 {
get_low64(&target) << (8 * (3 - exponent))
} else {
get_low64(&(target >> (8 * (exponent - 3))))
};
compact |= exponent << 24;
compact as u32
}
pub fn compact_to_target(compact: u32) -> (U256, bool) {
let exponent = compact >> 24;
let mut mantissa = U256::from(compact & 0x00ff_ffff);
let mut ret;
if exponent <= 3 {
mantissa >>= 8 * (3 - exponent);
ret = mantissa.clone();
} else {
ret = mantissa.clone();
ret <<= 8 * (exponent - 3);
}
let overflow = !mantissa.is_zero() && (exponent > 32);
(ret, overflow)
}
pub fn compact_to_difficulty(compact: u32) -> U256 {
let (target, overflow) = compact_to_target(compact);
if target.is_zero() || overflow {
return U256::zero();
}
target_to_difficulty(&target)
}
pub fn difficulty_to_compact(difficulty: U256) -> u32 {
let target = difficulty_to_target(&difficulty);
target_to_compact(target)
}