Negotiate pool extensions and authorize over bounded transport
main-release-gate / verify-and-release (push) Canceled after 0s
main-release-gate / verify-and-release (push) Canceled after 0s
This commit is contained in:
+47
-1
@@ -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
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user