Bound pool share replies and advance mining cycle
next-build / build (push) Canceled after 0s

This commit is contained in:
2026-10-15 02:12:19 -06:00
parent 90a2fe12d5
commit 16b55b58e3
2 changed files with 98 additions and 11 deletions
+4
View File
@@ -57,6 +57,10 @@ 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.
Its cycle helper reads one pool event, polls one ASIC report, and sends a
verified share when present. A share reply unanswered for 30 seconds closes
the connection so a caller can reconnect instead of filling the pending
queue indefinitely. The executable still lacks a board adapter and run loop.
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
+94 -11
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
//! One bounded pool connection with ordered jobs and verified share replies.
use crate::miner::{Bm1366Miner, ValidShare};
use crate::miner::{Bm1366Miner, MinerError, 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};
@@ -9,9 +9,10 @@ use crate::HardwareBackend;
use serde_json::Value;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::time::Duration;
use std::time::{Duration, Instant};
const MAX_PENDING_SHARES: usize = 32;
const SHARE_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug)]
pub enum ClientError<E> {
@@ -22,6 +23,7 @@ pub enum ClientError<E> {
UnexpectedResponse,
TooManyPending,
RequestIdsExhausted,
ShareReplyTimeout,
}
#[derive(Debug)]
@@ -33,17 +35,37 @@ pub enum PoolEvent {
ShareRejected(u64),
}
#[derive(Debug, Eq, PartialEq)]
pub enum ReportEvent {
None,
Stale,
BelowTarget,
Submitted(u64),
}
#[derive(Debug)]
pub enum CycleError<E> {
Pool(ClientError<E>),
Miner(MinerError<E>),
Submit(ClientError<()>),
}
pub struct PoolConnection {
wire: StratumWire,
session: PoolSession,
worker: String,
early: VecDeque<Vec<u8>>,
next_request_id: u64,
pending: Vec<u64>,
pending: Vec<PendingShare>,
accepted: u64,
rejected: u64,
}
struct PendingShare {
id: u64,
sent_at: Instant,
}
impl PoolConnection {
pub fn connect(
address: SocketAddr,
@@ -96,23 +118,39 @@ impl PoolConnection {
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<PoolEvent, ClientError<B::Error>> {
if self
.pending
.first()
.is_some_and(|share| share.sent_at.elapsed() >= SHARE_REPLY_TIMEOUT)
{
return Err(ClientError::ShareReplyTimeout);
}
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(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);
}
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) {
if !self.pending.iter().any(|share| share.id == id) {
return Err(ClientError::UnexpectedResponse);
}
let accepted = parse_boolean_response(&line, id).map_err(ClientError::Pool)?;
self.pending.retain(|pending| *pending != id);
self.pending.retain(|pending| pending.id != id);
if accepted {
self.accepted = self.accepted.saturating_add(1);
return Ok(PoolEvent::ShareAccepted(id));
@@ -155,7 +193,10 @@ impl PoolConnection {
.send_line(line.as_bytes())
.map_err(ClientError::Wire)?;
self.next_request_id = next;
self.pending.push(id);
self.pending.push(PendingShare {
id,
sent_at: Instant::now(),
});
Ok(id)
}
@@ -163,6 +204,25 @@ 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.
pub fn cycle<B: HardwareBackend>(
&mut self,
miner: &mut Bm1366Miner<'_, B>,
) -> Result<(PoolEvent, 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)) => {
ReportEvent::Submitted(self.submit_share(share).map_err(CycleError::Submit)?)
}
Err(MinerError::StaleReport) => ReportEvent::Stale,
Err(MinerError::BelowTarget) => ReportEvent::BelowTarget,
Err(error) => return Err(CycleError::Miner(error)),
};
Ok((pool, report))
}
/// 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();
@@ -248,9 +308,12 @@ mod tests {
{
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),
assert!(matches!(
link.cycle(&mut miner).unwrap(),
(PoolEvent::Control, ReportEvent::None)
));
match link.cycle(&mut miner).unwrap() {
(PoolEvent::Work(work), ReportEvent::None) => assert_eq!(work.work_id, 0),
_ => panic!("expected job"),
}
}
@@ -268,7 +331,10 @@ mod tests {
)
.as_bytes(),
);
link.pending.extend([4, 5]);
link.pending.extend([4, 5].map(|id| PendingShare {
id,
sent_at: Instant::now(),
}));
let mut backend = Backend::default();
let mut miner = Bm1366Miner::new(&mut backend, 0, 0, 0, 100, 80_000).unwrap();
assert!(matches!(
@@ -303,4 +369,21 @@ mod tests {
assert_eq!(link.share_counts(), (0, 0, 0));
server.join().unwrap();
}
#[test]
fn unanswered_share_closes_pool_connection() {
let (mut link, server) = test_link(b"");
link.pending.push(PendingShare {
id: 4,
sent_at: Instant::now() - SHARE_REPLY_TIMEOUT - Duration::from_secs(1),
});
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),
Err(ClientError::ShareReplyTimeout)
));
assert!(link.wire.is_closed());
server.join().unwrap();
}
}