Files
alkane-os/src/stratum_v1.rs
T
noah 5d352139dd
main-release-gate / verify-and-release (push) Canceled after 0s
Decode bounded Stratum V1 pool jobs
2026-10-15 00:05:14 -06:00

146 lines
4.9 KiB
Rust

// 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::stratum_work::{JobError, Sha256Job};
use serde_json::Value;
const MAX_LINE_BYTES: usize = 131_072;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PoolMessageError {
TooLarge,
Json,
WrongMessage,
InvalidField,
InvalidHex,
InvalidWork(JobError),
}
pub struct Subscription {
pub extranonce1: Vec<u8>,
pub extranonce2_size: usize,
}
pub struct PoolJob {
pub id: String,
pub clean_jobs: bool,
pub work: Sha256Job,
}
fn parse_json(line: &[u8]) -> Result<Value, PoolMessageError> {
if line.len() > MAX_LINE_BYTES {
return Err(PoolMessageError::TooLarge);
}
serde_json::from_slice(line).map_err(|_| PoolMessageError::Json)
}
fn hex_bytes(text: &str) -> Result<Vec<u8>, 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<const N: usize>(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<u32, PoolMessageError> {
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)
}
/// Parse the response to a matching `mining.subscribe` request.
pub fn parse_subscription(line: &[u8], request_id: u64) -> Result<Subscription, 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_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)?;
if extranonce1.len() > 32 || extranonce2_size > 32 {
return Err(PoolMessageError::InvalidField);
}
Ok(Subscription {
extranonce1,
extranonce2_size: extranonce2_size as usize,
})
}
/// Parse exactly the nine Bitcoin `mining.notify` parameters into work.
pub fn parse_notify(line: &[u8], subscription: &Subscription) -> Result<PoolJob, PoolMessageError> {
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>(&params[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(&params[5])?,
nbits: hex_u32(&params[6])?,
ntime: hex_u32(&params[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,
})
}