Add the Stratum V2 session: handshake, jobs and submissions
source-pr / source (pull_request) Successful in 11s

Drive the client half of an SV2 mining connection: send SetupConnection,
verify the success reply, open a standard channel and remember its id, target
and extranonce prefix. Afterwards the session interprets NewMiningJob,
SetNewPrevHash, SetTarget and share acknowledgements, and submits standard
shares with a monotonic sequence number.

State is explicit rather than assumed: a job that arrives before any
SetNewPrevHash reports no previous hash instead of a zero one, a setup or
channel rejection carries the server's error code, and an unknown message is
ignored instead of killing the session.
This commit is contained in:
2026-10-22 10:36:29 -06:00
parent 6ab645e731
commit 914fb8bef7
2 changed files with 554 additions and 0 deletions
+1
View File
@@ -23,6 +23,7 @@ pub mod stratum_session;
pub mod stratum_submit;
pub mod stratum_v1;
pub mod stratum_v2;
pub mod stratum_v2_session;
pub mod stratum_wire;
pub mod stratum_work;
pub mod tuning;
+553
View File
@@ -0,0 +1,553 @@
// SPDX-License-Identifier: MIT
//! Stratum V2 session: handshake, channel, jobs and share submission.
//!
//! The codec in `stratum_v2` owns bytes; this module owns order. It drives the client half of a
//! mining connection and refuses to invent state: a job received before any `SetNewPrevHash` is
//! reported with no previous hash rather than with a zero one, and a rejected setup surfaces the
//! server's code.
use crate::stratum_v2::{
Frame, NewMiningJob, OpenStandardMiningChannel, SetNewPrevHash, SetupConnection,
SetupConnectionSuccess, SubmitSharesStandard, NEW_MINING_JOB, OPEN_MINING_CHANNEL_ERROR,
OPEN_STANDARD_MINING_CHANNEL, OPEN_STANDARD_MINING_CHANNEL_SUCCESS, SETUP_CONNECTION,
SETUP_CONNECTION_ERROR, SETUP_CONNECTION_SUCCESS, SET_NEW_PREV_HASH, SET_TARGET,
SUBMIT_SHARES_ERROR, SUBMIT_SHARES_STANDARD, SUBMIT_SHARES_SUCCESS,
};
/// A connection that carries whole frames.
pub trait V2Link {
type Error;
fn send(&mut self, frame: &Frame) -> Result<(), Self::Error>;
fn recv(&mut self) -> Result<Frame, Self::Error>;
}
/// What the client declares when it connects.
#[derive(Clone, Debug, PartialEq)]
pub struct V2Config {
pub host: String,
pub port: u16,
pub flags: u32,
pub user_identity: String,
pub nominal_hash_rate: f32,
pub max_target: [u8; 32],
pub vendor: String,
pub hardware: String,
pub firmware: String,
pub device_id: String,
}
/// An opened standard channel.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct V2Channel {
pub channel_id: u32,
pub target: [u8; 32],
pub extranonce_prefix: Vec<u8>,
pub group_channel_id: u32,
}
/// A job the miner may work on.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct V2Job {
pub job_id: u32,
pub version: u32,
pub merkle_root: [u8; 32],
pub ntime_start: Option<u32>,
pub prev_hash: Option<[u8; 32]>,
pub nbits: Option<u32>,
}
/// Something the server told us.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum V2Event {
Job(V2Job),
PrevHash {
job_id: u32,
prev_hash: [u8; 32],
ntime_start: u32,
nbits: u32,
},
Target {
channel_id: u32,
target: [u8; 32],
},
ShareAccepted {
last_sequence: u32,
accepted: u32,
},
ShareRejected {
last_sequence: u32,
},
Ignored,
}
/// A protocol-level failure, without a link error inside it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SessionError {
Protocol(&'static str),
Rejected(String),
}
/// A failure that may have come from the transport.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ConnectError<E> {
Link(E),
Session(SessionError),
}
/// Run the client handshake and return the opened channel.
pub fn handshake<L: V2Link>(
link: &mut L,
config: &V2Config,
) -> Result<V2Channel, ConnectError<L::Error>> {
let setup = SetupConnection {
protocol: 0,
min_version: 2,
max_version: 2,
flags: config.flags,
endpoint_host: config.host.clone(),
endpoint_port: config.port,
vendor: config.vendor.clone(),
hardware_version: config.hardware.clone(),
firmware: config.firmware.clone(),
device_id: config.device_id.clone(),
};
link.send(&Frame::new(SETUP_CONNECTION, setup.encode()))
.map_err(ConnectError::Link)?;
let reply = link.recv().map_err(ConnectError::Link)?;
match reply.msg_type {
SETUP_CONNECTION_SUCCESS => {
let _ = SetupConnectionSuccess::decode(&reply.payload)
.map_err(|_| ConnectError::Session(SessionError::Protocol("bad setup success")))?;
}
SETUP_CONNECTION_ERROR => {
return Err(ConnectError::Session(SessionError::Rejected(
setup_error_text(&reply.payload),
)))
}
_ => {
return Err(ConnectError::Session(SessionError::Protocol(
"unexpected message before setup success",
)))
}
}
let open = OpenStandardMiningChannel {
request_id: 1,
user_identity: config.user_identity.clone(),
nominal_hash_rate: config.nominal_hash_rate,
max_target: config.max_target,
};
link.send(&Frame::new(OPEN_STANDARD_MINING_CHANNEL, open.encode()))
.map_err(ConnectError::Link)?;
let reply = link.recv().map_err(ConnectError::Link)?;
match reply.msg_type {
OPEN_STANDARD_MINING_CHANNEL_SUCCESS => {
let success =
crate::stratum_v2::OpenStandardMiningChannelSuccess::decode(&reply.payload)
.map_err(|_| {
ConnectError::Session(SessionError::Protocol("bad channel success"))
})?;
if success.request_id != 1 {
return Err(ConnectError::Session(SessionError::Protocol(
"channel response does not match the request",
)));
}
Ok(V2Channel {
channel_id: success.channel_id,
target: success.target,
extranonce_prefix: success.extranonce_prefix,
group_channel_id: success.group_channel_id,
})
}
OPEN_MINING_CHANNEL_ERROR => Err(ConnectError::Session(SessionError::Rejected(
setup_error_text(&reply.payload),
))),
_ => Err(ConnectError::Session(SessionError::Protocol(
"unexpected message while opening a channel",
))),
}
}
fn setup_error_text(payload: &[u8]) -> String {
// Error messages are a U32 flag mask followed by a STR0_255 code.
if payload.len() < 5 {
return String::from("unspecified");
}
let length = payload[4] as usize;
payload
.get(5..5 + length)
.and_then(|bytes| std::str::from_utf8(bytes).ok())
.unwrap_or("unspecified")
.to_owned()
}
/// Session state after the handshake.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct V2Session {
channel: V2Channel,
prev_hash: Option<[u8; 32]>,
nbits: Option<u32>,
sequence: u32,
}
impl V2Session {
pub fn new(channel: V2Channel) -> Self {
Self {
channel,
prev_hash: None,
nbits: None,
sequence: 0,
}
}
pub fn channel(&self) -> &V2Channel {
&self.channel
}
/// Interpret one server frame.
pub fn on_frame(&mut self, frame: &Frame) -> Result<V2Event, SessionError> {
match frame.msg_type {
NEW_MINING_JOB => {
let job = NewMiningJob::decode(&frame.payload)
.map_err(|_| SessionError::Protocol("bad NewMiningJob"))?;
Ok(V2Event::Job(V2Job {
job_id: job.job_id,
version: job.version,
merkle_root: job.merkle_root,
ntime_start: job.ntime_start,
prev_hash: self.prev_hash,
nbits: self.nbits,
}))
}
SET_NEW_PREV_HASH => {
let message = SetNewPrevHash::decode(&frame.payload)
.map_err(|_| SessionError::Protocol("bad SetNewPrevHash"))?;
self.prev_hash = Some(message.prev_hash);
self.nbits = Some(message.nbits);
Ok(V2Event::PrevHash {
job_id: message.job_id,
prev_hash: message.prev_hash,
ntime_start: message.ntime_start,
nbits: message.nbits,
})
}
SET_TARGET => {
if frame.payload.len() != 4 + 32 {
return Err(SessionError::Protocol("bad SetTarget"));
}
let channel_id = u32::from_le_bytes([
frame.payload[0],
frame.payload[1],
frame.payload[2],
frame.payload[3],
]);
let mut target = [0_u8; 32];
target.copy_from_slice(&frame.payload[4..36]);
Ok(V2Event::Target { channel_id, target })
}
SUBMIT_SHARES_SUCCESS => {
if frame.payload.len() < 20 {
return Err(SessionError::Protocol("bad SubmitShares.Success"));
}
let last_sequence = u32::from_le_bytes([
frame.payload[4],
frame.payload[5],
frame.payload[6],
frame.payload[7],
]);
let accepted = u32::from_le_bytes([
frame.payload[8],
frame.payload[9],
frame.payload[10],
frame.payload[11],
]);
Ok(V2Event::ShareAccepted {
last_sequence,
accepted,
})
}
SUBMIT_SHARES_ERROR => {
let last_sequence = if frame.payload.len() >= 8 {
u32::from_le_bytes([
frame.payload[0],
frame.payload[1],
frame.payload[2],
frame.payload[3],
])
} else {
0
};
Ok(V2Event::ShareRejected { last_sequence })
}
_ => Ok(V2Event::Ignored),
}
}
/// Submit one standard share; returns the sequence number used.
pub fn submit<L: V2Link>(
&mut self,
link: &mut L,
job_id: u32,
nonce: u32,
ntime: u32,
version: u32,
) -> Result<u32, ConnectError<L::Error>> {
self.sequence = self.sequence.wrapping_add(1);
let share = SubmitSharesStandard {
channel_id: self.channel.channel_id,
sequence_number: self.sequence,
job_id,
nonce,
ntime,
version,
};
link.send(&Frame::new(SUBMIT_SHARES_STANDARD, share.encode()))
.map_err(ConnectError::Link)?;
Ok(self.sequence)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::VecDeque;
struct Scripted {
incoming: VecDeque<Frame>,
sent: Vec<Frame>,
}
impl Scripted {
fn new(incoming: Vec<Frame>) -> Self {
Self {
incoming: incoming.into(),
sent: Vec::new(),
}
}
}
impl V2Link for Scripted {
type Error = ();
fn send(&mut self, frame: &Frame) -> Result<(), ()> {
self.sent.push(frame.clone());
Ok(())
}
fn recv(&mut self) -> Result<Frame, ()> {
self.incoming.pop_front().ok_or(())
}
}
fn config() -> V2Config {
V2Config {
host: "pool.example".into(),
port: 3333,
flags: 0,
user_identity: "worker".into(),
nominal_hash_rate: 1.0e14,
max_target: [0xff; 32],
vendor: "alkane".into(),
hardware: "bench".into(),
firmware: "alkane-os".into(),
device_id: "bench-1".into(),
}
}
fn setup_success() -> Frame {
Frame::new(
SETUP_CONNECTION_SUCCESS,
SetupConnectionSuccess {
used_version: 2,
flags: 0,
}
.encode(),
)
}
fn channel_success() -> Frame {
Frame::new(
OPEN_STANDARD_MINING_CHANNEL_SUCCESS,
crate::stratum_v2::OpenStandardMiningChannelSuccess {
request_id: 1,
channel_id: 9,
target: [0x7f; 32],
extranonce_prefix: vec![1, 2],
group_channel_id: 0,
}
.encode(),
)
}
#[test]
fn handshake_sends_setup_then_open_and_returns_the_channel() {
let mut link = Scripted::new(vec![setup_success(), channel_success()]);
let channel = handshake(&mut link, &config()).expect("handshake");
assert_eq!(channel.channel_id, 9);
assert_eq!(channel.extranonce_prefix, vec![1, 2]);
assert_eq!(link.sent.len(), 2);
assert_eq!(link.sent[0].msg_type, SETUP_CONNECTION);
assert_eq!(link.sent[1].msg_type, OPEN_STANDARD_MINING_CHANNEL);
let open = OpenStandardMiningChannel::decode(&link.sent[1].payload).expect("open");
assert_eq!(open.user_identity, "worker");
assert_eq!(open.request_id, 1);
}
#[test]
fn a_setup_error_surfaces_the_server_code() {
let mut payload = 0_u32.to_le_bytes().to_vec();
payload.push(3);
payload.extend_from_slice(b"bad");
let mut link = Scripted::new(vec![Frame::new(SETUP_CONNECTION_ERROR, payload)]);
assert_eq!(
handshake(&mut link, &config()),
Err(ConnectError::Session(SessionError::Rejected("bad".into())))
);
}
#[test]
fn an_unexpected_message_during_setup_is_a_protocol_error() {
let mut link = Scripted::new(vec![Frame::new(NEW_MINING_JOB, vec![0; 44])]);
assert_eq!(
handshake(&mut link, &config()),
Err(ConnectError::Session(SessionError::Protocol(
"unexpected message before setup success"
)))
);
}
#[test]
fn a_job_before_any_prev_hash_has_no_prev_hash() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let job = NewMiningJob {
channel_id: 9,
job_id: 1,
ntime_start: Some(1_700_000_000),
version: 0x2000_0000,
merkle_root: [0x11; 32],
};
let event = session
.on_frame(&Frame::new(NEW_MINING_JOB, job.encode()))
.expect("job");
match event {
V2Event::Job(parsed) => {
assert_eq!(parsed.job_id, 1);
assert_eq!(parsed.prev_hash, None);
assert_eq!(parsed.nbits, None);
}
other => panic!("unexpected event: {other:?}"),
}
}
#[test]
fn prev_hash_is_remembered_for_later_jobs() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let prev = SetNewPrevHash {
channel_id: 9,
job_id: 1,
prev_hash: [0x22; 32],
ntime_start: 1_700_000_100,
nbits: 0x1707_0000,
};
session
.on_frame(&Frame::new(SET_NEW_PREV_HASH, prev.encode()))
.expect("prev hash");
let job = NewMiningJob {
channel_id: 9,
job_id: 2,
ntime_start: None,
version: 0x2000_0000,
merkle_root: [0x33; 32],
};
match session
.on_frame(&Frame::new(NEW_MINING_JOB, job.encode()))
.expect("job")
{
V2Event::Job(parsed) => {
assert_eq!(parsed.prev_hash, Some([0x22; 32]));
assert_eq!(parsed.nbits, Some(0x1707_0000));
assert_eq!(parsed.ntime_start, None);
}
other => panic!("unexpected event: {other:?}"),
}
}
#[test]
fn submissions_use_the_channel_and_increasing_sequence_numbers() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let mut link = Scripted::new(Vec::new());
assert_eq!(
session
.submit(&mut link, 1, 0xabcd, 1_700_000_000, 0x2000_0000)
.expect("submit"),
1
);
assert_eq!(
session
.submit(&mut link, 1, 0xabce, 1_700_000_000, 0x2000_0000)
.expect("submit"),
2
);
assert_eq!(link.sent.len(), 2);
let first = SubmitSharesStandard::decode(&link.sent[0].payload).expect("share");
assert_eq!(first.channel_id, 9);
assert_eq!(first.sequence_number, 1);
assert_eq!(first.nonce, 0xabcd);
}
#[test]
fn share_success_reports_the_last_sequence() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
let mut payload = Vec::new();
payload.extend_from_slice(&9_u32.to_le_bytes());
payload.extend_from_slice(&7_u32.to_le_bytes());
payload.extend_from_slice(&3_u32.to_le_bytes());
payload.extend_from_slice(&0_u64.to_le_bytes());
assert_eq!(
session
.on_frame(&Frame::new(SUBMIT_SHARES_SUCCESS, payload))
.expect("event"),
V2Event::ShareAccepted {
last_sequence: 7,
accepted: 3
}
);
}
#[test]
fn an_unknown_message_is_ignored_not_fatal() {
let mut session = V2Session::new(V2Channel {
channel_id: 9,
target: [0xff; 32],
extranonce_prefix: Vec::new(),
group_channel_id: 0,
});
assert_eq!(
session
.on_frame(&Frame::new(0x7e, vec![0; 4]))
.expect("event"),
V2Event::Ignored
);
}
}