Track pool jobs and share replies in connection
next-build / build (push) Canceled after 0s

This commit is contained in:
2026-10-15 01:56:55 -06:00
parent bc38a4a787
commit 90a2fe12d5
6 changed files with 349 additions and 7 deletions
+6 -3
View File
@@ -53,7 +53,10 @@ represent. The pool transport bounds newline frames and uses absolute socket
deadlines. It can negotiate BIP310 extensions, subscribe, and authorize a
worker over a live TCP connection while retaining early notifications in wire
order. It has loopback tests; no live pool acceptance has been observed yet.
Share response tracking and continuous scheduling remain to be implemented.
The pool connection applies difficulty and job messages in stream order,
dispatches work to the BM1366 mining session, and tracks up to 32 verified
share submissions by request ID. It counts accepted and rejected pool replies
separately. Continuous scheduling and live pool acceptance remain unverified.
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
@@ -61,8 +64,8 @@ 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. Hardware job dispatch is library-only so far;
share response tracking and continuous mining remain to be implemented.
confirms a hardware reset. Hardware job dispatch and share reply tracking are
library-only so far; continuous mining remains 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_client;
pub mod stratum_session;
pub mod stratum_submit;
pub mod stratum_v1;
+306
View File
@@ -0,0 +1,306 @@
// SPDX-License-Identifier: MIT
//! One bounded pool connection with ordered jobs and verified share replies.
use crate::miner::{Bm1366Miner, ValidShare};
use crate::stratum_session::{DispatchError, IssuedWork, PoolSession, SessionError};
use crate::stratum_v1::{parse_boolean_response, PoolMessageError};
use crate::stratum_wire::{HandshakeError, PoolHandshake, StratumWire, WireError};
use crate::HardwareBackend;
use serde_json::Value;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::time::Duration;
const MAX_PENDING_SHARES: usize = 32;
#[derive(Debug)]
pub enum ClientError<E> {
Wire(WireError),
Pool(PoolMessageError),
Session(SessionError),
Dispatch(DispatchError<E>),
UnexpectedResponse,
TooManyPending,
RequestIdsExhausted,
}
#[derive(Debug)]
pub enum PoolEvent {
Idle,
Control,
Work(IssuedWork),
ShareAccepted(u64),
ShareRejected(u64),
}
pub struct PoolConnection {
wire: StratumWire,
session: PoolSession,
worker: String,
early: VecDeque<Vec<u8>>,
next_request_id: u64,
pending: Vec<u64>,
accepted: u64,
rejected: u64,
}
impl PoolConnection {
pub fn connect(
address: SocketAddr,
agent: &str,
worker: &str,
password: &str,
io_timeout: Duration,
handshake_timeout: Duration,
) -> Result<Self, HandshakeError> {
let mut wire = StratumWire::connect(address, io_timeout).map_err(HandshakeError::Wire)?;
let handshake = wire.handshake(agent, worker, password, handshake_timeout)?;
Self::from_handshake(wire, handshake, worker)
.map_err(|_| HandshakeError::Pool(PoolMessageError::InvalidField))
}
fn from_handshake(
wire: StratumWire,
handshake: PoolHandshake,
worker: &str,
) -> Result<Self, SessionError> {
let session = PoolSession::new(
handshake.subscription,
handshake.configure.version_mask,
handshake.configure.subscribe_extranonce,
)?;
Ok(Self {
wire,
session,
worker: worker.to_owned(),
early: handshake.early_notifications.into(),
next_request_id: 4,
pending: Vec::new(),
accepted: 0,
rejected: 0,
})
}
pub fn step<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<PoolEvent, ClientError<B::Error>> {
let result = self.step_inner(miner);
if result.is_err() {
self.wire.close();
}
result
}
fn step_inner<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<PoolEvent, ClientError<B::Error>> {
let line = if let Some(line) = self.early.pop_front() {
line
} else {
match self.wire.read_line() {
Ok(line) => line,
Err(WireError::Timeout) if !self.wire.is_closed() => return Ok(PoolEvent::Idle),
Err(error) => return Err(ClientError::Wire(error)),
}
};
let message: Value =
serde_json::from_slice(&line).map_err(|_| ClientError::Pool(PoolMessageError::Json))?;
if let Some(id) = message.get("id").and_then(Value::as_u64) {
if !self.pending.contains(&id) {
return Err(ClientError::UnexpectedResponse);
}
let accepted = parse_boolean_response(&line, id).map_err(ClientError::Pool)?;
self.pending.retain(|pending| *pending != id);
if accepted {
self.accepted = self.accepted.saturating_add(1);
return Ok(PoolEvent::ShareAccepted(id));
}
self.rejected = self.rejected.saturating_add(1);
return Ok(PoolEvent::ShareRejected(id));
}
if !message.get("id").is_none_or(Value::is_null) {
return Err(ClientError::Pool(PoolMessageError::WrongMessage));
}
match message.get("method").and_then(Value::as_str) {
Some("mining.notify") => self
.session
.issue_to_miner(miner, &line)
.map(PoolEvent::Work)
.map_err(ClientError::Dispatch),
Some("mining.set_difficulty" | "mining.set_version_mask" | "mining.set_extranonce") => {
self.session
.control_with_miner(miner, &line)
.map_err(ClientError::Session)?;
Ok(PoolEvent::Control)
}
_ => Err(ClientError::Pool(PoolMessageError::WrongMessage)),
}
}
/// Send only a nonce already verified by the miner and session. A sent
/// request remains pending until its matching boolean pool reply arrives.
pub fn submit_share(&mut self, share: ValidShare) -> Result<u64, ClientError<()>> {
if self.pending.len() >= MAX_PENDING_SHARES {
return Err(ClientError::TooManyPending);
}
let id = self.next_request_id;
let next = id.checked_add(1).ok_or(ClientError::RequestIdsExhausted)?;
let line = self
.session
.submission(share, &self.worker, id)
.map_err(ClientError::Session)?;
self.wire
.send_line(line.as_bytes())
.map_err(ClientError::Wire)?;
self.next_request_id = next;
self.pending.push(id);
Ok(id)
}
pub fn share_counts(&self) -> (u64, u64, usize) {
(self.accepted, self.rejected, self.pending.len())
}
/// Call only after an actual chain reset flushes old hardware reports.
pub fn after_hardware_reset<B: HardwareBackend>(&mut self, miner: &mut Bm1366Miner<'_, B>) {
miner.clear_work();
self.session.after_hardware_reset();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stratum_v1::Subscription;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::thread;
#[derive(Default)]
struct Backend {
sent: Vec<Vec<u8>>,
}
impl HardwareBackend for Backend {
type Error = ();
fn send_frame(&mut self, _chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
self.sent.push(frame.to_vec());
Ok(())
}
fn receive_frame(&mut self, _chain: u8, _frame: &mut [u8]) -> Result<usize, Self::Error> {
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> {
Ok(())
}
}
fn test_link(input: &'static [u8]) -> (PoolConnection, thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.write_all(input).unwrap();
});
let stream = TcpStream::connect(address).unwrap();
let wire = StratumWire::from_stream(stream, Duration::from_secs(2)).unwrap();
let handshake = PoolHandshake {
subscription: Subscription {
extranonce1: vec![1, 2, 3, 4],
extranonce2_size: 4,
},
configure: crate::stratum_v1::ConfigureResult {
version_mask: None,
subscribe_extranonce: false,
},
early_notifications: Vec::new(),
};
(
PoolConnection::from_handshake(wire, handshake, "miner.worker").unwrap(),
server,
)
}
#[test]
fn pool_controls_then_dispatches_one_synthetic_job() {
let (mut link, server) = test_link(
concat!(
"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n",
"{\"id\":null,\"method\":\"mining.notify\",\"params\":[\"job-1\",",
"\"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\",",
"\"616263\",\"78797a\",[],\"20000000\",\"1d00ffff\",\"66554433\",true]}\n"
)
.as_bytes(),
);
let mut backend = Backend::default();
{
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert!(matches!(link.step(&mut miner).unwrap(), PoolEvent::Control));
match link.step(&mut miner).unwrap() {
PoolEvent::Work(work) => assert_eq!(work.work_id, 0),
_ => panic!("expected job"),
}
}
assert_eq!(backend.sent.len(), 1);
server.join().unwrap();
}
#[test]
fn share_replies_match_pending_ids_and_count_accepts_separately() {
let (mut link, server) = test_link(
concat!(
"{\"id\":4,\"result\":true,\"error\":null}\n",
"{\"id\":5,\"result\":false,\"error\":[23,\"stale\"]}\n",
"{\"id\":6,\"result\":true,\"error\":null}\n"
)
.as_bytes(),
);
link.pending.extend([4, 5]);
let mut backend = Backend::default();
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
assert!(matches!(
link.step(&mut miner).unwrap(),
PoolEvent::ShareAccepted(4)
));
assert!(matches!(
link.step(&mut miner).unwrap(),
PoolEvent::ShareRejected(5)
));
assert_eq!(link.share_counts(), (1, 1, 0));
assert!(matches!(
link.step(&mut miner),
Err(ClientError::UnexpectedResponse)
));
server.join().unwrap();
}
#[test]
fn untracked_report_cannot_be_sent_to_pool() {
let (mut link, server) = test_link(b"");
let report = ValidShare {
nonce: 1,
work_id: 0,
rolled_version: 0x2000_0000,
hash_le: [0; 32],
};
assert!(matches!(
link.submit_share(report),
Err(ClientError::Session(SessionError::StaleShare))
));
assert_eq!(link.share_counts(), (0, 0, 0));
server.join().unwrap();
}
}
+1
View File
@@ -30,6 +30,7 @@ pub enum DispatchError<E> {
Miner(MinerError<E>),
}
#[derive(Debug)]
pub struct IssuedWork {
pub work_id: u8,
pub header: [u8; 80],
+13 -4
View File
@@ -74,11 +74,15 @@ impl StratumWire {
})
}
fn close(&mut self) {
pub(crate) fn close(&mut self) {
self.closed = true;
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn is_closed(&self) -> bool {
self.closed
}
fn remaining(deadline: Instant) -> Result<Duration, WireError> {
deadline
.checked_duration_since(Instant::now())
@@ -112,7 +116,9 @@ impl StratumWire {
let remaining = match Self::remaining(deadline) {
Ok(value) => value,
Err(error) => {
self.close();
if !self.buffered.is_empty() {
self.close();
}
return Err(error);
}
};
@@ -128,8 +134,11 @@ impl StratumWire {
}
Ok(length) => self.buffered.extend_from_slice(&chunk[..length]),
Err(error) => {
self.close();
return Err(Self::transport_error(error));
let error = Self::transport_error(error);
if !matches!(error, WireError::Timeout) || !self.buffered.is_empty() {
self.close();
}
return Err(error);
}
}
}
+22
View File
@@ -90,6 +90,28 @@ fn trickled_pool_line_hits_the_absolute_deadline() {
server.join().unwrap();
}
#[test]
fn idle_timeout_keeps_connection_available_for_later_messages() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let (release, wait) = std::sync::mpsc::channel();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
wait.recv().unwrap();
stream
.write_all(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_millis(130)).unwrap();
assert!(matches!(wire.read_line(), Err(WireError::Timeout)));
release.send(()).unwrap();
assert_eq!(
serde_json::from_slice::<Value>(&wire.read_line().unwrap()).unwrap()["method"],
"mining.set_difficulty"
);
server.join().unwrap();
}
#[test]
fn handshake_preserves_early_notifications_and_authorizes_worker() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();