// SPDX-License-Identifier: MIT //! Bounded newline-framed TCP transport for Bitcoin Stratum V1 pools. use crate::stratum_v1::MAX_POOL_LINE_BYTES; use crate::stratum_v1::{ parse_boolean_response, parse_configure_result, parse_subscription, ConfigureResult, PoolMessageError, Subscription, }; use serde_json::json; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpStream}; 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 { InvalidRequest, LineTooLong, Timeout, Eof, Closed, Io(io::Error), } #[derive(Debug)] pub enum HandshakeError { Wire(WireError), Pool(PoolMessageError), Rejected, TooManyNotifications, } pub struct PoolHandshake { pub subscription: Subscription, pub configure: ConfigureResult, /// Notifications received during negotiation, in original wire order. pub early_notifications: Vec>, } pub struct StratumWire { stream: TcpStream, buffered: Vec, partial_started: Option, timeout: Duration, write_timeout: Duration, closed: bool, } impl StratumWire { pub fn connect(address: SocketAddr, timeout: Duration) -> Result { if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() { return Err(WireError::InvalidRequest); } let stream = TcpStream::connect_timeout(&address, timeout).map_err(WireError::Io)?; stream.set_nodelay(true).map_err(WireError::Io)?; Ok(Self { stream, buffered: Vec::new(), partial_started: None, timeout, write_timeout: timeout, closed: false, }) } pub fn from_stream(stream: TcpStream, timeout: Duration) -> Result { if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() { return Err(WireError::InvalidRequest); } stream.set_nodelay(true).map_err(WireError::Io)?; Ok(Self { stream, buffered: Vec::new(), partial_started: None, timeout, write_timeout: timeout, closed: false, }) } pub(crate) fn close(&mut self) { self.closed = true; let _ = self.stream.shutdown(Shutdown::Both); } pub fn is_closed(&self) -> bool { 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 { deadline .checked_duration_since(Instant::now()) .filter(|remaining| !remaining.is_zero()) .ok_or(WireError::Timeout) } fn transport_error(error: io::Error) -> WireError { match error.kind() { io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock => WireError::Timeout, _ => WireError::Io(error), } } fn read_line_before(&mut self, deadline: Instant) -> Result, WireError> { if self.closed { return Err(WireError::Closed); } loop { 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 = if self.buffered.is_empty() { None } else { self.partial_started.or_else(|| Some(Instant::now())) }; return Ok(line); } if self.buffered.len() >= MAX_POOL_LINE_BYTES { self.close(); return Err(WireError::LineTooLong); } let remaining = match Self::remaining(deadline) { Ok(value) => value, Err(error) => { if !self.buffered.is_empty() { self.close(); } return Err(error); } }; if let Err(error) = self.stream.set_read_timeout(Some(remaining)) { self.close(); return Err(WireError::Io(error)); } let mut chunk = [0_u8; 4096]; match self.stream.read(&mut chunk) { Ok(0) => { self.close(); return Err(WireError::Eof); } 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() { self.close(); } return Err(error); } } } } pub fn read_line(&mut self) -> Result, WireError> { 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>, 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>, 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 = if self.buffered.is_empty() { None } else { self.partial_started.or_else(|| Some(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); } if line.is_empty() || line.len() > MAX_POOL_LINE_BYTES || line.last() != Some(&b'\n') || line[..line.len() - 1].contains(&b'\n') { return Err(WireError::InvalidRequest); } let mut sent = 0; while sent < line.len() { let remaining = match Self::remaining(deadline) { Ok(value) => value, Err(error) => { self.close(); return Err(error); } }; if let Err(error) = self.stream.set_write_timeout(Some(remaining)) { self.close(); return Err(WireError::Io(error)); } match self.stream.write(&line[sent..]) { Ok(0) => { self.close(); return Err(WireError::Eof); } Ok(length) => sent += length, Err(error) => { self.close(); return Err(Self::transport_error(error)); } } } Ok(()) } pub fn send_line(&mut self, line: &[u8]) -> Result<(), WireError> { self.send_line_before(line, Instant::now() + self.write_timeout) } fn read_reply( &mut self, request_id: u64, deadline: Instant, early: &mut Vec>, early_bytes: &mut usize, ) -> Result, HandshakeError> { loop { let line = self .read_line_before(deadline) .map_err(HandshakeError::Wire)?; let message: serde_json::Value = serde_json::from_slice(&line) .map_err(|_| HandshakeError::Pool(PoolMessageError::Json))?; if message.get("id").and_then(serde_json::Value::as_u64) == Some(request_id) { return Ok(line); } if !message.get("id").is_none_or(serde_json::Value::is_null) || !matches!( message.get("method").and_then(serde_json::Value::as_str), Some( "mining.set_difficulty" | "mining.set_version_mask" | "mining.set_extranonce" | "mining.notify" ) ) { return Err(HandshakeError::Pool(PoolMessageError::WrongMessage)); } *early_bytes += line.len(); if early.len() >= MAX_EARLY_NOTIFICATIONS || *early_bytes > MAX_EARLY_NOTIFICATION_BYTES { return Err(HandshakeError::TooManyNotifications); } early.push(line); } } /// Negotiate BIP310, subscribe, and authorize in that order. The entire /// handshake shares one absolute deadline; early notifications are kept /// for the caller to apply before reading new pool lines. pub fn handshake( &mut self, agent: &str, worker: &str, password: &str, timeout: Duration, ) -> Result { let result = self.handshake_inner(agent, worker, password, timeout); if result.is_err() { self.close(); } result } fn handshake_inner( &mut self, agent: &str, worker: &str, password: &str, timeout: Duration, ) -> Result { let deadline = Instant::now() .checked_add(timeout) .filter(|_| !timeout.is_zero()) .ok_or(HandshakeError::Wire(WireError::InvalidRequest))?; let subscribe = subscribe_request(2, agent).map_err(HandshakeError::Wire)?; let authorize = authorize_request(3, worker, password).map_err(HandshakeError::Wire)?; let mut early_notifications = Vec::new(); let mut early_bytes = 0; self.send_line_before(configure_request(1).as_bytes(), deadline) .map_err(HandshakeError::Wire)?; let configure = self.read_reply(1, deadline, &mut early_notifications, &mut early_bytes)?; let configure = parse_configure_result(&configure, 1).map_err(HandshakeError::Pool)?; self.send_line_before(subscribe.as_bytes(), deadline) .map_err(HandshakeError::Wire)?; let subscription = self.read_reply(2, deadline, &mut early_notifications, &mut early_bytes)?; let subscription = parse_subscription(&subscription, 2).map_err(HandshakeError::Pool)?; self.send_line_before(authorize.as_bytes(), deadline) .map_err(HandshakeError::Wire)?; let authorized = self.read_reply(3, deadline, &mut early_notifications, &mut early_bytes)?; if !parse_boolean_response(&authorized, 3).map_err(HandshakeError::Pool)? { return Err(HandshakeError::Rejected); } Ok(PoolHandshake { subscription, configure, early_notifications, }) } } /// Offer BIP310 version rolling and extranonce updates before subscribing. pub fn configure_request(id: u64) -> String { json!({ "id": id, "method": "mining.configure", "params": [ ["version-rolling", "subscribe-extranonce"], {"version-rolling.mask": "1fffe000", "version-rolling.min-bit-count": 0} ] }) .to_string() + "\n" } pub fn subscribe_request(id: u64, agent: &str) -> Result { if agent.is_empty() || agent.len() > 128 { return Err(WireError::InvalidRequest); } Ok(json!({"id": id, "method": "mining.subscribe", "params": [agent]}).to_string() + "\n") } pub fn authorize_request(id: u64, worker: &str, password: &str) -> Result { if worker.is_empty() || worker.len() > 128 || password.len() > 256 { return Err(WireError::InvalidRequest); } Ok( json!({"id": id, "method": "mining.authorize", "params": [worker, password]}).to_string() + "\n", ) }