diff --git a/Cargo.toml b/Cargo.toml index 6daf206..0ee1001 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ description = "Portable mining and tuning core for Alkane control boards" name = "alkane_os" [dependencies] -serde_json = "=1.0.154" +serde_json = { version = "=1.0.154", features = ["arbitrary_precision"] } [profile.release] lto = true diff --git a/src/difficulty.rs b/src/difficulty.rs new file mode 100644 index 0000000..16c4cce --- /dev/null +++ b/src/difficulty.rs @@ -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 { + 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::() + .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") + } +} diff --git a/src/lib.rs b/src/lib.rs index 1718877..e2abea9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/stratum_v1.rs b/src/stratum_v1.rs index 82af9de..cf985da 100644 --- a/src/stratum_v1.rs +++ b/src/stratum_v1.rs @@ -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 => { diff --git a/tests/bench.rs b/tests/bench.rs index 7165614..cd38283 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -1,4 +1,5 @@ use alkane_os::bm1366::{decode_nonce_report, encode_work}; +use alkane_os::difficulty::PoolDifficulty; use alkane_os::miner::Bm1366Miner; use alkane_os::pow::verify_sha256_report; use alkane_os::pow::VersionMask; @@ -145,6 +146,16 @@ fn bench_stratum_control_parse() { }); } +#[test] +#[ignore = "microbenchmark"] +fn bench_difficulty_target() { + let number = serde_json::from_str("2048.5").unwrap(); + let difficulty = PoolDifficulty::from_json_number(&number).unwrap(); + measure("difficulty_target", 20_000, || { + black_box(black_box(difficulty).target_le()); + }); +} + struct BenchBackend; impl HardwareBackend for BenchBackend { diff --git a/tests/difficulty.rs b/tests/difficulty.rs new file mode 100644 index 0000000..7339c59 --- /dev/null +++ b/tests/difficulty.rs @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT +use alkane_os::difficulty::{DifficultyError, PoolDifficulty}; + +fn target(decimal: &str) -> String { + let number = serde_json::from_str(decimal).unwrap(); + PoolDifficulty::from_json_number(&number) + .unwrap() + .target_le() + .iter() + .rev() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +#[test] +fn exact_share_targets_match_integer_reference() { + for (difficulty, expected) in [ + ( + "1", + "00000000ffff0000000000000000000000000000000000000000000000000000", + ), + ( + "2", + "000000007fff8000000000000000000000000000000000000000000000000000", + ), + ( + "0.5", + "00000001fffe0000000000000000000000000000000000000000000000000000", + ), + ( + "1.25", + "00000000cccc0000000000000000000000000000000000000000000000000000", + ), + ( + "2048.5", + "00000000001ffde021fde021fde021fde021fde021fde021fde021fde021fde0", + ), + ( + "0.000001", + "000f4230bdc00000000000000000000000000000000000000000000000000000", + ), + ( + "1000000000000000000", + "000000000000000000000012724b5f7471d95d3bbefee5e602a7b17261180d8e", + ), + ] { + assert_eq!(target(difficulty), expected, "difficulty {difficulty}"); + } + assert_eq!(target("1.2e3"), target("1200")); + assert_eq!(target("1e-19"), "ff".repeat(32)); +} + +#[test] +fn invalid_or_unrepresentable_difficulty_is_rejected() { + let zero = serde_json::from_str("0").unwrap(); + assert_eq!( + PoolDifficulty::from_json_number(&zero), + Err(DifficultyError::Invalid) + ); + let negative = serde_json::from_str("-1").unwrap(); + assert_eq!( + PoolDifficulty::from_json_number(&negative), + Err(DifficultyError::OutOfRange) + ); + for value in ["1e20", "1e-20", "1.00000000000000000001"] { + let number = serde_json::from_str(value).unwrap(); + assert_eq!( + PoolDifficulty::from_json_number(&number), + Err(DifficultyError::OutOfRange), + "difficulty {value}" + ); + } +} diff --git a/tests/stratum_v1.rs b/tests/stratum_v1.rs index 105b664..371ac53 100644 --- a/tests/stratum_v1.rs +++ b/tests/stratum_v1.rs @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MIT +use alkane_os::difficulty::PoolDifficulty; use alkane_os::stratum_v1::{ parse_configure_response, parse_control_notification, parse_notify, parse_subscription, PoolMessageError, PoolNotification, Subscription, @@ -109,7 +110,9 @@ fn difficulty_and_extranonce_notifications_validate_shape_and_negotiation() { let difficulty = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#; assert_eq!( parse_control_notification(difficulty, false, false), - Ok(PoolNotification::SetDifficulty(2048.5)) + Ok(PoolNotification::SetDifficulty( + PoolDifficulty::from_json_number(&serde_json::from_str("2048.5").unwrap()).unwrap() + )) ); let extranonce = br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#; assert_eq!(