Bind share evidence to Stratum work and improve pool polling
next-build / build (push) Canceled after 0s

This commit is contained in:
2026-10-15 03:07:16 -06:00
parent 492fe68c9e
commit 8fa9e5d9e6
13 changed files with 458 additions and 70 deletions
+11 -9
View File
@@ -109,6 +109,11 @@ pub struct HalClient {
}
impl HalClient {
fn poison(&mut self) {
self.poisoned = true;
let _ = self.stream.shutdown(Shutdown::Both);
}
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
Self::from_stream(stream)
@@ -134,10 +139,9 @@ impl HalClient {
let result = self.exchange_inner(opcode, payload);
if let Err(ref error) = result {
if !matches!(error, HalError::Device(_)) {
self.poisoned = true;
self.poison();
// A backend power lease must expire on disconnect. Reusing a
// desynchronized stream could silently discard an off request.
let _ = self.stream.shutdown(Shutdown::Both);
}
}
result
@@ -183,8 +187,7 @@ impl HalClient {
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
if !self.exchange(opcode, payload)?.is_empty() {
self.poisoned = true;
let _ = self.stream.shutdown(Shutdown::Both);
self.poison();
return Err(HalError::Protocol("unexpected response data"));
}
Ok(())
@@ -357,12 +360,12 @@ impl HardwareBackend for HalClient {
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
let body = self.exchange(RECEIVE_FRAME, &request)?;
if body.len() < 2 {
self.poisoned = true;
self.poison();
return Err(HalError::Protocol("missing receive length"));
}
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
if count > frame.len() || body.len() != count + 2 {
self.poisoned = true;
self.poison();
return Err(HalError::Protocol("invalid received frame size"));
}
frame[..count].copy_from_slice(&body[2..]);
@@ -385,7 +388,7 @@ impl HardwareBackend for HalClient {
let bytes: [u8; 4] = match body.try_into() {
Ok(bytes) => bytes,
Err(_) => {
self.poisoned = true;
self.poison();
return Err(HalError::Protocol("invalid temperature response"));
}
};
@@ -395,8 +398,7 @@ impl HardwareBackend for HalClient {
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
if !enabled && result.is_err() {
self.poisoned = true;
let _ = self.stream.shutdown(Shutdown::Both);
self.poison();
}
result
}
+8
View File
@@ -224,6 +224,14 @@ impl<'a, B: HardwareBackend> Bm1366Miner<'a, B> {
hash_le: check.hash_le,
}))
}
/// Keep thermal supervision active while pool share replies are pending.
pub fn supervise(&mut self) -> Result<(), MinerError<B::Error>> {
if !self.running {
return Err(MinerError::NotRunning);
}
self.check_temperature()
}
}
impl<B: HardwareBackend> Drop for Bm1366Miner<'_, B> {
+76 -40
View File
@@ -13,7 +13,8 @@ use std::time::{Duration, Instant};
const MAX_PENDING_SHARES: usize = 32;
const SHARE_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
const MINER_POOL_POLL_INTERVAL: Duration = Duration::from_millis(500);
const MAX_REPORTS_PER_CYCLE: usize = 256;
const POOL_WRITE_DEADLINE: Duration = Duration::from_millis(100);
#[derive(Debug)]
pub enum ClientError<E> {
@@ -39,10 +40,10 @@ pub enum PoolEvent {
#[derive(Debug, Eq, PartialEq)]
pub enum ReportEvent {
None,
Stale,
BelowTarget,
Submitted(u64),
Backpressured,
}
#[derive(Debug)]
@@ -94,8 +95,7 @@ impl PoolConnection {
handshake.configure.version_mask,
handshake.configure.subscribe_extranonce,
)?;
// Pool I/O must not postpone the next ASIC sensor check indefinitely.
wire.set_timeout(MINER_POOL_POLL_INTERVAL);
wire.cap_write_timeout(POOL_WRITE_DEADLINE);
Ok(Self {
wire,
session,
@@ -136,18 +136,9 @@ impl PoolConnection {
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() => {
if self
.pending
.first()
.is_some_and(|share| share.sent_at.elapsed() >= SHARE_REPLY_TIMEOUT)
{
return Err(ClientError::ShareReplyTimeout);
}
return Ok(PoolEvent::Idle);
}
match self.wire.try_read_line() {
Ok(Some(line)) => line,
Ok(None) => return Ok(PoolEvent::Idle),
Err(error) => return Err(ClientError::Wire(error)),
}
};
@@ -212,31 +203,41 @@ impl PoolConnection {
(self.accepted, self.rejected, self.pending.len())
}
/// Process one pool message or idle interval, then poll the ASIC once.
/// A reported nonce is verified by the miner and session before sending.
/// Process one pool message, then drain a bounded burst of ASIC reports.
/// A reported nonce is verified before sending. The caller must cycle
/// continuously; hardware still requires an independent power watchdog.
pub fn cycle<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<(PoolEvent, ReportEvent), CycleError<B::Error>> {
) -> Result<(PoolEvent, Vec<ReportEvent>), CycleError<B::Error>> {
let pool = self.step(miner).map_err(CycleError::Pool)?;
let report = match miner.poll() {
Ok(None) => ReportEvent::None,
Ok(Some(share)) => {
let id = match self.submit_share(share) {
Ok(id) => id,
Err(error) => {
self.wire.close();
miner.stop().map_err(CycleError::EmergencyShutdown)?;
return Err(CycleError::Submit(error));
}
};
ReportEvent::Submitted(id)
let mut reports = Vec::new();
for _ in 0..MAX_REPORTS_PER_CYCLE {
if self.pending.len() >= MAX_PENDING_SHARES {
miner.supervise().map_err(CycleError::Miner)?;
reports.push(ReportEvent::Backpressured);
break;
}
Err(MinerError::StaleReport) => ReportEvent::Stale,
Err(MinerError::BelowTarget) => ReportEvent::BelowTarget,
Err(error) => return Err(CycleError::Miner(error)),
};
Ok((pool, report))
let event = match miner.poll() {
Ok(None) => break,
Ok(Some(share)) => {
let id = match self.submit_share(share) {
Ok(id) => id,
Err(error) => {
self.wire.close();
miner.stop().map_err(CycleError::EmergencyShutdown)?;
return Err(CycleError::Submit(error));
}
};
ReportEvent::Submitted(id)
}
Err(MinerError::StaleReport) => ReportEvent::Stale,
Err(MinerError::BelowTarget) => ReportEvent::BelowTarget,
Err(error) => return Err(CycleError::Miner(error)),
};
reports.push(event);
}
Ok((pool, reports))
}
/// Call only after an actual chain reset flushes old hardware reports.
@@ -254,12 +255,14 @@ mod tests {
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::rc::Rc;
use std::sync::mpsc;
use std::thread;
#[derive(Default)]
struct Backend {
sent: Vec<Vec<u8>>,
powered: Rc<Cell<bool>>,
reports_remaining: usize,
}
impl HardwareBackend for Backend {
@@ -269,8 +272,15 @@ mod tests {
self.sent.push(frame.to_vec());
Ok(())
}
fn receive_frame(&mut self, _chain: u8, _frame: &mut [u8]) -> Result<usize, Self::Error> {
Ok(0)
fn receive_frame(&mut self, _chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
if self.reports_remaining == 0 {
return Ok(0);
}
self.reports_remaining -= 1;
frame[..11].copy_from_slice(&[
0xaa, 0x55, 0x38, 0xff, 0xad, 0xed, 0, 0x18, 0x04, 0xb3, 0x94,
]);
Ok(11)
}
fn set_chain_reset(&mut self, _chain: u8, _asserted: bool) -> Result<(), Self::Error> {
Ok(())
@@ -290,12 +300,15 @@ mod tests {
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 (ready, received) = mpsc::channel();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.write_all(input).unwrap();
ready.send(()).unwrap();
});
let stream = TcpStream::connect(address).unwrap();
let wire = StratumWire::from_stream(stream, Duration::from_secs(2)).unwrap();
received.recv_timeout(Duration::from_secs(2)).unwrap();
let handshake = PoolHandshake {
subscription: Subscription {
extranonce1: vec![1, 2, 3, 4],
@@ -330,10 +343,12 @@ mod tests {
miner.start().unwrap();
assert!(matches!(
link.cycle(&mut miner).unwrap(),
(PoolEvent::Control, ReportEvent::None)
(PoolEvent::Control, reports) if reports.is_empty()
));
match link.cycle(&mut miner).unwrap() {
(PoolEvent::Work(work), ReportEvent::None) => assert_eq!(work.work_id, 0),
(PoolEvent::Work(work), reports) if reports.is_empty() => {
assert_eq!(work.work_id, 0)
}
_ => panic!("expected job"),
}
}
@@ -419,4 +434,25 @@ mod tests {
assert!(!powered.get());
server.join().unwrap();
}
#[test]
fn idle_pool_does_not_limit_asic_report_burst_to_one() {
let (mut link, server) =
test_link(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n");
let mut backend = Backend {
reports_remaining: MAX_REPORTS_PER_CYCLE + 3,
..Backend::default()
};
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
let (pool, reports) = link.cycle(&mut miner).unwrap();
assert!(matches!(pool, PoolEvent::Control));
assert_eq!(reports.len(), MAX_REPORTS_PER_CYCLE);
assert!(reports
.iter()
.all(|event| matches!(event, ReportEvent::Stale)));
drop(miner);
assert_eq!(backend.reports_remaining, 3);
server.join().unwrap();
}
}
+46 -10
View File
@@ -48,14 +48,21 @@ struct TrackedWork {
base_version: u32,
}
struct NonceSpace {
template: [u8; 80],
next: [u8; 32],
exhausted: bool,
}
const MAX_NONCE_SPACES: usize = 4096;
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,
nonce_spaces: Vec<NonceSpace>,
zero_extranonce_headers: Vec<[u8; 80]>,
tracked: [Option<TrackedWork>; 32],
next_slot: usize,
@@ -76,8 +83,7 @@ impl PoolSession {
subscribe_extranonce,
pending_difficulty: None,
active_difficulty: None,
extranonce2: [0; 32],
extranonce_exhausted: false,
nonce_spaces: Vec::new(),
zero_extranonce_headers: Vec::new(),
tracked: std::array::from_fn(|_| None),
next_slot: 0,
@@ -104,8 +110,7 @@ impl PoolSession {
}
PoolNotification::SetExtranonce(subscription) => {
self.subscription = subscription;
self.extranonce2 = [0; 32];
self.extranonce_exhausted = false;
self.nonce_spaces.clear();
self.zero_extranonce_headers.clear();
self.tracked = std::array::from_fn(|_| None);
Ok(true)
@@ -140,10 +145,30 @@ impl PoolSession {
return Err(SessionError::WorkIdsExhausted);
}
let size = self.subscription.extranonce2_size;
if size != 0 && self.extranonce_exhausted {
let template = if size == 0 {
None
} else {
Some(
job.work
.nonce_zero_header(&vec![0; size], job.work.ntime)
.map_err(SessionError::Work)?,
)
};
let space_index = template.and_then(|header| {
self.nonce_spaces
.iter()
.position(|space| space.template == header)
});
if size != 0 && space_index.is_none() && self.nonce_spaces.len() == MAX_NONCE_SPACES {
return Err(SessionError::ExtranonceExhausted);
}
let extranonce2 = self.extranonce2[..size].to_vec();
let extranonce2 = match space_index {
Some(index) if self.nonce_spaces[index].exhausted => {
return Err(SessionError::ExtranonceExhausted)
}
Some(index) => self.nonce_spaces[index].next[..size].to_vec(),
None => vec![0; size],
};
let header = job
.work
.nonce_zero_header(&extranonce2, job.work.ntime)
@@ -170,8 +195,19 @@ impl PoolSession {
if size == 0 {
self.zero_extranonce_headers.push(header);
} else {
let space = match space_index {
Some(index) => &mut self.nonce_spaces[index],
None => {
self.nonce_spaces.push(NonceSpace {
template: template.expect("nonzero extranonce has a template"),
next: [0; 32],
exhausted: false,
});
self.nonce_spaces.last_mut().expect("just pushed")
}
};
let mut carry = true;
for byte in self.extranonce2[..size].iter_mut().rev() {
for byte in space.next[..size].iter_mut().rev() {
let (new, overflow) = byte.overflowing_add(u8::from(carry));
*byte = new;
carry = overflow;
@@ -179,7 +215,7 @@ impl PoolSession {
break;
}
}
self.extranonce_exhausted = carry;
space.exhausted = carry;
}
Ok(IssuedWork {
work_id: (slot as u8) << 3,
+86 -6
View File
@@ -13,6 +13,8 @@ use std::time::{Duration, Instant};
const MAX_EARLY_NOTIFICATIONS: usize = 32;
const MAX_EARLY_NOTIFICATION_BYTES: usize = 262_144;
const READ_SLICE: Duration = Duration::from_millis(1);
const MAX_PARTIAL_AGE: Duration = Duration::from_secs(2);
#[derive(Debug)]
pub enum WireError {
@@ -42,14 +44,13 @@ pub struct PoolHandshake {
pub struct StratumWire {
stream: TcpStream,
buffered: Vec<u8>,
partial_started: Option<Instant>,
timeout: Duration,
write_timeout: Duration,
closed: bool,
}
impl StratumWire {
pub(crate) fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
pub fn connect(address: SocketAddr, timeout: Duration) -> Result<Self, WireError> {
if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() {
return Err(WireError::InvalidRequest);
@@ -59,7 +60,9 @@ impl StratumWire {
Ok(Self {
stream,
buffered: Vec::new(),
partial_started: None,
timeout,
write_timeout: timeout,
closed: false,
})
}
@@ -72,7 +75,9 @@ impl StratumWire {
Ok(Self {
stream,
buffered: Vec::new(),
partial_started: None,
timeout,
write_timeout: timeout,
closed: false,
})
}
@@ -86,6 +91,10 @@ impl StratumWire {
self.closed
}
pub(crate) fn cap_write_timeout(&mut self, limit: Duration) {
self.write_timeout = self.write_timeout.min(limit);
}
fn remaining(deadline: Instant) -> Result<Duration, WireError> {
deadline
.checked_duration_since(Instant::now())
@@ -110,7 +119,9 @@ impl StratumWire {
self.close();
return Err(WireError::LineTooLong);
}
return Ok(self.buffered.drain(..=end).collect());
let line = self.buffered.drain(..=end).collect();
self.partial_started = (!self.buffered.is_empty()).then(Instant::now);
return Ok(line);
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
self.close();
@@ -135,7 +146,12 @@ impl StratumWire {
self.close();
return Err(WireError::Eof);
}
Ok(length) => self.buffered.extend_from_slice(&chunk[..length]),
Ok(length) => {
if self.buffered.is_empty() {
self.partial_started = Some(Instant::now());
}
self.buffered.extend_from_slice(&chunk[..length]);
}
Err(error) => {
let error = Self::transport_error(error);
if !matches!(error, WireError::Timeout) || !self.buffered.is_empty() {
@@ -151,6 +167,70 @@ impl StratumWire {
self.read_line_before(Instant::now() + self.timeout)
}
/// Check one socket slice without coupling ASIC polling to pool silence.
/// An unfinished line has its own absolute deadline across calls.
pub fn try_read_line(&mut self) -> Result<Option<Vec<u8>>, WireError> {
if self.closed {
return Err(WireError::Closed);
}
if let Some(line) = self.try_read_line_buffered()? {
return Ok(Some(line));
}
if self
.partial_started
.is_some_and(|start| start.elapsed() >= MAX_PARTIAL_AGE)
{
self.close();
return Err(WireError::Timeout);
}
self.stream
.set_read_timeout(Some(READ_SLICE))
.map_err(WireError::Io)?;
let mut chunk = [0_u8; 4096];
match self.stream.read(&mut chunk) {
Ok(0) => {
self.close();
Err(WireError::Eof)
}
Ok(length) => {
if self.buffered.is_empty() {
self.partial_started = Some(Instant::now());
}
self.buffered.extend_from_slice(&chunk[..length]);
self.try_read_line_buffered()
}
Err(error)
if matches!(
error.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) =>
{
Ok(None)
}
Err(error) => {
self.close();
Err(WireError::Io(error))
}
}
}
fn try_read_line_buffered(&mut self) -> Result<Option<Vec<u8>>, WireError> {
if let Some(end) = self.buffered.iter().position(|byte| *byte == b'\n') {
if end + 1 > MAX_POOL_LINE_BYTES {
self.close();
return Err(WireError::LineTooLong);
}
let line = self.buffered.drain(..=end).collect();
self.partial_started = (!self.buffered.is_empty()).then(Instant::now);
return Ok(Some(line));
}
if self.buffered.len() >= MAX_POOL_LINE_BYTES {
self.close();
return Err(WireError::LineTooLong);
}
Ok(None)
}
fn send_line_before(&mut self, line: &[u8], deadline: Instant) -> Result<(), WireError> {
if self.closed {
return Err(WireError::Closed);
@@ -191,7 +271,7 @@ impl StratumWire {
}
pub fn send_line(&mut self, line: &[u8]) -> Result<(), WireError> {
self.send_line_before(line, Instant::now() + self.timeout)
self.send_line_before(line, Instant::now() + self.write_timeout)
}
fn read_reply(