Track Stratum jobs across ASIC work IDs
next-build / build (push) Canceled after 0s

This commit is contained in:
2026-10-15 01:16:19 -06:00
parent 5cd77eb5de
commit ece32ef55f
5 changed files with 568 additions and 5 deletions
+10 -5
View File
@@ -18,7 +18,7 @@ minimal API.
## Status
This is the initial interface and release tooling. It does not mine yet. A
This is an early mining core and release tooling, not a complete daemon. A
target in the matrix is an obligation to implement and validate, not a claim
of support. All 64 theoretical same-vendor controller/chip pairings are in
scope: 52 Bitmain and 12 WhatsMiner. For pairings a stock image rejects, the
@@ -51,10 +51,15 @@ For negotiated BIP310 version rolling, it includes the sixth version-bits
parameter and rejects ASIC versions that the current pool mask cannot
represent. Pool connections, response tracking, and continuous scheduling
remain to be implemented.
The Stratum V1 decoder now bounds and validates `mining.subscribe` responses
and nine-field Bitcoin `mining.notify` jobs before handing them to the header
builder. It uses the MIT-compatible `serde_json` parser. A live pool client,
target conversion, and job-to-share scheduling are still pending.
The Stratum V1 decoder bounds and validates `mining.subscribe` responses,
nine-field Bitcoin `mining.notify` jobs, difficulty and extranonce changes,
and negotiated BIP310 version-mask updates. Exact decimal difficulty values
become 256-bit pool targets without floating point rounding. Pool job
bookkeeping keeps earlier work tied to its original target and extranonce,
invalidates old work on `clean_jobs`, and rechecks a reported share before
formatting it for submission. It does not reuse ASIC work IDs until the caller
confirms a hardware reset. A live pool connection, hardware job dispatch,
share-response tracking, and continuous mining remain to be implemented.
The exact Rust dependency sources are under `vendor/` with Cargo checksums,
so SDK board builds can compile offline. Dependencies retain the license terms
in their vendored manifests and license files.
+1
View File
@@ -8,6 +8,7 @@ pub mod difficulty;
pub mod hal_wire;
pub mod miner;
pub mod pow;
pub mod stratum_session;
pub mod stratum_submit;
pub mod stratum_v1;
pub mod stratum_work;
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: MIT
//! Bounded pool-job bookkeeping for one BM1366 chain and one Stratum V1 session.
use crate::difficulty::PoolDifficulty;
use crate::miner::{Bm1366Miner, MinerError, ValidShare};
use crate::pow::{sha256d, VersionMask};
use crate::stratum_submit::{format_submission, Submission, SubmitError};
use crate::stratum_v1::{
parse_control_notification, parse_notify, PoolMessageError, PoolNotification, Subscription,
};
use crate::stratum_work::JobError;
use crate::HardwareBackend;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionError {
InvalidSubscription,
Pool(PoolMessageError),
Work(JobError),
MissingDifficulty,
ExtranonceExhausted,
WorkIdsExhausted,
StaleShare,
UnverifiedShare,
Submit(SubmitError),
}
#[derive(Debug, Eq, PartialEq)]
pub enum DispatchError<E> {
Session(SessionError),
Miner(MinerError<E>),
}
pub struct IssuedWork {
pub work_id: u8,
pub header: [u8; 80],
pub target_le: [u8; 32],
/// The hardware miner must forget prior work before submitting this job.
pub clean_jobs: bool,
}
struct TrackedWork {
job_id: String,
header: [u8; 80],
target_le: [u8; 32],
extranonce2: Vec<u8>,
ntime: u32,
base_version: u32,
}
pub struct PoolSession {
subscription: Subscription,
version_mask: Option<VersionMask>,
subscribe_extranonce: bool,
pending_difficulty: Option<PoolDifficulty>,
active_difficulty: Option<PoolDifficulty>,
extranonce2: [u8; 32],
extranonce_exhausted: bool,
tracked: [Option<TrackedWork>; 32],
next_slot: usize,
}
impl PoolSession {
pub fn new(
subscription: Subscription,
version_mask: Option<VersionMask>,
subscribe_extranonce: bool,
) -> Result<Self, SessionError> {
if subscription.extranonce1.len() > 32 || subscription.extranonce2_size > 32 {
return Err(SessionError::InvalidSubscription);
}
Ok(Self {
subscription,
version_mask,
subscribe_extranonce,
pending_difficulty: None,
active_difficulty: None,
extranonce2: [0; 32],
extranonce_exhausted: false,
tracked: std::array::from_fn(|_| None),
next_slot: 0,
})
}
/// Apply a control message in wire order. A true result means the caller
/// must call the hardware miner's `clear_work` before accepting reports.
pub fn control(&mut self, line: &[u8]) -> Result<bool, SessionError> {
let control = parse_control_notification(
line,
self.version_mask.is_some(),
self.subscribe_extranonce,
)
.map_err(SessionError::Pool)?;
match control {
PoolNotification::SetDifficulty(difficulty) => {
self.pending_difficulty = Some(difficulty);
Ok(false)
}
PoolNotification::SetVersionMask(mask) => {
self.version_mask = Some(mask);
Ok(false)
}
PoolNotification::SetExtranonce(subscription) => {
self.subscription = subscription;
self.extranonce2 = [0; 32];
self.extranonce_exhausted = false;
self.tracked = std::array::from_fn(|_| None);
Ok(true)
}
}
}
/// Apply a pool control message and invalidate the hardware miner's work
/// when an extranonce change makes earlier jobs stale.
pub fn control_with_miner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
line: &[u8],
) -> Result<(), SessionError> {
if self.control(line)? {
miner.clear_work();
}
Ok(())
}
/// Allocate one unique extranonce and ASIC work ID for a pool job. The
/// caller must pass this header, target, and ID to `Bm1366Miner::submit`.
/// On `clean_jobs`, clear the hardware miner's work first. Work IDs are
/// never reused on the same chain without an explicit hardware reset.
pub fn issue_notify(&mut self, line: &[u8]) -> Result<IssuedWork, SessionError> {
let job = parse_notify(line, &self.subscription).map_err(SessionError::Pool)?;
let difficulty = self
.pending_difficulty
.or(self.active_difficulty)
.ok_or(SessionError::MissingDifficulty)?;
if self.next_slot == self.tracked.len() {
return Err(SessionError::WorkIdsExhausted);
}
if self.extranonce_exhausted {
return Err(SessionError::ExtranonceExhausted);
}
let size = self.subscription.extranonce2_size;
let extranonce2 = self.extranonce2[..size].to_vec();
let header = job
.work
.nonce_zero_header(&extranonce2, job.work.ntime)
.map_err(SessionError::Work)?;
let target_le = difficulty.target_le();
if job.clean_jobs {
self.tracked = std::array::from_fn(|_| None);
}
self.active_difficulty = Some(difficulty);
self.pending_difficulty = None;
let slot = self.next_slot;
self.next_slot += 1;
self.tracked[slot] = Some(TrackedWork {
job_id: job.id,
header,
target_le,
extranonce2,
ntime: job.work.ntime,
base_version: job.work.version,
});
if size == 0 {
self.extranonce_exhausted = true;
} else {
let mut carry = true;
for byte in self.extranonce2[..size].iter_mut().rev() {
let (new, overflow) = byte.overflowing_add(u8::from(carry));
*byte = new;
carry = overflow;
if !carry {
break;
}
}
self.extranonce_exhausted = carry;
}
Ok(IssuedWork {
work_id: (slot as u8) << 3,
header,
target_le,
clean_jobs: job.clean_jobs,
})
}
/// Preserve pool-message order while dispatching one job to the hardware
/// miner. A failed dispatch consumes its ASIC work ID to avoid ambiguity
/// with any frame that may have reached the device before the error.
pub fn issue_to_miner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
line: &[u8],
) -> Result<IssuedWork, DispatchError<B::Error>> {
let issued = self.issue_notify(line).map_err(DispatchError::Session)?;
if issued.clean_jobs {
miner.clear_work();
}
if let Err(error) = miner.submit(issued.header, issued.target_le, issued.work_id) {
self.tracked[usize::from(issued.work_id >> 3)] = None;
return Err(DispatchError::Miner(error));
}
Ok(issued)
}
/// Recheck the hardware-reported share and format its pool submission.
/// This method verifies one reported nonce; it never searches for one.
pub fn submission(
&self,
share: ValidShare,
worker: &str,
request_id: u64,
) -> Result<String, SessionError> {
let tracked = self
.tracked
.get(usize::from(share.work_id >> 3))
.and_then(Option::as_ref)
.ok_or(SessionError::StaleShare)?;
if share.work_id & 7 != 0 {
return Err(SessionError::StaleShare);
}
let mut header = tracked.header;
header[..4].copy_from_slice(&share.rolled_version.to_le_bytes());
header[76..80].copy_from_slice(&share.nonce.to_le_bytes());
let hash_le = sha256d(&header);
if hash_le != share.hash_le
|| hash_le
.iter()
.rev()
.cmp(tracked.target_le.iter().rev())
.is_gt()
{
return Err(SessionError::UnverifiedShare);
}
format_submission(&Submission {
request_id,
worker,
job_id: &tracked.job_id,
extranonce2: &tracked.extranonce2,
ntime: tracked.ntime,
nonce: share.nonce,
base_version: tracked.base_version,
rolled_version: share.rolled_version,
version_mask: self.version_mask,
})
.map_err(SessionError::Submit)
}
/// Call only after the chain has actually reset and prior reports cannot
/// arrive. A pool `clean_jobs` notification alone is insufficient.
pub fn after_hardware_reset(&mut self) {
self.tracked = std::array::from_fn(|_| None);
self.next_slot = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bytes(text: &str) -> Vec<u8> {
text.as_bytes()
.chunks_exact(2)
.map(|part| u8::from_str_radix(std::str::from_utf8(part).unwrap(), 16).unwrap())
.collect()
}
#[test]
fn captured_report_is_rechecked_and_formatted_for_pool() {
let header: [u8; 80] = bytes(concat!(
"00000020fc3ab8d43021f45eb662389d0f791f657dbf75a5cb93670b57b6c22503",
"b4213a43ae1052ebd44443068fe178e2c61ca4994846fd133addb04aab2b382c5",
"b4c74c1012e6a8f06021700000000"
))
.try_into()
.unwrap();
let hash_le: [u8; 32] =
bytes("4b5e00850cf9de9809f822f8858eda39e49996d9d40f634f1043290000000000")
.try_into()
.unwrap();
let mut target_le = [0_u8; 32];
target_le[26..28].fill(0xff);
let mut session = PoolSession::new(
Subscription {
extranonce1: vec![],
extranonce2_size: 4,
},
VersionMask::new(0x1fff_e000),
false,
)
.unwrap();
session.tracked[3] = Some(TrackedWork {
job_id: "captured-job".into(),
header,
target_le,
extranonce2: vec![0, 0, 0, 1],
ntime: u32::from_le_bytes(header[68..72].try_into().unwrap()),
base_version: 0x2000_0000,
});
let share = ValidShare {
nonce: 0xedad_ff38,
work_id: 0x18,
rolled_version: 0x2096_6000,
hash_le,
};
let submit = session.submission(share, "miner.worker", 7).unwrap();
assert!(submit.contains("\"mining.submit\""));
assert!(submit.contains("\"captured-job\""));
assert!(submit.contains("\"edadff38\",\"00966000\""));
assert_eq!(
session.submission(
ValidShare {
hash_le: [0; 32],
..share
},
"miner.worker",
8
),
Err(SessionError::UnverifiedShare)
);
session.version_mask = VersionMask::new(0x0000_2000);
assert_eq!(
session.submission(share, "miner.worker", 8),
Err(SessionError::Submit(SubmitError::UnrepresentableVersion))
);
}
}
+31
View File
@@ -3,6 +3,7 @@ use alkane_os::difficulty::PoolDifficulty;
use alkane_os::miner::Bm1366Miner;
use alkane_os::pow::verify_sha256_report;
use alkane_os::pow::VersionMask;
use alkane_os::stratum_session::PoolSession;
use alkane_os::stratum_submit::{format_submission, Submission};
use alkane_os::stratum_v1::{parse_control_notification, parse_notify, Subscription};
use alkane_os::stratum_work::Sha256Job;
@@ -156,6 +157,36 @@ fn bench_difficulty_target() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_job_issue() {
let line = serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
"job-1", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a", [], "20000000", "1d00ffff", "66554433", true
]
})
.to_string();
let mut session = PoolSession::new(
Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
None,
false,
)
.unwrap();
session
.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
measure("stratum_job_issue", 5_000, || {
session.after_hardware_reset();
black_box(session.issue_notify(black_box(line.as_bytes())).unwrap());
});
}
struct BenchBackend;
impl HardwareBackend for BenchBackend {
+201
View File
@@ -0,0 +1,201 @@
// SPDX-License-Identifier: MIT
use alkane_os::miner::{Bm1366Miner, MinerError, ValidShare};
use alkane_os::pow::VersionMask;
use alkane_os::stratum_session::{DispatchError, PoolSession, SessionError};
use alkane_os::stratum_v1::Subscription;
use alkane_os::HardwareBackend;
fn session() -> PoolSession {
PoolSession::new(
Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
Some(VersionMask::new(0x1fff_e000).unwrap()),
true,
)
.unwrap()
}
fn notify(id: &str, clean: bool) -> String {
serde_json::json!({
"id": null,
"method": "mining.notify",
"params": [
id,
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"616263", "78797a", [], "20000000", "1d00ffff", "66554433", clean
]
})
.to_string()
}
#[test]
fn difficulty_changes_on_next_job_and_old_work_keeps_its_target() {
let mut pool = session();
assert_eq!(
pool.issue_notify(notify("early", true).as_bytes()).err(),
Some(SessionError::MissingDifficulty)
);
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
let first = pool.issue_notify(notify("first", true).as_bytes()).unwrap();
assert!(first.clean_jobs);
assert_eq!(first.work_id, 0);
assert_eq!(&first.target_le[26..28], &[0xff, 0xff]);
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[2]}"#)
.unwrap();
let second = pool
.issue_notify(notify("second", false).as_bytes())
.unwrap();
assert!(!second.clean_jobs);
assert_eq!(second.work_id, 8);
assert_eq!(&second.target_le[26..28], &[0xff, 0x7f]);
assert_ne!(first.header, second.header);
assert!(pool
.control(br#"{"id":null,"method":"mining.set_version_mask","params":["00006000"]}"#)
.is_ok());
let clean = pool.issue_notify(notify("third", true).as_bytes()).unwrap();
assert!(clean.clean_jobs);
assert_eq!(clean.work_id, 16);
let old = ValidShare {
nonce: 0xedad_ff38,
work_id: first.work_id,
rolled_version: 0x2000_0000,
hash_le: [0; 32],
};
assert_eq!(
pool.submission(old, "worker", 10),
Err(SessionError::StaleShare)
);
}
#[test]
fn extranonce_change_invalidates_jobs_without_reusing_asic_ids() {
let mut pool = session();
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
let old = pool.issue_notify(notify("old", true).as_bytes()).unwrap();
assert!(pool
.control(br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#)
.unwrap());
let new = pool.issue_notify(notify("new", false).as_bytes()).unwrap();
assert_eq!(new.work_id, 8);
assert_ne!(old.header, new.header);
for index in 2..32 {
let work = pool.issue_notify(notify("more", false).as_bytes()).unwrap();
assert_eq!(work.work_id, (index as u8) << 3);
}
assert_eq!(
pool.issue_notify(notify("exhausted", false).as_bytes())
.err(),
Some(SessionError::WorkIdsExhausted)
);
pool.after_hardware_reset();
assert_eq!(
pool.issue_notify(notify("after-reset", false).as_bytes())
.unwrap()
.work_id,
0
);
}
#[test]
fn zero_length_extranonce_can_be_issued_once() {
let mut pool = PoolSession::new(
Subscription {
extranonce1: vec![1],
extranonce2_size: 0,
},
None,
false,
)
.unwrap();
pool.control(br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#)
.unwrap();
pool.issue_notify(notify("one", true).as_bytes()).unwrap();
assert_eq!(
pool.issue_notify(notify("two", false).as_bytes()).err(),
Some(SessionError::ExtranonceExhausted)
);
}
struct FakeBackend {
powered: bool,
sent: usize,
report: Option<[u8; 11]>,
}
impl HardwareBackend for FakeBackend {
type Error = &'static str;
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
assert!(self.powered);
assert_eq!(&frame[..4], &[0x55, 0xaa, 0x21, 0x54]);
self.sent += 1;
Ok(())
}
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
match self.report.take() {
Some(report) => {
frame[..11].copy_from_slice(&report);
Ok(11)
}
None => Ok(0),
}
}
fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> {
Ok(())
}
fn set_fan_target(&mut self, _fan: u8, _percent: u8) -> Result<(), Self::Error> {
Ok(())
}
fn read_temperature_mc(&mut self, _sensor: u8) -> Result<i32, Self::Error> {
Ok(50_000)
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.powered = enabled;
Ok(())
}
}
#[test]
fn pool_job_dispatch_and_extranonce_invalidation_reach_the_miner() {
let mut backend = FakeBackend {
powered: false,
sent: 0,
report: Some([
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
]),
};
{
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
let mut pool = session();
pool.control_with_miner(
&mut miner,
br#"{"id":null,"method":"mining.set_difficulty","params":[1]}"#,
)
.unwrap();
for index in 0..4 {
let work = pool
.issue_to_miner(&mut miner, notify("job", index == 0).as_bytes())
.unwrap();
assert_eq!(work.work_id, (index as u8) << 3);
}
pool.control_with_miner(
&mut miner,
br#"{"id":null,"method":"mining.set_extranonce","params":["aabbccdd",4]}"#,
)
.unwrap();
assert_eq!(miner.poll(), Err(MinerError::StaleReport));
miner.stop().unwrap();
assert_eq!(
pool.issue_to_miner(&mut miner, notify("stopped", false).as_bytes())
.err(),
Some(DispatchError::Miner(MinerError::NotRunning))
);
}
assert!(!backend.powered);
assert_eq!(backend.sent, 4);
}