Files
alkane-os/src/stratum_work.rs
T
noah d2afef19a9
next-build / build (push) Canceled after 0s
Construct SHA-256 Stratum work headers for BM1366
2026-10-14 20:24:34 -06:00

84 lines
2.9 KiB
Rust

// SPDX-License-Identifier: MIT
//! Construct SHA-256 Stratum V1 work after a protocol client decodes notify.
//! This module assembles headers; it never searches for nonces.
use crate::pow::sha256d;
const MAX_COINBASE_BYTES: usize = 65_536;
const MAX_MERKLE_BRANCHES: usize = 64;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JobError {
InvalidExtranonceSize,
CoinbaseTooLarge,
TooManyMerkleBranches,
ExtranonceLength,
}
/// Binary fields from `mining.notify`, plus `mining.subscribe` extranonce data.
/// `prevhash_stratum` is the eight word-swapped 32-bit words sent on the wire.
pub struct Sha256Job {
pub prevhash_stratum: [u8; 32],
pub coinb1: Vec<u8>,
pub coinb2: Vec<u8>,
pub merkle_branches: Vec<[u8; 32]>,
pub version: u32,
pub nbits: u32,
pub ntime: u32,
pub extranonce1: Vec<u8>,
pub extranonce2_size: usize,
}
impl Sha256Job {
pub fn validate(&self) -> Result<(), JobError> {
if self.extranonce1.len() > 32 || self.extranonce2_size > 32 {
return Err(JobError::InvalidExtranonceSize);
}
let total = self
.coinb1
.len()
.checked_add(self.extranonce1.len())
.and_then(|sum| sum.checked_add(self.extranonce2_size))
.and_then(|sum| sum.checked_add(self.coinb2.len()));
if total.is_none_or(|sum| sum > MAX_COINBASE_BYTES) {
return Err(JobError::CoinbaseTooLarge);
}
if self.merkle_branches.len() > MAX_MERKLE_BRANCHES {
return Err(JobError::TooManyMerkleBranches);
}
Ok(())
}
pub fn nonce_zero_header(&self, extranonce2: &[u8], ntime: u32) -> Result<[u8; 80], JobError> {
self.validate()?;
if extranonce2.len() != self.extranonce2_size {
return Err(JobError::ExtranonceLength);
}
let mut coinbase = Vec::with_capacity(
self.coinb1.len() + self.extranonce1.len() + extranonce2.len() + self.coinb2.len(),
);
coinbase.extend_from_slice(&self.coinb1);
coinbase.extend_from_slice(&self.extranonce1);
coinbase.extend_from_slice(extranonce2);
coinbase.extend_from_slice(&self.coinb2);
let mut root = sha256d(&coinbase);
for branch in &self.merkle_branches {
let mut pair = [0_u8; 64];
pair[..32].copy_from_slice(&root);
pair[32..].copy_from_slice(branch);
root = sha256d(&pair);
}
let mut header = [0_u8; 80];
header[..4].copy_from_slice(&self.version.to_le_bytes());
for (index, word) in self.prevhash_stratum.chunks_exact(4).enumerate() {
for (offset, byte) in word.iter().rev().enumerate() {
header[4 + index * 4 + offset] = *byte;
}
}
header[36..68].copy_from_slice(&root);
header[68..72].copy_from_slice(&ntime.to_le_bytes());
header[72..76].copy_from_slice(&self.nbits.to_le_bytes());
Ok(header)
}
}