Convert pool difficulty to exact share targets
next-build / build (push) Successful in 11s

This commit is contained in:
2026-10-15 01:00:53 -06:00
parent e7a23faa5a
commit 5cd77eb5de
7 changed files with 218 additions and 8 deletions
+120
View File
@@ -0,0 +1,120 @@
// 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")
}
}
+1
View File
@@ -4,6 +4,7 @@
//! the pairing already mines. Hardware backends are supplied by SDK images.
pub mod bm1366;
pub mod difficulty;
pub mod hal_wire;
pub mod miner;
pub mod pow;
+8 -6
View File
@@ -2,6 +2,7 @@
//! Bounded decoding of Bitcoin Stratum V1 subscription and job messages.
//! The network client must enforce a line limit before passing data here.
use crate::difficulty::PoolDifficulty;
use crate::pow::VersionMask;
use crate::stratum_work::{JobError, Sha256Job};
use serde_json::Value;
@@ -25,9 +26,9 @@ pub struct Subscription {
pub extranonce2_size: usize,
}
#[derive(Debug, PartialEq)]
#[derive(Debug, Eq, PartialEq)]
pub enum PoolNotification {
SetDifficulty(f64),
SetDifficulty(PoolDifficulty),
SetExtranonce(Subscription),
SetVersionMask(VersionMask),
}
@@ -169,10 +170,11 @@ pub fn parse_control_notification(
.ok_or(PoolMessageError::InvalidField)?;
match method {
"mining.set_difficulty" if params.len() == 1 => {
let difficulty = params[0].as_f64().ok_or(PoolMessageError::InvalidField)?;
if !difficulty.is_finite() || difficulty <= 0.0 {
return Err(PoolMessageError::InvalidField);
}
let number = params[0]
.as_number()
.ok_or(PoolMessageError::InvalidField)?;
let difficulty = PoolDifficulty::from_json_number(number)
.map_err(|_| PoolMessageError::InvalidField)?;
Ok(PoolNotification::SetDifficulty(difficulty))
}
"mining.set_version_mask" if params.len() == 1 => {