diff --git a/COVERAGE.md b/COVERAGE.md index 1cc8732..0e33ce7 100644 --- a/COVERAGE.md +++ b/COVERAGE.md @@ -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` | @@ -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 | ❌ | diff --git a/src/app_type.rs b/src/app_type.rs index d3780e5..28c2e15 100644 --- a/src/app_type.rs +++ b/src/app_type.rs @@ -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, @@ -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 { @@ -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, - } - } } diff --git a/src/client.rs b/src/client.rs index b88dc08..64f85ca 100644 --- a/src/client.rs +++ b/src/client.rs @@ -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`. diff --git a/src/lib.rs b/src/lib.rs index 4118bfd..c54598f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/probe.rs b/src/probe.rs new file mode 100644 index 0000000..9ef296e --- /dev/null +++ b/src/probe.rs @@ -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 { + 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 { + 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 { + 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 { + value.to_string().try_into().map_err(|_| { + ScenarioError::Failed(format!( + "user_identity ({} bytes) does not fit in a STR0_255 field", + value.len() + )) + }) +} diff --git a/src/scenarios/common/setup_connection.rs b/src/scenarios/common/setup_connection.rs index 764416f..723a822 100644 --- a/src/scenarios/common/setup_connection.rs +++ b/src/scenarios/common/setup_connection.rs @@ -3,11 +3,15 @@ //! Covers catalog rows C-SC-*, C-SCS-*, C-SCE-*. use integration_tests_sv2::mock_roles::WithSetup; -use stratum_apps::stratum_core::parsers_sv2::{AnyMessageOwned, CommonMessagesOwned}; +use stratum_apps::stratum_core::parsers_sv2::{ + message_type_to_name, AnyMessageOwned, CommonMessagesOwned, +}; use crate::{ - client::{setup_connection, TestClient}, + app_type::AppType, + client::{setup_connection, TestClient, DEFAULT_MSG_TIMEOUT}, endpoint::Endpoint, + probe::{self, ProbeOutcome}, scenarios::ScenarioError, }; @@ -110,36 +114,133 @@ pub async fn unsupported_version_rejected(endpoint: Endpoint) -> ScenarioResult } // --------------------------------------------------------------------------- -// C-SC-7 — unsupported protocol rejected +// C-SC-7 — accepted protocol is actually served // --------------------------------------------------------------------------- -/// The endpoint MUST reject a `SetupConnection` for a sub-protocol it does -/// not serve with a framed `SetupConnectionError`. +/// The endpoint MUST reject a `SetupConnection` for a sub-protocol it does not +/// serve with a framed `SetupConnectionError` (§3.6.1). Because a `.Success` +/// alone does not show whether the endpoint serves the protocol, the scenario +/// sends that protocol's first client message and classifies the answer. /// /// Covers: C-SC-7 pub async fn unsupported_protocol_rejected(endpoint: Endpoint) -> ScenarioResult { - let setup = setup_connection(endpoint.app_type.wrong_protocol(), 2, 2, 0); - let client = TestClient::connect_with_setup(&endpoint, WithSetup::Yes(setup)).await?; + let mut details = Vec::new(); + let mut failed = false; + let mut inconclusive = false; - // Take whatever the endpoint answers first: a `.Success` is the violation - // and must fail right away, not after the message timeout. - match client.next_from_server().await? { - (_, AnyMessageOwned::Common(CommonMessagesOwned::SetupConnectionError(m))) => Ok(Some( - format!("error_code=\"{}\"", m.error_code.as_utf8_or_hex()), - )), - (_, AnyMessageOwned::Common(CommonMessagesOwned::SetupConnectionSuccess(m))) => { - Err(format!( - "endpoint accepted the SetupConnection with used_version={}", - m.used_version - ) - .into()) + for probed in AppType::ALL + .into_iter() + .filter(|app_type| *app_type != endpoint.app_type) + { + match probe_endpoint(&endpoint, probed).await { + ProbeReport::Pass(detail) => details.push(detail), + ProbeReport::Fail(detail) => { + failed = true; + details.push(detail); + } + ProbeReport::Inconclusive(detail) => { + inconclusive = true; + details.push(detail); + } + } + } + + let detail = details.join("; "); + if failed { + Err(ScenarioError::Failed(detail)) + } else if inconclusive { + Err(ScenarioError::NotExercised(detail)) + } else { + Ok(Some(detail)) + } +} + +/// How one protocol probe contributed to the scenario's outcome. +enum ProbeReport { + Pass(String), + Fail(String), + Inconclusive(String), +} + +/// Opens a connection for `probed`, reads its `SetupConnection` response, and +/// probes the protocol when the endpoint accepted it. +async fn probe_endpoint(endpoint: &Endpoint, probed: AppType) -> ProbeReport { + let label = protocol_label(probed); + let setup = setup_connection(probed.protocol(), 2, 2, probed.default_flags()); + let client = match TestClient::connect_with_setup(endpoint, WithSetup::Yes(setup)).await { + Ok(client) => client, + Err(e) => { + return ProbeReport::Inconclusive(format!("{label}: probe connection failed: {e}")) } - (msg_type, other) => { - Err(format!("expected SetupConnectionError, got type 0x{msg_type:02x}: {other}").into()) + }; + + let (msg_type, msg) = match client.next_from_server().await { + Ok(msg) => msg, + Err(e) => { + return ProbeReport::Inconclusive(format!("{label}: no SetupConnection response: {e}")) } + }; + + let used_version = match msg { + AnyMessageOwned::Common(CommonMessagesOwned::SetupConnectionError(m)) => { + return ProbeReport::Pass(format!( + "{label} rejected (error_code=\"{}\")", + m.error_code.as_utf8_or_hex() + )) + } + AnyMessageOwned::Common(CommonMessagesOwned::SetupConnectionSuccess(m)) => m.used_version, + other => { + return ProbeReport::Inconclusive(format!( + "{label}: expected SetupConnection.Success or SetupConnection.Error, got type 0x{msg_type:02x}: {other}" + )) + } + }; + + match probe::probe_protocol(&client, probed, &endpoint.user_identity).await { + Ok(ProbeOutcome::Serves { msg_type }) => ProbeReport::Pass(format!( + "{label} also served (used_version={used_version}, reply {})", + message_type_to_name(msg_type) + )), + Ok(ProbeOutcome::WrongProtocol { + got, + msg_type, + msg, + }) => ProbeReport::Fail(format!( + "{label} accepted but answered {} with a {} message (type 0x{msg_type:02x}: {msg})", + probe::opening_request_name(probed), + got.name() + )), + Ok(ProbeOutcome::NotEstablished { reason }) => ProbeReport::Inconclusive(format!( + "{label} accepted but the probe could not be sent: {reason}" + )), + Ok(ProbeOutcome::NoResponse) => match probe::first_response_requirement(probed) { + Some(requirement) => ProbeReport::Fail(format!( + "{label} accepted but did not answer {} within {:?}; either it does not serve the protocol and should have sent SetupConnection.Error (§3.6.1), or it failed the requirement: {requirement}", + probe::opening_request_name(probed), + DEFAULT_MSG_TIMEOUT + )), + None => ProbeReport::Inconclusive(format!( + "{label} accepted but sent no {} response to {} within {:?}; §6.4.2 rate-limits this request and leaves `user_identifier` restrictions to the server, so whether the endpoint serves {} could not be determined", + probed.name(), + probe::opening_request_name(probed), + DEFAULT_MSG_TIMEOUT, + probed.name() + )), + }, + Err(e) => ProbeReport::Inconclusive(format!( + "{label} accepted but the probe could not run: {e}" + )), } } +fn protocol_label(app_type: AppType) -> String { + format!( + "protocol={} ({})", + app_type.protocol() as u8, + app_type.name() + ) +} + // --------------------------------------------------------------------------- // registry entries for this module // --------------------------------------------------------------------------- diff --git a/tests/c_sc_7_probe.rs b/tests/c_sc_7_probe.rs new file mode 100644 index 0000000..80dc60a --- /dev/null +++ b/tests/c_sc_7_probe.rs @@ -0,0 +1,248 @@ +//! C-SC-7 against mock endpoints with different protocol deployments. + +use integration_tests_sv2::utils::{create_downstream, get_available_address, message_from_frame}; +use interoperability_tests_sv2::{ + app_type::AppType, + endpoint::Endpoint, + scenarios::{ + common::setup_connection::unsupported_protocol_rejected, ScenarioError, ScenarioResult, + }, +}; +use stratum_apps::{ + stratum_core::{ + common_messages_sv2::{ + SetupConnectionErrorOwned, SetupConnectionSuccessOwned, + ERROR_CODE_SETUP_CONNECTION_UNSUPPORTED_PROTOCOL, + }, + job_declaration_sv2::AllocateMiningJobTokenSuccessOwned, + mining_sv2::OpenMiningChannelErrorOwned, + parsers_sv2::{ + AnyMessageOwned, CommonMessagesOwned, JobDeclarationOwned, MiningOwned, + TemplateDistributionOwned, + }, + template_distribution_sv2::SetNewPrevHashOwned, + }, + utils::types::OutboundFrame, +}; +use tokio::net::{TcpListener, TcpStream}; + +#[derive(Clone, Copy)] +enum Reply { + Serves, + Silent, + WrongFamily, +} + +#[tokio::test] +async fn passes_when_other_protocols_are_rejected() { + let result = run(vec![], Reply::Silent).await; + let detail = result.expect("rejections pass").expect("pass detail"); + assert!(detail.contains("protocol=1"), "{detail}"); + assert!(detail.contains("protocol=2"), "{detail}"); + assert!(detail.contains("rejected"), "{detail}"); +} + +#[tokio::test] +async fn passes_when_endpoint_also_serves_job_declaration() { + let result = run(vec![1], Reply::Serves).await; + let detail = result + .expect("multi-protocol endpoint passes") + .expect("pass detail"); + assert!(detail.contains("protocol=1"), "{detail}"); + assert!(detail.contains("also served"), "{detail}"); + assert!(detail.contains("protocol=2"), "{detail}"); + assert!(detail.contains("rejected"), "{detail}"); +} + +#[tokio::test] +async fn passes_when_endpoint_serves_both_other_protocols() { + let result = run(vec![1, 2], Reply::Serves).await; + let detail = result + .expect("multi-protocol endpoint passes") + .expect("pass detail"); + assert_eq!(detail.matches("also served").count(), 2, "{detail}"); +} + +#[tokio::test] +async fn job_declaration_silence_is_not_exercised() { + match run(vec![1], Reply::Silent).await { + Err(ScenarioError::NotExercised(reason)) => { + assert!(reason.contains("protocol=1"), "{reason}"); + assert!(reason.contains("Job Declaration"), "{reason}"); + // The Template Distribution probe still rejects the endpoint. + assert!(reason.contains("protocol=2"), "{reason}"); + } + other => panic!("expected a not-exercised result, got {other:?}"), + } +} + +#[tokio::test] +async fn template_distribution_silence_is_a_failure() { + match run(vec![2], Reply::Silent).await { + Err(ScenarioError::Failed(reason)) => { + assert!(reason.contains("protocol=2"), "{reason}"); + assert!(reason.contains("CoinbaseOutputConstraints"), "{reason}"); + } + other => panic!("expected a failed result, got {other:?}"), + } +} + +#[tokio::test] +async fn wrong_protocol_family_is_a_failure() { + match run(vec![1], Reply::WrongFamily).await { + Err(ScenarioError::Failed(reason)) => { + assert!(reason.contains("protocol=1"), "{reason}"); + assert!(reason.contains("Mining Protocol"), "{reason}"); + } + other => panic!("expected a failed result, got {other:?}"), + } +} + +#[tokio::test] +async fn job_declaration_target_probes_mining_and_template_distribution() { + let result = run_as(AppType::JobDeclarationServer, vec![0, 2], Reply::Serves).await; + let detail = result + .expect("multi-protocol endpoint passes") + .expect("pass detail"); + assert_eq!(detail.matches("also served").count(), 2, "{detail}"); + assert!(detail.contains("protocol=0"), "{detail}"); + assert!(detail.contains("protocol=2"), "{detail}"); +} + +async fn run(accepted: Vec, reply: Reply) -> ScenarioResult { + run_as(AppType::MiningServer, accepted, reply).await +} + +async fn run_as(app_type: AppType, accepted: Vec, reply: Reply) -> ScenarioResult { + let listener = TcpListener::bind(get_available_address()) + .await + .expect("the mock endpoint's address is available"); + let addr = listener + .local_addr() + .expect("the mock endpoint has an address"); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + break; + }; + let accepted = accepted.clone(); + tokio::spawn(serve(stream, accepted, reply)); + } + }); + + let endpoint = Endpoint { + addr, + app_type, + user_identity: "interoperability_tests_sv2".to_string(), + }; + unsupported_protocol_rejected(endpoint).await +} + +async fn serve(stream: TcpStream, accepted: Vec, reply: Reply) { + let Some((receiver, sender)) = create_downstream(stream).await else { + return; + }; + while let Ok(mut frame) = receiver.recv().await { + let (_, msg) = message_from_frame(&mut frame); + for response in respond(msg, &accepted, reply) { + if sender.send(response).await.is_err() { + return; + } + } + } +} + +fn respond(msg: AnyMessageOwned, accepted: &[u8], reply: Reply) -> Vec { + match msg { + AnyMessageOwned::Common(CommonMessagesOwned::SetupConnection(m)) => { + if accepted.contains(&(m.protocol as u8)) { + vec![setup_success()] + } else { + vec![setup_error()] + } + } + AnyMessageOwned::Mining(MiningOwned::OpenStandardMiningChannel(_)) => match reply { + Reply::Serves => vec![mining_reply()], + Reply::Silent => vec![], + Reply::WrongFamily => vec![job_declaration_reply()], + }, + AnyMessageOwned::JobDeclaration(JobDeclarationOwned::AllocateMiningJobToken(_)) => { + match reply { + Reply::Serves => vec![job_declaration_reply()], + Reply::Silent => vec![], + Reply::WrongFamily => vec![mining_reply()], + } + } + AnyMessageOwned::TemplateDistribution( + TemplateDistributionOwned::CoinbaseOutputConstraints(_), + ) => match reply { + Reply::Serves => vec![template_distribution_reply()], + Reply::Silent => vec![], + Reply::WrongFamily => vec![mining_reply()], + }, + _ => vec![], + } +} + +fn setup_success() -> OutboundFrame { + frame(AnyMessageOwned::Common( + CommonMessagesOwned::SetupConnectionSuccess(SetupConnectionSuccessOwned { + used_version: 2, + flags: 0, + }), + )) +} + +fn setup_error() -> OutboundFrame { + frame(AnyMessageOwned::Common( + CommonMessagesOwned::SetupConnectionError(SetupConnectionErrorOwned { + flags: 0, + error_code: ERROR_CODE_SETUP_CONNECTION_UNSUPPORTED_PROTOCOL + .to_string() + .try_into() + .expect("the error code fits in STR0_255"), + }), + )) +} + +fn mining_reply() -> OutboundFrame { + frame(AnyMessageOwned::Mining( + MiningOwned::OpenMiningChannelError(OpenMiningChannelErrorOwned { + request_id: 1, + error_code: "probe" + .to_string() + .try_into() + .expect("the error code fits in STR0_255"), + }), + )) +} + +fn job_declaration_reply() -> OutboundFrame { + frame(AnyMessageOwned::JobDeclaration( + JobDeclarationOwned::AllocateMiningJobTokenSuccess(AllocateMiningJobTokenSuccessOwned { + request_id: 1, + mining_job_token: Vec::::new() + .try_into() + .expect("an empty token fits in B0_255"), + coinbase_outputs: Vec::::new() + .try_into() + .expect("empty outputs fit in B0_64K"), + }), + )) +} + +fn template_distribution_reply() -> OutboundFrame { + frame(AnyMessageOwned::TemplateDistribution( + TemplateDistributionOwned::SetNewPrevHash(SetNewPrevHashOwned { + template_id: 0, + prev_hash: [0_u8; 32].into(), + ntime_start: 0, + n_bits: 0, + target: [0_u8; 32].into(), + }), + )) +} + +fn frame(message: AnyMessageOwned) -> OutboundFrame { + OutboundFrame::from_message(message).expect("the message can be framed") +}