-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifficulty.rs
29 lines (22 loc) · 894 Bytes
/
difficulty.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use crate::u256;
pub fn bits_to_target(bits: u32) -> u256 {
// Target = coefficient * 2 ^ ( 8 * (index — 3) )
let exponent = bits >> 24;
let coefficient = u256::new((bits & 0x00ffffff).into());
coefficient << ((exponent - 3) * 8)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn bits_to_target_test() {
// genesis block bits & difficulty
let target_hex = "00000000ffff0000000000000000000000000000000000000000000000000000";
let target = u256::from_str_radix(target_hex, 16).unwrap();
assert_eq!(target, bits_to_target(486604799));
// inspired from https://learnmeabitcoin.com/technical/bits
let target_hex = "00000000000000000696f4000000000000000000000000000000000000000000";
let target = u256::from_str_radix(target_hex, 16).unwrap();
assert_eq!(target, bits_to_target(0x180696f4));
}
}