121 lines
4.1 KiB
Rust
121 lines
4.1 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Exact Bitcoin Stratum share target conversion; no floating point or nonce search.
|
|
|
|
use serde_json::Number;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum DifficultyError {
|
|
Invalid,
|
|
OutOfRange,
|
|
}
|
|
|
|
/// A positive decimal difficulty represented exactly as numerator/denominator.
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct PoolDifficulty {
|
|
numerator: u64,
|
|
denominator: u64,
|
|
}
|
|
|
|
impl PoolDifficulty {
|
|
pub fn from_json_number(number: &Number) -> Result<Self, DifficultyError> {
|
|
let text = number.as_str();
|
|
if text.len() > 128 || text.starts_with('-') {
|
|
return Err(DifficultyError::OutOfRange);
|
|
}
|
|
let (mantissa, exponent) = match text.split_once(['e', 'E']) {
|
|
Some((base, exponent)) => (
|
|
base,
|
|
exponent
|
|
.parse::<i32>()
|
|
.map_err(|_| DifficultyError::OutOfRange)?,
|
|
),
|
|
None => (text, 0),
|
|
};
|
|
let mut digits = Vec::with_capacity(mantissa.len());
|
|
let mut fractional = 0_i32;
|
|
let mut after_dot = false;
|
|
for byte in mantissa.bytes() {
|
|
match byte {
|
|
b'.' if !after_dot => after_dot = true,
|
|
b'0'..=b'9' => {
|
|
digits.push(byte - b'0');
|
|
if after_dot {
|
|
fractional += 1;
|
|
}
|
|
}
|
|
_ => return Err(DifficultyError::Invalid),
|
|
}
|
|
}
|
|
let first = digits
|
|
.iter()
|
|
.position(|digit| *digit != 0)
|
|
.ok_or(DifficultyError::Invalid)?;
|
|
let last = digits
|
|
.iter()
|
|
.rposition(|digit| *digit != 0)
|
|
.expect("nonzero digit");
|
|
let trailing = (digits.len() - last - 1) as i32;
|
|
let mut numerator = 0_u64;
|
|
for digit in &digits[first..=last] {
|
|
numerator = numerator
|
|
.checked_mul(10)
|
|
.and_then(|value| value.checked_add(u64::from(*digit)))
|
|
.ok_or(DifficultyError::OutOfRange)?;
|
|
}
|
|
let shift = exponent
|
|
.checked_sub(fractional)
|
|
.and_then(|value| value.checked_add(trailing))
|
|
.ok_or(DifficultyError::OutOfRange)?;
|
|
if !(-19..=19).contains(&shift) {
|
|
return Err(DifficultyError::OutOfRange);
|
|
}
|
|
let mut denominator = 1_u64;
|
|
if shift >= 0 {
|
|
for _ in 0..shift {
|
|
numerator = numerator
|
|
.checked_mul(10)
|
|
.ok_or(DifficultyError::OutOfRange)?;
|
|
}
|
|
} else {
|
|
for _ in 0..-shift {
|
|
denominator = denominator
|
|
.checked_mul(10)
|
|
.ok_or(DifficultyError::OutOfRange)?;
|
|
}
|
|
}
|
|
Ok(Self {
|
|
numerator,
|
|
denominator,
|
|
})
|
|
}
|
|
|
|
/// floor((0xFFFF << 208) / difficulty), capped at the 256-bit maximum.
|
|
/// The 320-bit intermediate permits all supported decimal denominators.
|
|
pub fn target_le(self) -> [u8; 32] {
|
|
let mut product = [0_u8; 40];
|
|
let mut carry = 0_u128;
|
|
for (index, byte) in product.iter_mut().enumerate() {
|
|
let diff_one_byte = if index == 26 || index == 27 { 0xff } else { 0 };
|
|
let value = (diff_one_byte as u128) * u128::from(self.denominator) + carry;
|
|
*byte = value as u8;
|
|
carry = value >> 8;
|
|
}
|
|
debug_assert_eq!(carry, 0);
|
|
|
|
let mut quotient = [0_u8; 40];
|
|
let mut remainder = 0_u128;
|
|
for index in (0..320).rev() {
|
|
let bit = (product[index / 8] >> (index % 8)) & 1;
|
|
remainder = (remainder << 1) | u128::from(bit);
|
|
if remainder >= u128::from(self.numerator) {
|
|
remainder -= u128::from(self.numerator);
|
|
quotient[index / 8] |= 1 << (index % 8);
|
|
}
|
|
}
|
|
if quotient[32..].iter().any(|byte| *byte != 0) {
|
|
return [0xff; 32];
|
|
}
|
|
quotient[..32].try_into().expect("256-bit quotient")
|
|
}
|
|
}
|