Negotiate pool extensions and authorize over bounded transport
next-build / build (push) Canceled after 0s

This commit is contained in:
2026-10-15 01:44:12 -06:00
parent 654b205e00
commit bc38a4a787
6 changed files with 349 additions and 15 deletions
+8 -5
View File
@@ -35,7 +35,7 @@ board adapter is installed in an image yet.
The library can also verify an ASIC-reported SHA-256d share against an exact
pool target, including BM13xx version rolling. A test checks a BM1366 nonce
captured from real silicon at difficulty 1588. This verifies reports only;
pool communication and continuous job scheduling are still pending.
end-to-end pool mining and continuous job scheduling are still pending.
The `simulator_replay_probe` example sends that captured job through the Rust
HAL client to the SDK's host-only C/Python replay server, then verifies the
returned nonce. From this repository, run it with
@@ -49,8 +49,11 @@ limit.
The library now formats verified shares as Stratum V1 `mining.submit` requests.
For negotiated BIP310 version rolling, it includes the sixth version-bits
parameter and rejects ASIC versions that the current pool mask cannot
represent. Pool connections, response tracking, and continuous scheduling
remain to be implemented.
represent. The pool transport bounds newline frames and uses absolute socket
deadlines. It can negotiate BIP310 extensions, subscribe, and authorize a
worker over a live TCP connection while retaining early notifications in wire
order. It has loopback tests; no live pool acceptance has been observed yet.
Share response tracking and continuous scheduling remain to be implemented.
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
@@ -58,8 +61,8 @@ become 256-bit pool targets without floating point rounding. Pool job
bookkeeping keeps earlier work tied to its original target and extranonce,
invalidates old work on `clean_jobs`, and rechecks a reported share before
formatting it for submission. It does not reuse ASIC work IDs until the caller
confirms a hardware reset. A live pool connection, hardware job dispatch,
share-response tracking, and continuous mining remain to be implemented.
confirms a hardware reset. Hardware job dispatch is library-only so far;
share response tracking and continuous mining remain to be implemented.
The exact Rust dependency sources are under `vendor/` with Cargo checksums,
so SDK board builds can compile offline. Dependencies retain the license terms
in their vendored manifests and license files.
+47 -1
View File
@@ -26,6 +26,12 @@ pub struct Subscription {
pub extranonce2_size: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ConfigureResult {
pub version_mask: Option<VersionMask>,
pub subscribe_extranonce: bool,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PoolNotification {
SetDifficulty(PoolDifficulty),
@@ -133,7 +139,7 @@ pub fn parse_configure_response(
.and_then(Value::as_object)
.ok_or(PoolMessageError::InvalidField)?;
match result.get("version-rolling") {
Some(Value::Bool(false)) => Ok(None),
Some(Value::Bool(false) | Value::String(_)) => Ok(None),
Some(Value::Bool(true)) => {
let mask = hex_u32(
result
@@ -148,6 +154,46 @@ pub fn parse_configure_response(
}
}
/// Decode both offered BIP310 extensions. The response must explicitly
/// acknowledge each advertised extension before its notifications are used.
pub fn parse_configure_result(
line: &[u8],
request_id: u64,
) -> Result<ConfigureResult, PoolMessageError> {
let version_mask = parse_configure_response(line, request_id)?;
let message = parse_json(line)?;
let result = message
.get("result")
.and_then(Value::as_object)
.ok_or(PoolMessageError::InvalidField)?;
let subscribe_extranonce = match result.get("subscribe-extranonce") {
Some(Value::Bool(value)) => *value,
Some(Value::String(_)) => false,
_ => return Err(PoolMessageError::InvalidField),
};
Ok(ConfigureResult {
version_mask,
subscribe_extranonce,
})
}
/// Decode a matching authorization or share-submission result. A false
/// result is an ordinary pool rejection and must not count as an accept.
pub fn parse_boolean_response(line: &[u8], request_id: u64) -> Result<bool, PoolMessageError> {
let message = parse_json(line)?;
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);
}
Ok(accepted)
}
/// Decode pool control notifications. The caller applies them in stream order:
/// difficulty to the next job, extranonce to subsequent work, and the version
/// mask immediately to all pending submissions.
+125 -4
View File
@@ -2,11 +2,18 @@
//! 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;
#[derive(Debug)]
pub enum WireError {
InvalidRequest,
@@ -17,6 +24,21 @@ pub enum WireError {
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<Vec<u8>>,
}
pub struct StratumWire {
stream: TcpStream,
buffered: Vec<u8>,
@@ -71,11 +93,10 @@ impl StratumWire {
}
}
pub fn read_line(&mut self) -> Result<Vec<u8>, WireError> {
fn read_line_before(&mut self, deadline: Instant) -> Result<Vec<u8>, 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 {
@@ -114,7 +135,11 @@ impl StratumWire {
}
}
pub fn send_line(&mut self, line: &[u8]) -> Result<(), WireError> {
pub fn read_line(&mut self) -> Result<Vec<u8>, WireError> {
self.read_line_before(Instant::now() + self.timeout)
}
fn send_line_before(&mut self, line: &[u8], deadline: Instant) -> Result<(), WireError> {
if self.closed {
return Err(WireError::Closed);
}
@@ -125,7 +150,6 @@ impl StratumWire {
{
return Err(WireError::InvalidRequest);
}
let deadline = Instant::now() + self.timeout;
let mut sent = 0;
while sent < line.len() {
let remaining = match Self::remaining(deadline) {
@@ -153,6 +177,103 @@ impl StratumWire {
}
Ok(())
}
pub fn send_line(&mut self, line: &[u8]) -> Result<(), WireError> {
self.send_line_before(line, Instant::now() + self.timeout)
}
fn read_reply(
&mut self,
request_id: u64,
deadline: Instant,
early: &mut Vec<Vec<u8>>,
early_bytes: &mut usize,
) -> Result<Vec<u8>, 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<PoolHandshake, HandshakeError> {
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<PoolHandshake, HandshakeError> {
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.
+12 -1
View File
@@ -5,7 +5,9 @@ use alkane_os::pow::verify_sha256_report;
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_v1::{
parse_configure_result, 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};
@@ -156,6 +158,15 @@ fn bench_stratum_control_parse() {
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_stratum_configure_parse() {
let line = br#"{"id":1,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","subscribe-extranonce":true},"error":null}"#;
measure("stratum_configure_parse", 20_000, || {
black_box(parse_configure_result(black_box(line), 1).unwrap());
});
}
#[test]
#[ignore = "microbenchmark"]
fn bench_difficulty_target() {
+43 -2
View File
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: MIT
use alkane_os::difficulty::PoolDifficulty;
use alkane_os::stratum_v1::{
parse_configure_response, parse_control_notification, parse_notify, parse_subscription,
PoolMessageError, PoolNotification, Subscription,
parse_boolean_response, parse_configure_response, parse_configure_result,
parse_control_notification, parse_notify, parse_subscription, PoolMessageError,
PoolNotification, Subscription,
};
const SUBSCRIBE: &str =
@@ -105,6 +106,46 @@ fn version_rolling_negotiation_and_immediate_mask_change() {
);
}
#[test]
fn both_bip310_extensions_and_boolean_responses_are_checked() {
let accepted = br#"{"id":3,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","subscribe-extranonce":true},"error":null}"#;
let result = parse_configure_result(accepted, 3).unwrap();
assert_eq!(result.version_mask.unwrap().bits(), 0x1fff_e000);
assert!(result.subscribe_extranonce);
let declined =
br#"{"id":3,"result":{"version-rolling":false,"subscribe-extranonce":false},"error":null}"#;
let result = parse_configure_result(declined, 3).unwrap();
assert_eq!(result.version_mask, None);
assert!(!result.subscribe_extranonce);
let unavailable = br#"{"id":3,"result":{"version-rolling":"unavailable","subscribe-extranonce":"unsupported"},"error":null}"#;
let result = parse_configure_result(unavailable, 3).unwrap();
assert_eq!(result.version_mask, None);
assert!(!result.subscribe_extranonce);
assert_eq!(
parse_configure_result(
br#"{"id":3,"result":{"version-rolling":false},"error":null}"#,
3
),
Err(PoolMessageError::InvalidField)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":true,"error":null}"#, 5),
Ok(true)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":false,"error":[23,"stale"]}"#, 5),
Ok(false)
);
assert_eq!(
parse_boolean_response(br#"{"id":5,"result":true,"error":[23,"stale"]}"#, 5),
Err(PoolMessageError::InvalidField)
);
assert_eq!(
parse_boolean_response(br#"{"id":6,"result":true,"error":null}"#, 5),
Err(PoolMessageError::WrongMessage)
);
}
#[test]
fn difficulty_and_extranonce_notifications_validate_shape_and_negotiation() {
let difficulty = br#"{"id":null,"method":"mining.set_difficulty","params":[2048.5]}"#;
+114 -2
View File
@@ -1,10 +1,10 @@
// 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,
authorize_request, configure_request, subscribe_request, HandshakeError, StratumWire, WireError,
};
use serde_json::Value;
use std::io::{Read, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;
@@ -89,3 +89,115 @@ fn trickled_pool_line_hits_the_absolute_deadline() {
assert!(matches!(wire.send_line(b"{}\n"), Err(WireError::Closed)));
server.join().unwrap();
}
#[test]
fn handshake_preserves_early_notifications_and_authorizes_worker() {
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 input = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.configure"
);
stream.write_all(b"{\"id\":1,\"result\":{\"version-rolling\":true,\"version-rolling.mask\":\"1fffe000\",\"subscribe-extranonce\":true},\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.subscribe"
);
stream.write_all(b"{\"id\":null,\"method\":\"mining.set_difficulty\",\"params\":[1]}\n{\"id\":2,\"result\":[[],\"01020304\",4],\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&line).unwrap()["method"],
"mining.authorize"
);
stream
.write_all(b"{\"id\":3,\"result\":true,\"error\":null}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
let result = wire
.handshake(
"alkane-os/0.1",
"miner.worker",
"password",
Duration::from_secs(2),
)
.unwrap();
assert_eq!(result.subscription.extranonce1, [1, 2, 3, 4]);
assert_eq!(result.subscription.extranonce2_size, 4);
assert!(result.configure.subscribe_extranonce);
assert_eq!(result.configure.version_mask.unwrap().bits(), 0x1fff_e000);
assert_eq!(result.early_notifications.len(), 1);
assert_eq!(
serde_json::from_slice::<Value>(&result.early_notifications[0]).unwrap()["method"],
"mining.set_difficulty"
);
server.join().unwrap();
}
#[test]
fn rejected_worker_closes_the_handshake_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 input = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
input.read_line(&mut line).unwrap();
stream.write_all(b"{\"id\":1,\"result\":{\"version-rolling\":false,\"subscribe-extranonce\":false},\"error\":null}\n").unwrap();
line.clear();
input.read_line(&mut line).unwrap();
stream
.write_all(b"{\"id\":2,\"result\":[[],\"01020304\",4],\"error\":null}\n")
.unwrap();
line.clear();
input.read_line(&mut line).unwrap();
stream
.write_all(b"{\"id\":3,\"result\":false,\"error\":[24,\"unauthorized\"]}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert!(matches!(
wire.handshake("alkane-os/0.1", "bad", "password", Duration::from_secs(2)),
Err(HandshakeError::Rejected)
));
assert!(matches!(wire.read_line(), Err(WireError::Closed)));
server.join().unwrap();
}
#[test]
fn wrong_handshake_reply_id_is_rejected_and_connection_closed() {
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 = String::new();
BufReader::new(stream.try_clone().unwrap())
.read_line(&mut line)
.unwrap();
stream
.write_all(b"{\"id\":9,\"result\":true,\"error\":null}\n")
.unwrap();
});
let mut wire = StratumWire::connect(address, Duration::from_secs(2)).unwrap();
assert!(matches!(
wire.handshake(
"alkane-os/0.1",
"miner.worker",
"password",
Duration::from_secs(2)
),
Err(HandshakeError::Pool(
alkane_os::stratum_v1::PoolMessageError::WrongMessage
))
));
assert!(matches!(wire.read_line(), Err(WireError::Closed)));
server.join().unwrap();
}