// SPDX-License-Identifier: MIT //! 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; pub const MAX_POOL_LINE_BYTES: usize = 131_072; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PoolMessageError { TooLarge, Json, WrongMessage, Unnegotiated, InvalidField, InvalidHex, InvalidWork(JobError), } #[derive(Debug, Eq, PartialEq)] pub struct Subscription { pub extranonce1: Vec, pub extranonce2_size: usize, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ConfigureResult { pub version_mask: Option, pub subscribe_extranonce: bool, } #[derive(Debug, Eq, PartialEq)] pub enum PoolNotification { SetDifficulty(PoolDifficulty), SetExtranonce(Subscription), SetVersionMask(VersionMask), } pub struct PoolJob { pub id: String, pub clean_jobs: bool, pub work: Sha256Job, } fn parse_json(line: &[u8]) -> Result { if line.len() > MAX_POOL_LINE_BYTES { return Err(PoolMessageError::TooLarge); } serde_json::from_slice(line).map_err(|_| PoolMessageError::Json) } fn hex_bytes(text: &str) -> Result, PoolMessageError> { let bytes = text.as_bytes(); if bytes.len() & 1 != 0 { return Err(PoolMessageError::InvalidHex); } let mut result = Vec::with_capacity(bytes.len() / 2); for pair in bytes.chunks_exact(2) { let high = (pair[0] as char) .to_digit(16) .ok_or(PoolMessageError::InvalidHex)?; let low = (pair[1] as char) .to_digit(16) .ok_or(PoolMessageError::InvalidHex)?; result.push(((high << 4) | low) as u8); } Ok(result) } fn hex_fixed(field: &Value) -> Result<[u8; N], PoolMessageError> { let text = field.as_str().ok_or(PoolMessageError::InvalidField)?; if text.len() != N * 2 { return Err(PoolMessageError::InvalidField); } hex_bytes(text)? .try_into() .map_err(|_| PoolMessageError::InvalidField) } fn hex_u32(field: &Value) -> Result { let text = field.as_str().ok_or(PoolMessageError::InvalidField)?; if text.len() != 8 { return Err(PoolMessageError::InvalidField); } u32::from_str_radix(text, 16).map_err(|_| PoolMessageError::InvalidHex) } fn valid_subscription( extranonce1: Vec, extranonce2_size: u64, ) -> Result { if extranonce1.len() > 32 || extranonce2_size > 32 { return Err(PoolMessageError::InvalidField); } Ok(Subscription { extranonce1, extranonce2_size: extranonce2_size as usize, }) } /// Parse the response to a matching `mining.subscribe` request. pub fn parse_subscription(line: &[u8], request_id: u64) -> Result { let message = parse_json(line)?; if message.get("id").and_then(Value::as_u64) != Some(request_id) || !message.get("error").is_none_or(Value::is_null) { return Err(PoolMessageError::WrongMessage); } let result = message .get("result") .and_then(Value::as_array) .ok_or(PoolMessageError::InvalidField)?; if result.len() != 3 || !result[0].is_array() { return Err(PoolMessageError::InvalidField); } let extranonce1 = hex_bytes(result[1].as_str().ok_or(PoolMessageError::InvalidField)?)?; let extranonce2_size = result[2].as_u64().ok_or(PoolMessageError::InvalidField)?; valid_subscription(extranonce1, extranonce2_size) } /// Decode the response to a BIP310 configure request that offered version /// rolling. A pool mask outside this ASIC's changeable bits is unusable: the /// pool would reconstruct a different block version for submitted shares. pub fn parse_configure_response( line: &[u8], request_id: u64, ) -> Result, PoolMessageError> { let message = parse_json(line)?; if message.get("id").and_then(Value::as_u64) != Some(request_id) || !message.get("error").is_none_or(Value::is_null) { return Err(PoolMessageError::WrongMessage); } let result = message .get("result") .and_then(Value::as_object) .ok_or(PoolMessageError::InvalidField)?; match result.get("version-rolling") { Some(Value::Bool(false) | Value::String(_)) => Ok(None), Some(Value::Bool(true)) => { let mask = hex_u32( result .get("version-rolling.mask") .ok_or(PoolMessageError::InvalidField)?, )?; VersionMask::new(mask) .map(Some) .ok_or(PoolMessageError::InvalidField) } _ => Err(PoolMessageError::InvalidField), } } /// Decode both offered BIP310 extensions. An omitted extranonce extension is /// unsupported; its notifications cannot be used without an explicit grant. pub fn parse_configure_result( line: &[u8], request_id: u64, ) -> Result { let version_mask = parse_configure_response(line, request_id)?; let message = parse_json(line)?; let result = message .get("result") .and_then(Value::as_object) .ok_or(PoolMessageError::InvalidField)?; let subscribe_extranonce = match result.get("subscribe-extranonce") { Some(Value::Bool(value)) => *value, Some(Value::String(_)) | None => false, _ => return Err(PoolMessageError::InvalidField), }; Ok(ConfigureResult { version_mask, subscribe_extranonce, }) } /// Decode a matching authorization or share-submission result. A false /// result is an ordinary pool rejection and must not count as an accept. pub fn parse_boolean_response(line: &[u8], request_id: u64) -> Result { let message = parse_json(line)?; if message.get("id").and_then(Value::as_u64) != Some(request_id) { return Err(PoolMessageError::WrongMessage); } match message.get("result") { Some(Value::Bool(true)) if message.get("error").is_none_or(Value::is_null) => Ok(true), Some(Value::Bool(false)) => Ok(false), Some(Value::Null) if !message.get("error").is_none_or(Value::is_null) => Ok(false), _ => Err(PoolMessageError::InvalidField), } } /// Decode pool control notifications. The caller applies them in stream order: /// difficulty to the next job, extranonce to subsequent work, and the version /// mask immediately to all pending submissions. pub fn parse_control_notification( line: &[u8], version_rolling: bool, subscribe_extranonce: bool, ) -> Result { let message = parse_json(line)?; if !message.get("id").is_none_or(Value::is_null) { return Err(PoolMessageError::WrongMessage); } let method = message .get("method") .and_then(Value::as_str) .ok_or(PoolMessageError::WrongMessage)?; let params = message .get("params") .and_then(Value::as_array) .ok_or(PoolMessageError::InvalidField)?; match method { "mining.set_difficulty" if params.len() == 1 => { 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 => { if !version_rolling { return Err(PoolMessageError::Unnegotiated); } let mask = hex_u32(¶ms[0])?; let mask = VersionMask::new(mask).ok_or(PoolMessageError::InvalidField)?; Ok(PoolNotification::SetVersionMask(mask)) } "mining.set_extranonce" if params.len() == 2 => { if !subscribe_extranonce { return Err(PoolMessageError::Unnegotiated); } let extranonce1 = hex_bytes(params[0].as_str().ok_or(PoolMessageError::InvalidField)?)?; let size = params[1].as_u64().ok_or(PoolMessageError::InvalidField)?; Ok(PoolNotification::SetExtranonce(valid_subscription( extranonce1, size, )?)) } "mining.set_difficulty" | "mining.set_version_mask" | "mining.set_extranonce" => { Err(PoolMessageError::InvalidField) } _ => Err(PoolMessageError::WrongMessage), } } /// Parse exactly the nine Bitcoin `mining.notify` parameters into work. pub fn parse_notify(line: &[u8], subscription: &Subscription) -> Result { let message = parse_json(line)?; if message.get("method").and_then(Value::as_str) != Some("mining.notify") || !message.get("id").is_none_or(Value::is_null) { return Err(PoolMessageError::WrongMessage); } let params = message .get("params") .and_then(Value::as_array) .ok_or(PoolMessageError::InvalidField)?; if params.len() != 9 { return Err(PoolMessageError::InvalidField); } let id = params[0].as_str().ok_or(PoolMessageError::InvalidField)?; if id.is_empty() || id.len() > 128 { return Err(PoolMessageError::InvalidField); } let branches = params[4].as_array().ok_or(PoolMessageError::InvalidField)?; if branches.len() > 64 { return Err(PoolMessageError::InvalidField); } let mut merkle_branches = Vec::with_capacity(branches.len()); for branch in branches { merkle_branches.push(hex_fixed::<32>(branch)?); } let work = Sha256Job { prevhash_stratum: hex_fixed::<32>(¶ms[1])?, coinb1: hex_bytes(params[2].as_str().ok_or(PoolMessageError::InvalidField)?)?, coinb2: hex_bytes(params[3].as_str().ok_or(PoolMessageError::InvalidField)?)?, merkle_branches, version: hex_u32(¶ms[5])?, nbits: hex_u32(¶ms[6])?, ntime: hex_u32(¶ms[7])?, extranonce1: subscription.extranonce1.clone(), extranonce2_size: subscription.extranonce2_size, }; work.validate().map_err(PoolMessageError::InvalidWork)?; let clean_jobs = params[8].as_bool().ok_or(PoolMessageError::InvalidField)?; Ok(PoolJob { id: id.to_owned(), clean_jobs, work, }) } #[cfg(test)] mod configure_tests { use super::*; #[test] fn omitted_extranonce_extension_is_unsupported() { let line = br#"{"id":1,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000"},"error":null}"#; let result = parse_configure_result(line, 1).unwrap(); assert!(result.version_mask.is_some()); assert!(!result.subscribe_extranonce); } }