From 654b205e00b5478f4bbf5de25f705ef29263caca Mon Sep 17 00:00:00 2001 From: noah Date: Thu, 15 Oct 2026 01:30:43 -0600 Subject: [PATCH] Add bounded Stratum TCP transport and request frames --- src/lib.rs | 1 + src/stratum_v1.rs | 4 +- src/stratum_wire.rs | 187 ++++++++++++++++++++++++++++++++++++++++++ tests/bench.rs | 9 ++ tests/stratum_wire.rs | 91 ++++++++++++++++++++ 5 files changed, 290 insertions(+), 2 deletions(-) create mode 100644 src/stratum_wire.rs create mode 100644 tests/stratum_wire.rs diff --git a/src/lib.rs b/src/lib.rs index c948360..60c79b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod pow; pub mod stratum_session; pub mod stratum_submit; pub mod stratum_v1; +pub mod stratum_wire; pub mod stratum_work; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/src/stratum_v1.rs b/src/stratum_v1.rs index cf985da..dbe8522 100644 --- a/src/stratum_v1.rs +++ b/src/stratum_v1.rs @@ -7,7 +7,7 @@ use crate::pow::VersionMask; use crate::stratum_work::{JobError, Sha256Job}; use serde_json::Value; -const MAX_LINE_BYTES: usize = 131_072; +pub const MAX_POOL_LINE_BYTES: usize = 131_072; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PoolMessageError { @@ -40,7 +40,7 @@ pub struct PoolJob { } fn parse_json(line: &[u8]) -> Result { - if line.len() > MAX_LINE_BYTES { + if line.len() > MAX_POOL_LINE_BYTES { return Err(PoolMessageError::TooLarge); } serde_json::from_slice(line).map_err(|_| PoolMessageError::Json) diff --git a/src/stratum_wire.rs b/src/stratum_wire.rs new file mode 100644 index 0000000..6254e74 --- /dev/null +++ b/src/stratum_wire.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: MIT +//! Bounded newline-framed TCP transport for Bitcoin Stratum V1 pools. + +use crate::stratum_v1::MAX_POOL_LINE_BYTES; +use serde_json::json; +use std::io::{self, Read, Write}; +use std::net::{Shutdown, SocketAddr, TcpStream}; +use std::time::{Duration, Instant}; + +#[derive(Debug)] +pub enum WireError { + InvalidRequest, + LineTooLong, + Timeout, + Eof, + Closed, + Io(io::Error), +} + +pub struct StratumWire { + stream: TcpStream, + buffered: Vec, + 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(), + 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(), + timeout, + closed: false, + }) + } + + fn close(&mut self) { + self.closed = true; + let _ = self.stream.shutdown(Shutdown::Both); + } + + 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), + } + } + + pub fn read_line(&mut self) -> Result, WireError> { + if self.closed { + return Err(WireError::Closed); + } + let deadline = Instant::now() + self.timeout; + 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); + } + return Ok(self.buffered.drain(..=end).collect()); + } + 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) => { + 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) => self.buffered.extend_from_slice(&chunk[..length]), + Err(error) => { + self.close(); + return Err(Self::transport_error(error)); + } + } + } + } + + pub fn send_line(&mut self, line: &[u8]) -> 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 deadline = Instant::now() + self.timeout; + 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(()) + } +} + +/// 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", + ) +} diff --git a/tests/bench.rs b/tests/bench.rs index 6b59263..ababaef 100644 --- a/tests/bench.rs +++ b/tests/bench.rs @@ -6,6 +6,7 @@ use alkane_os::pow::VersionMask; use alkane_os::stratum_session::PoolSession; use alkane_os::stratum_submit::{format_submission, Submission}; use alkane_os::stratum_v1::{parse_control_notification, parse_notify, Subscription}; +use alkane_os::stratum_wire::authorize_request; use alkane_os::stratum_work::Sha256Job; use alkane_os::{power_decision, target_matrix, HardwareBackend}; use std::hint::black_box; @@ -116,6 +117,14 @@ fn bench_stratum_submission() { }); } +#[test] +#[ignore = "microbenchmark"] +fn bench_stratum_authorize_format() { + measure("stratum_authorize_format", 20_000, || { + black_box(authorize_request(black_box(3), "miner.worker", "password").unwrap()); + }); +} + #[test] #[ignore = "microbenchmark"] fn bench_stratum_notify_parse() { diff --git a/tests/stratum_wire.rs b/tests/stratum_wire.rs new file mode 100644 index 0000000..f336b39 --- /dev/null +++ b/tests/stratum_wire.rs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +use alkane_os::stratum_v1::MAX_POOL_LINE_BYTES; +use alkane_os::stratum_wire::{ + authorize_request, configure_request, subscribe_request, StratumWire, WireError, +}; +use serde_json::Value; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::thread; +use std::time::Duration; + +#[test] +fn request_frames_escape_pool_credentials_and_advertise_supported_bits() { + let configure: Value = serde_json::from_str(&configure_request(1)).unwrap(); + assert_eq!(configure["method"], "mining.configure"); + assert_eq!(configure["params"][1]["version-rolling.mask"], "1fffe000"); + assert_eq!(configure["params"][0][1], "subscribe-extranonce"); + let subscribe: Value = + serde_json::from_str(&subscribe_request(2, "alkane-os/0.1").unwrap()).unwrap(); + assert_eq!(subscribe["params"][0], "alkane-os/0.1"); + let authorized = authorize_request(3, "worker\"name", "secret\nvalue").unwrap(); + assert_eq!(authorized.as_bytes().last(), Some(&b'\n')); + let authorize: Value = serde_json::from_str(&authorized).unwrap(); + assert_eq!(authorize["params"][0], "worker\"name"); + assert_eq!(authorize["params"][1], "secret\nvalue"); + assert!(matches!( + subscribe_request(2, ""), + Err(WireError::InvalidRequest) + )); + assert!(matches!( + authorize_request(3, "", "pass"), + Err(WireError::InvalidRequest) + )); +} + +#[test] +fn loopback_frames_preserve_pipelined_lines_and_reject_invalid_sends() { + 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(b"{\"id\":1}\n{\"id\":2}\n").unwrap(); + let mut request = [0_u8; 3]; + stream.read_exact(&mut request).unwrap(); + assert_eq!(&request, b"{}\n"); + }); + let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap(); + assert_eq!(wire.read_line().unwrap(), b"{\"id\":1}\n"); + assert_eq!(wire.read_line().unwrap(), b"{\"id\":2}\n"); + assert!(matches!( + wire.send_line(b"bad\nline\n"), + Err(WireError::InvalidRequest) + )); + wire.send_line(b"{}\n").unwrap(); + server.join().unwrap(); +} + +#[test] +fn oversized_pool_line_poison_closes_the_connection() { + 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(); + let mut line = vec![b'a'; MAX_POOL_LINE_BYTES]; + line.push(b'\n'); + let _ = stream.write_all(&line); + }); + let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap(); + assert!(matches!(wire.read_line(), Err(WireError::LineTooLong))); + assert!(matches!(wire.read_line(), Err(WireError::Closed))); + server.join().unwrap(); +} + +#[test] +fn trickled_pool_line_hits_the_absolute_deadline() { + 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(); + for byte in b"{123}\n" { + if stream.write_all(&[*byte]).is_err() { + break; + } + thread::sleep(Duration::from_millis(60)); + } + }); + let mut wire = StratumWire::connect(address, Duration::from_millis(130)).unwrap(); + assert!(matches!(wire.read_line(), Err(WireError::Timeout))); + assert!(matches!(wire.send_line(b"{}\n"), Err(WireError::Closed))); + server.join().unwrap(); +}