Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions COVERAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Cross-cutting invariants with no single home message.
| C-SC-4 | Ω2 | Θ1 | Server that serves Standard Channels (does not set `REQUIRES_EXTENDED_CHANNELS`) rejects a `SetupConnection` carrying `REQUIRES_STANDARD_JOBS` (bit 0) — fails the most basic client class | [§5.2.2](https://github.com/stratum-mining/sv2-spec/blob/main/05-Mining-Protocol.md#522-extended-channel) "MUST also accept Standard Channels unless they set `REQUIRES_EXTENDED_CHANNELS`" (derived: no sentence requires accepting `REQUIRES_STANDARD_JOBS`) | Send `SetupConnection` without bit 0; if `.Success.flags` lacks `REQUIRES_EXTENDED_CHANNELS`, a fresh connection with `REQUIRES_STANDARD_JOBS` must get `.Success` | `SetupConnection.Success`, `SetupConnection.Error` |
| C-SC-5 | Ω1 | Θ1 | Server sets `REQUIRES_EXTENDED_CHANNELS` in `.Success.flags` but then accepts `OpenStandardMiningChannel` instead of responding with `OpenMiningChannel.Error` | [§5.3.1](https://github.com/stratum-mining/sv2-spec/blob/main/05-Mining-Protocol.md#531-setupconnection-flags-for-mining-protocol) "If it does, the server MUST respond with `OpenMiningChannel.Error`" | After a `.Success` carrying `REQUIRES_EXTENDED_CHANNELS`, send `OpenStandardMiningChannel`; assert `OpenMiningChannel.Error` (only if the server sets `REQUIRES_EXTENDED_CHANNELS`) | `SetupConnection.Success`, `OpenStandardMiningChannel`, `OpenMiningChannel.Error` |
| C-SC-6 | Ω1 | Θ1 | Server sets `REQUIRES_FIXED_VERSION` but later sends `NewExtendedMiningJob` with `version_rolling_allowed = True` | [§5.3.1](https://github.com/stratum-mining/sv2-spec/blob/main/05-Mining-Protocol.md#531-setupconnection-flags-for-mining-protocol) "if this bit is set, extended jobs MUST NOT indicate support for version rolling" | Cross-message consistency (only if the server sets `REQUIRES_FIXED_VERSION`) | `NewExtendedMiningJob` |
| C-SC-7 | Ω1 | Θ1 | Server accepts `SetupConnection` with a `protocol` it does not serve | [§3.6.1](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#361-setupconnection-client---server) "If the server does not support the requested `protocol`, it MUST respond with `SetupConnection.Error`" | Send `SetupConnection` with a valid `protocol` the suite's target does not serve (e.g. `protocol=1`, Job Declaration, against a Mining Protocol Server); assert `SetupConnection.Error` | `SetupConnection.Error` |
| C-SC-7 | Ω1 | Θ1 | Server accepts `SetupConnection` for a defined `protocol` it does not then serve on the connection | [§3.6.1](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#361-setupconnection-client---server) "If the server does not support the requested `protocol`, it MUST respond with `SetupConnection.Error`" | Probe every other defined protocol on a fresh connection, using that protocol's own `SetupConnection.flags`: after `.Success`, send its first client message. A reply from the same protocol family passes as multi-protocol; a reply from another family fails; no reply fails only where the spec mandates a first server response (Mining [§5.3.2](https://github.com/stratum-mining/sv2-spec/blob/main/05-Mining-Protocol.md#532-openstandardminingchannel-client---server), Template Distribution [§7](https://github.com/stratum-mining/sv2-spec/blob/main/07-Template-Distribution-Protocol.md#7-template-distribution-protocol)). Job Declaration no-reply is reported *not exercised*: [§6.4.2](https://github.com/stratum-mining/sv2-spec/blob/main/06-Job-Declaration-Protocol.md#642-allocateminingjobtoken-client---server) rate-limits the request and leaves `user_identifier` restrictions to the server | `SetupConnection.Error`, `AllocateMiningJobToken`, `CoinbaseOutputConstraints`, `OpenStandardMiningChannel` |
| C-SC-8 | Ω1 | Θ1 | Server accepts `SetupConnection` with no supported version in the offered range (e.g. `(3,3)`, `(3,2)`, `(1,1)`) or closes without first sending `SetupConnection.Error` | [§3.6.1](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#361-setupconnection-client---server) "If the server supports no protocol version between `min_version` and `max_version` inclusive, it MUST respond with `SetupConnection.Error`" | Send version ranges with no overlap with 2; assert framed `SetupConnection.Error` before TCP close | `SetupConnection.Error` |
| C-SC-9 | Ω2 | Θ1 | Server crashes or drops the connection on 255-byte device-info strings (`vendor`, `hardware_version`, `firmware`, `device_id`) | [§3.1](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#31-data-types-mapping) `STR0_255` "Allowed range of length is 0 to 255" (derived) | Send `SetupConnection` with 255-byte printable-ASCII strings (so the probe exercises only the length bound); assert a framed `.Success` or `.Error` | `SetupConnection.Success`, `SetupConnection.Error` |
| C-SC-10 | Ω1 | Θ1 | Server accepts `SetupConnection` with a `protocol` value outside the ones the spec defines | [§3.6.1](https://github.com/stratum-mining/sv2-spec/blob/main/03-Protocol-Overview.md#361-setupconnection-client---server) "If the server does not support the requested `protocol`, it MUST respond with `SetupConnection.Error`" (`protocol` defines only 0, 1 and 2, so a server cannot support any other value) | Send `SetupConnection` with `protocol=3`; assert `SetupConnection.Error`. Needs a hand-built frame, since a typed client cannot encode an undefined `protocol` | `SetupConnection.Error` |
Expand Down Expand Up @@ -372,7 +372,7 @@ Reserved for a future Template Distribution Server suite. No scenarios yet.
| C-SC-4 — `REQUIRES_STANDARD_JOBS` accepted by a standard-serving server | ❌ |
| C-SC-5 — standard channel accepted despite `REQUIRES_EXTENDED_CHANNELS` | ❌ |
| C-SC-6 — `REQUIRES_FIXED_VERSION` + `version_rolling_allowed` consistency | ❌ |
| C-SC-7 — unsupported `protocol` value | ✅ |
| C-SC-7 — defined `protocol` accepted but not served | ✅ |
| C-SC-8 — version range with no supported version | ✅ |
| C-SC-9 — 255-byte printable device-info strings | ❌ |
| C-SC-10 — undefined `protocol` value | ❌ |
Expand Down
32 changes: 22 additions & 10 deletions src/app_type.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use stratum_apps::stratum_core::common_messages_sv2::Protocol;

/// The type of Sv2 application under test.
///
/// This selects the suite to run. It is not a claim that the endpoint serves
/// only this protocol: §3 allows one deployment to serve more than one Sv2
/// sub-protocol on the same address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppType {
MiningServer,
Expand All @@ -9,6 +13,22 @@ pub enum AppType {
}

impl AppType {
/// Every server role the suite knows how to test.
pub const ALL: [AppType; 3] = [
AppType::MiningServer,
AppType::JobDeclarationServer,
AppType::TemplateProvider,
];

/// A human-readable name for reports.
pub fn name(&self) -> &'static str {
match self {
AppType::MiningServer => "Mining Protocol",
AppType::JobDeclarationServer => "Job Declaration",
AppType::TemplateProvider => "Template Distribution",
}
}

/// The sub-protocol a well-behaved client speaks to this app type.
pub fn protocol(&self) -> Protocol {
match self {
Expand All @@ -22,18 +42,10 @@ impl AppType {
pub fn default_flags(&self) -> u32 {
match self {
AppType::MiningServer => 0,
// DECLARE_TX_DATA is required by the JDS.
// DECLARE_TX_DATA selects Full-Template mode, which makes
// `AllocateMiningJobToken` available on the connection.
AppType::JobDeclarationServer => 0b0001,
AppType::TemplateProvider => 0,
}
}

/// A sub-protocol this app type is expected to reject (C-SC-7).
pub fn wrong_protocol(&self) -> Protocol {
match self {
AppType::MiningServer => Protocol::JobDeclarationProtocol,
AppType::JobDeclarationServer => Protocol::TemplateDistributionProtocol,
AppType::TemplateProvider => Protocol::MiningProtocol,
}
}
}
38 changes: 28 additions & 10 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,18 +145,36 @@ impl TestClient {
}
}

/// Waits for the next message of any type from the endpoint, returning
/// `None` if `timeout` elapses first.
///
/// A caller that makes several reads under one budget passes the remaining
/// time on each call, so a server that keeps sending unrelated messages
/// cannot keep the caller waiting past its deadline.
pub async fn next_from_server_within(
&self,
timeout: Duration,
) -> Option<(u8, AnyMessageOwned)> {
let deadline = tokio::time::Instant::now() + timeout;
loop {
if let Some((t, msg)) = self.sniffer.next_message_from_upstream() {
return Some((t, msg));
}
let now = tokio::time::Instant::now();
if now >= deadline {
return None;
}
tokio::time::sleep(POLL_INTERVAL.min(deadline.saturating_duration_since(now))).await;
}
}

/// Waits for the next message of any type from the endpoint.
pub async fn next_from_server(&self) -> Result<(u8, AnyMessageOwned), ScenarioError> {
tokio::time::timeout(DEFAULT_MSG_TIMEOUT, async {
loop {
if let Some((t, msg)) = self.sniffer.next_message_from_upstream() {
return (t, msg);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.map_err(|_| ScenarioError::Failed("timeout waiting for any message from endpoint".into()))
self.next_from_server_within(DEFAULT_MSG_TIMEOUT)
.await
.ok_or_else(|| {
ScenarioError::Failed("timeout waiting for any message from endpoint".into())
})
}

/// Asserts the endpoint sends no message of `msg_type` within `duration`.
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ pub mod app_type;
pub mod client;
pub mod config;
pub mod endpoint;
pub mod probe;
pub mod runner;
pub mod scenarios;
150 changes: 150 additions & 0 deletions src/probe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//! Probing whether an endpoint serves a defined Sv2 sub-protocol.
//!
//! C-SC-7 cannot assume that the protocol selected by the suite is the only
//! one an endpoint serves (§3), and a `SetupConnection.Success` on its own is
//! not evidence that the endpoint serves the accepted protocol. The probe
//! sends the protocol's first client message and classifies what comes back.

use stratum_apps::stratum_core::{
binary_sv2::Str0255Owned,
job_declaration_sv2::AllocateMiningJobTokenOwned,
mining_sv2::OpenStandardMiningChannelOwned,
parsers_sv2::{AnyMessageOwned, JobDeclarationOwned, MiningOwned, TemplateDistributionOwned},
template_distribution_sv2::CoinbaseOutputConstraintsOwned,
};

use crate::{app_type::AppType, client::TestClient, scenarios::ScenarioError};

/// The `request_id` used by both the Mining and Job Declaration probes.
const PROBE_REQUEST_ID: u32 = 1;

/// What an endpoint did after accepting a probe's `SetupConnection`.
#[derive(Debug)]
pub enum ProbeOutcome {
/// The endpoint answered the opening request with a message from the
/// accepted protocol's family.
Serves { msg_type: u8 },
/// The endpoint answered the opening request with a message from another
/// protocol's family.
WrongProtocol {
got: AppType,
msg_type: u8,
msg: AnyMessageOwned,
},
/// The opening request could not be sent, e.g. because the endpoint closed
/// the connection after `SetupConnection.Success`.
NotEstablished { reason: String },
/// No message from any protocol family arrived before the probe deadline.
NoResponse,
}

/// Sends the first client message of `app_type` and classifies the first
/// protocol-family message that follows it.
///
/// The probe assumes the caller already consumed a `SetupConnection.Success`.
/// Common and extension messages are ignored while waiting, and every read
/// shares one deadline so a chatty endpoint cannot keep the probe alive.
pub async fn probe_protocol(
client: &TestClient,
app_type: AppType,
user_identity: &str,
) -> Result<ProbeOutcome, ScenarioError> {
let request = opening_request(app_type, user_identity)?;
if let Err(e) = client.send(request).await {
return Ok(ProbeOutcome::NotEstablished {
reason: e.to_string(),
});
}

let deadline = tokio::time::Instant::now() + crate::client::DEFAULT_MSG_TIMEOUT;
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Ok(ProbeOutcome::NoResponse);
}
let Some((msg_type, msg)) = client.next_from_server_within(remaining).await else {
return Ok(ProbeOutcome::NoResponse);
};
match app_type_of(&msg) {
Some(observed) if observed == app_type => {
return Ok(ProbeOutcome::Serves { msg_type });
}
Some(got) => {
return Ok(ProbeOutcome::WrongProtocol { got, msg_type, msg });
}
None => continue,
}
}
}

/// Builds the first client message a well-behaved client sends for
/// `app_type` after `SetupConnection.Success`.
pub fn opening_request(
app_type: AppType,
user_identity: &str,
) -> Result<AnyMessageOwned, ScenarioError> {
Ok(match app_type {
AppType::MiningServer => AnyMessageOwned::Mining(MiningOwned::OpenStandardMiningChannel(
OpenStandardMiningChannelOwned {
request_id: PROBE_REQUEST_ID,
user_identity: str0255(user_identity)?,
nominal_hash_rate: 1_000_000.0,
max_target: [0xff_u8; 32].into(),
},
)),
AppType::JobDeclarationServer => AnyMessageOwned::JobDeclaration(
JobDeclarationOwned::AllocateMiningJobToken(AllocateMiningJobTokenOwned {
user_identifier: str0255(user_identity)?,
request_id: PROBE_REQUEST_ID,
}),
),
AppType::TemplateProvider => AnyMessageOwned::TemplateDistribution(
TemplateDistributionOwned::CoinbaseOutputConstraints(CoinbaseOutputConstraintsOwned {
coinbase_output_max_additional_size: 0,
coinbase_output_max_additional_sigops: 0,
}),
),
})
}

/// The message a probe sends for `app_type`.
pub fn opening_request_name(app_type: AppType) -> &'static str {
match app_type {
AppType::MiningServer => "OpenStandardMiningChannel",
AppType::JobDeclarationServer => "AllocateMiningJobToken",
AppType::TemplateProvider => "CoinbaseOutputConstraints",
}
}

/// The spec section that requires the server to answer the first client
/// message of `app_type`, or `None` when the spec does not mandate a reply.
pub fn first_response_requirement(app_type: AppType) -> Option<&'static str> {
match app_type {
AppType::MiningServer => Some(
"§5.3.2: the server MUST accept the target or respond with OpenMiningChannel.Error",
),
AppType::JobDeclarationServer => None,
AppType::TemplateProvider => {
Some("§7: the server MUST immediately reply with a NewTemplate")
}
}
}

/// The app type whose protocol family `msg` belongs to, if it belongs to one.
pub fn app_type_of(msg: &AnyMessageOwned) -> Option<AppType> {
match msg {
AnyMessageOwned::Mining(_) => Some(AppType::MiningServer),
AnyMessageOwned::JobDeclaration(_) => Some(AppType::JobDeclarationServer),
AnyMessageOwned::TemplateDistribution(_) => Some(AppType::TemplateProvider),
AnyMessageOwned::Common(_) | AnyMessageOwned::Extensions(_) => None,
}
}

fn str0255(value: &str) -> Result<Str0255Owned, ScenarioError> {
value.to_string().try_into().map_err(|_| {
ScenarioError::Failed(format!(
"user_identity ({} bytes) does not fit in a STR0_255 field",
value.len()
))
})
}
Loading
Loading