Fail closed on pool and HAL faults and bind release evidence to CI run
main-release-gate / verify-and-release (push) Canceled after 0s

This commit is contained in:
2026-10-15 02:33:24 -06:00
parent 11adff8278
commit 4cea798651
12 changed files with 306 additions and 23 deletions
+11 -1
View File
@@ -4,6 +4,7 @@
use crate::HardwareBackend;
use std::fmt;
use std::io::{self, Read, Write};
use std::net::Shutdown;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixStream;
@@ -134,6 +135,9 @@ impl HalClient {
if let Err(ref error) = result {
if !matches!(error, HalError::Device(_)) {
self.poisoned = true;
// 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
@@ -180,6 +184,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);
return Err(HalError::Protocol("unexpected response data"));
}
Ok(())
@@ -388,6 +393,11 @@ impl HardwareBackend for HalClient {
}
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)])
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);
}
result
}
}
+36 -3
View File
@@ -13,6 +13,7 @@ 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);
#[derive(Debug)]
pub enum ClientError<E> {
@@ -24,6 +25,7 @@ pub enum ClientError<E> {
TooManyPending,
RequestIdsExhausted,
ShareReplyTimeout,
EmergencyShutdown(E),
}
#[derive(Debug)]
@@ -48,6 +50,7 @@ pub enum CycleError<E> {
Pool(ClientError<E>),
Miner(MinerError<E>),
Submit(ClientError<()>),
EmergencyShutdown(E),
}
pub struct PoolConnection {
@@ -82,7 +85,7 @@ impl PoolConnection {
}
fn from_handshake(
wire: StratumWire,
mut wire: StratumWire,
handshake: PoolHandshake,
worker: &str,
) -> Result<Self, SessionError> {
@@ -91,6 +94,8 @@ 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);
Ok(Self {
wire,
session,
@@ -110,6 +115,9 @@ impl PoolConnection {
let result = self.step_inner(miner);
if result.is_err() {
self.wire.close();
if let Err(error) = miner.stop() {
return Err(ClientError::EmergencyShutdown(error));
}
}
result
}
@@ -214,7 +222,15 @@ impl PoolConnection {
let report = match miner.poll() {
Ok(None) => ReportEvent::None,
Ok(Some(share)) => {
ReportEvent::Submitted(self.submit_share(share).map_err(CycleError::Submit)?)
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,
@@ -234,13 +250,16 @@ impl PoolConnection {
mod tests {
use super::*;
use crate::stratum_v1::Subscription;
use std::cell::Cell;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::rc::Rc;
use std::thread;
#[derive(Default)]
struct Backend {
sent: Vec<Vec<u8>>,
powered: Rc<Cell<bool>>,
}
impl HardwareBackend for Backend {
@@ -262,7 +281,8 @@ mod tests {
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> {
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
self.powered.set(enabled);
Ok(())
}
}
@@ -386,4 +406,17 @@ mod tests {
assert!(link.wire.is_closed());
server.join().unwrap();
}
#[test]
fn malformed_pool_message_stops_miner_before_returning() {
let (mut link, server) = test_link(b"{}\n");
let mut backend = Backend::default();
let powered = Rc::clone(&backend.powered);
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
miner.start().unwrap();
assert!(powered.get());
assert!(matches!(link.cycle(&mut miner), Err(CycleError::Pool(_))));
assert!(!powered.get());
server.join().unwrap();
}
}
+10 -3
View File
@@ -56,6 +56,7 @@ pub struct PoolSession {
active_difficulty: Option<PoolDifficulty>,
extranonce2: [u8; 32],
extranonce_exhausted: bool,
zero_extranonce_headers: Vec<[u8; 80]>,
tracked: [Option<TrackedWork>; 32],
next_slot: usize,
}
@@ -77,6 +78,7 @@ impl PoolSession {
active_difficulty: None,
extranonce2: [0; 32],
extranonce_exhausted: false,
zero_extranonce_headers: Vec::new(),
tracked: std::array::from_fn(|_| None),
next_slot: 0,
})
@@ -104,6 +106,7 @@ impl PoolSession {
self.subscription = subscription;
self.extranonce2 = [0; 32];
self.extranonce_exhausted = false;
self.zero_extranonce_headers.clear();
self.tracked = std::array::from_fn(|_| None);
Ok(true)
}
@@ -136,15 +139,18 @@ impl PoolSession {
if self.next_slot == self.tracked.len() {
return Err(SessionError::WorkIdsExhausted);
}
if self.extranonce_exhausted {
let size = self.subscription.extranonce2_size;
if size != 0 && 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)?;
if size == 0 && self.zero_extranonce_headers.contains(&header) {
return Err(SessionError::ExtranonceExhausted);
}
let target_le = difficulty.target_le();
if job.clean_jobs {
self.tracked = std::array::from_fn(|_| None);
@@ -162,7 +168,7 @@ impl PoolSession {
base_version: job.work.version,
});
if size == 0 {
self.extranonce_exhausted = true;
self.zero_extranonce_headers.push(header);
} else {
let mut carry = true;
for byte in self.extranonce2[..size].iter_mut().rev() {
@@ -250,6 +256,7 @@ impl PoolSession {
pub fn after_hardware_reset(&mut self) {
self.tracked = std::array::from_fn(|_| None);
self.next_slot = 0;
self.zero_extranonce_headers.clear();
}
}
+5 -7
View File
@@ -184,14 +184,12 @@ pub fn parse_boolean_response(line: &[u8], request_id: u64) -> Result<bool, Pool
if message.get("id").and_then(Value::as_u64) != Some(request_id) {
return Err(PoolMessageError::WrongMessage);
}
let accepted = message
.get("result")
.and_then(Value::as_bool)
.ok_or(PoolMessageError::InvalidField)?;
if accepted && !message.get("error").is_none_or(Value::is_null) {
return Err(PoolMessageError::InvalidField);
match message.get("result") {
Some(Value::Bool(true)) if message.get("error").is_none_or(Value::is_null) => Ok(true),
Some(Value::Bool(false)) => Ok(false),
Some(Value::Null) if !message.get("error").is_none_or(Value::is_null) => Ok(false),
_ => Err(PoolMessageError::InvalidField),
}
Ok(accepted)
}
/// Decode pool control notifications. The caller applies them in stream order:
+3
View File
@@ -47,6 +47,9 @@ pub struct StratumWire {
}
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);