diff --git a/Cargo.lock b/Cargo.lock index 58a34da8dd..20c9ec80fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1162,7 +1162,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" dependencies = [ "binary_sv2", "bitcoin", @@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "stratum_translation" -version = "0.6.0" +version = "0.7.0" dependencies = [ "binary_sv2", "bitcoin", @@ -1203,16 +1203,15 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sv1_api" -version = "7.0.0" +version = "8.0.0" dependencies = [ "binary_sv2", "bitcoin", - "byteorder", "quickcheck", "quickcheck_macros", "serde", "serde_json", - "tracing", + "trait-variant", ] [[package]] diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 79d118bb53..0e3227182c 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -101,12 +101,6 @@ dependencies = [ name = "buffer_sv2" version = "4.0.0" -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "cc" version = "1.2.63" @@ -162,7 +156,7 @@ dependencies = [ [[package]] name = "codec_sv2" -version = "8.0.0" +version = "8.1.0" dependencies = [ "binary_sv2", "buffer_sv2", @@ -371,24 +365,12 @@ dependencies = [ "zeroize", ] -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - [[package]] name = "opaque-debug" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - [[package]] name = "poly1305" version = "0.8.0" @@ -480,7 +462,7 @@ version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" dependencies = [ - "bitcoin_hashes 0.13.1", + "bitcoin_hashes 0.14.100", "secp256k1-sys 0.10.1", ] @@ -559,14 +541,13 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sv1_api" -version = "7.0.0" +version = "8.0.0" dependencies = [ "binary_sv2", "bitcoin", - "byteorder", "serde", "serde_json", - "tracing", + "trait-variant", ] [[package]] @@ -588,36 +569,16 @@ dependencies = [ ] [[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" +name = "trait-variant" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +checksum = "b19a4867a870f6edc4c283f2b455804b1879c0baf0e642f26b03ed8ee262d9d3" dependencies = [ "proc-macro2", "quote", "syn", ] -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - [[package]] name = "typenum" version = "1.20.1" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index ac0087a196..5745a073dd 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -27,7 +27,7 @@ template_distribution_sv2 = { path = "../sv2/subprotocols/template-distribution" secp256k1 = { version = "0.28.2", default-features = false, features = ["alloc", "rand"] } rand = { version = "0.8.5", default-features = false } sv1_api = { path = "../sv1" } -serde_json = { version = "1.0.64", default-features = false, features = ["alloc"] } +serde_json = { version = "1.0.64", default-features = false, features = ["alloc", "float_roundtrip"] } [[bin]] name = "deserialize_sv2frame" diff --git a/fuzz/fuzz_targets/fuzz_sv1_method_parsers.rs b/fuzz/fuzz_targets/fuzz_sv1_method_parsers.rs index e7e768ff7b..781a67a73c 100644 --- a/fuzz/fuzz_targets/fuzz_sv1_method_parsers.rs +++ b/fuzz/fuzz_targets/fuzz_sv1_method_parsers.rs @@ -9,13 +9,8 @@ use arbitrary::{Arbitrary, Unstructured}; use libfuzzer_sys::fuzz_target; use serde_json::Value; use sv1_api::{ - client_to_server::{Authorize, Configure as C2SConfigure, Submit, Subscribe as C2SSubscribe}, - json_rpc::{Notification, Response, StandardRequest}, - methods::Server2ClientResponse, - server_to_client::{ - Configure as S2CConfigure, GeneralResponse, Notify, SetDifficulty, SetExtranonce, - SetVersionMask, Subscribe as S2CSubscribe, - }, + json_rpc::{Request, Response}, + ClientToServer, Id, Method, ServerToClient, }; fn gen_edge_number(u: &mut Unstructured<'_>) -> arbitrary::Result { @@ -145,6 +140,22 @@ enum ParserTarget { Generic, } +fn client_request(id: u64, method: Method, params: Value) { + let _ = ClientToServer::try_from(Request { + id: Some(Id::from(id)), + method, + params, + }); +} + +fn notification(method: Method, params: Value) { + let _ = ServerToClient::try_from(Request { + id: None, + method, + params, + }); +} + fuzz_target!(|data: &[u8]| { let mut u = Unstructured::new(data); let Ok(target) = u.arbitrary::() else { @@ -157,123 +168,68 @@ fuzz_target!(|data: &[u8]| { match target { ParserTarget::Submit => { if let Ok(params) = gen_submit_params(&mut u) { - let _ = Submit::try_from(StandardRequest { - id, - method: String::new(), - params, - }); + client_request(id, Method::Submit, params); } } ParserTarget::Authorize => { if let Ok(params) = gen_authorize_params(&mut u) { - let _ = Authorize::try_from(StandardRequest { - id, - method: String::new(), - params, - }); + client_request(id, Method::Authorize, params); } } ParserTarget::Subscribe => { if let Ok(params) = gen_subscribe_params(&mut u) { - let _ = C2SSubscribe::try_from(StandardRequest { - id, - method: String::new(), - params, - }); + client_request(id, Method::Subscribe, params); } } ParserTarget::Configure => { if let Ok(params) = gen_configure_params(&mut u) { - let _ = C2SConfigure::try_from(StandardRequest { - id, - method: String::new(), - params, - }); + client_request(id, Method::Configure, params); } } ParserTarget::Notify => { if let Ok(params) = gen_notify_params(&mut u) { - let _ = Notify::try_from(Notification { - method: String::new(), - params, - }); + notification(Method::Notify, params); } } ParserTarget::SetDifficulty => { if let Ok(params) = gen_set_difficulty_params(&mut u) { - let _ = SetDifficulty::try_from(Notification { - method: String::new(), - params, - }); + notification(Method::SetDifficulty, params); } } ParserTarget::SetExtranonce => { if let Ok(params) = gen_set_extranonce_params(&mut u) { - let _ = SetExtranonce::try_from(Notification { - method: String::new(), - params, - }); + notification(Method::SetExtranonce, params); } } ParserTarget::SetVersionMask => { if let Ok(params) = gen_set_version_mask_params(&mut u) { - let _ = SetVersionMask::try_from(Notification { - method: String::new(), - params, - }); + notification(Method::SetVersionMask, params); } } ParserTarget::Generic => { if let Ok(params) = common::gen_json_value(&mut u, 5) { - let _ = Submit::try_from(StandardRequest { - id: 1, - method: String::new(), - params: params.clone(), - }); - let _ = Authorize::try_from(StandardRequest { - id: 2, - method: String::new(), - params: params.clone(), - }); - let _ = C2SSubscribe::try_from(StandardRequest { - id: 3, - method: String::new(), - params: params.clone(), - }); - let _ = C2SConfigure::try_from(StandardRequest { - id: 4, - method: String::new(), - params: params.clone(), - }); - let _ = Notify::try_from(Notification { - method: String::new(), - params: params.clone(), - }); - let _ = SetDifficulty::try_from(Notification { - method: String::new(), - params: params.clone(), - }); - let _ = SetExtranonce::try_from(Notification { - method: String::new(), - params: params.clone(), - }); - let _ = SetVersionMask::try_from(Notification { - method: String::new(), - params: params.clone(), - }); - let resp = Response { - id: 5, - error: None, - result: params.clone(), - }; - let _ = S2CSubscribe::try_from(&resp); - let _ = S2CConfigure::try_from(&resp); - let _ = GeneralResponse::try_from(&resp); - let _ = Server2ClientResponse::try_from(Response { - id: 6, - error: None, - result: params, - }); + for method in [ + Method::Submit, + Method::Authorize, + Method::Subscribe, + Method::Configure, + Method::ExtranonceSubscribe, + Method::SuggestDifficulty, + ] { + client_request(id, method, params.clone()); + } + for method in [ + Method::Notify, + Method::SetDifficulty, + Method::SetExtranonce, + Method::SetVersionMask, + ] { + notification(method, params.clone()); + } + let response = Response::success(Id::from(id), params); + let _ = ServerToClient::from_response(&response, &Method::Subscribe); + let _ = ServerToClient::from_response(&response, &Method::Configure); + let _ = ServerToClient::from_response(&response, &Method::Submit); } } } diff --git a/fuzz/fuzz_targets/fuzz_sv1_wire.rs b/fuzz/fuzz_targets/fuzz_sv1_wire.rs index 523d4402ae..0f64de7181 100644 --- a/fuzz/fuzz_targets/fuzz_sv1_wire.rs +++ b/fuzz/fuzz_targets/fuzz_sv1_wire.rs @@ -8,8 +8,8 @@ use arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; use serde_json::Value; use sv1_api::{ - json_rpc::{JsonRpcError, Message, Notification, Response, StandardRequest}, - methods::{Client2Server, Method, Server2Client, Server2ClientResponse}, + json_rpc::{Request, Response}, + ClientToServer, Id, Message, Method, RpcError, ServerToClient, }; #[derive(Debug)] @@ -23,7 +23,7 @@ impl<'a> Arbitrary<'a> for ArbJson { #[derive(Arbitrary, Debug)] enum MsgKind { - StandardRequest, + Request, Notification, OkResponse, ErrorResponse, @@ -32,6 +32,7 @@ enum MsgKind { #[derive(Arbitrary, Debug)] struct FuzzInput { id: u64, + string_id: Option, method: String, params: ArbJson, result: ArbJson, @@ -42,83 +43,89 @@ struct FuzzInput { impl From for Message { fn from(fi: FuzzInput) -> Self { + let id = fi.string_id.map_or(Id::from(fi.id), Id::from); match fi.kind { - MsgKind::StandardRequest => Message::StandardRequest(StandardRequest { - id: fi.id, - method: fi.method, + MsgKind::Request => Message::Request(Request { + id: Some(id), + method: Method::from(fi.method), params: fi.params.0, }), - MsgKind::Notification => Message::Notification(Notification { - method: fi.method, + MsgKind::Notification => Message::Request(Request { + id: None, + method: Method::from(fi.method), params: fi.params.0, }), - MsgKind::OkResponse => Message::OkResponse(Response { - id: fi.id, - error: None, - result: fi.result.0, - }), - MsgKind::ErrorResponse => Message::ErrorResponse(Response { - id: fi.id, - error: Some(JsonRpcError { + MsgKind::OkResponse => Message::Response(Response::success(id, fi.result.0)), + MsgKind::ErrorResponse => Message::Response(Response::failure( + Some(id), + RpcError { code: fi.error_code, message: fi.error_message, data: None, - }), - result: fi.result.0, - }), + }, + )), } } } +fn round_trip(message: Message) { + let line = serde_json::to_string(&message).expect("messages always serialize"); + let decoded = Message::decode(&line).expect("serialized messages always decode"); + assert_eq!(decoded, message); +} + fn test_msg_conversions(msg: Message) { let _ = format!("{}", msg); let _ = format!("{:?}", msg); - if let Ok(m) = Client2Server::try_from(msg.clone()) { - let _ = format!("{:?}", m); - if let Ok(m) = Method::try_from(msg.clone()) { - let _ = format!("{:?}", m); - } - } - - if let Ok(m) = Server2ClientResponse::try_from(msg.clone()) { - let _ = format!("{:?}", m); - if let Ok(m) = Method::try_from(msg.clone()) { - let _ = format!("{:?}", m); + match msg { + Message::Request(request) => { + if let Ok(m) = ClientToServer::try_from(request.clone()) { + let _ = format!("{:?}", m); + let line = serde_json::to_string(&Message::from(m)).unwrap(); + if let Ok(Message::Request(again)) = Message::decode(&line) { + ClientToServer::try_from(again).expect("encoded requests always decode"); + } + } + if let Ok(m) = ServerToClient::try_from(request) { + let _ = format!("{:?}", m); + let line = serde_json::to_string(&Message::from(m.clone())).unwrap(); + if let Ok(Message::Request(again)) = Message::decode(&line) { + let again = ServerToClient::try_from(again) + .expect("encoded notifications always decode"); + assert_eq!(again, m); + } + } } - } - - if let Ok(m) = Server2Client::try_from(msg.clone()) { - let _ = format!("{:?}", m); - if let Ok(m) = Method::try_from(msg.clone()) { - let _ = format!("{:?}", m); - } - } - - if matches!(&msg, Message::ErrorResponse(_)) { - if let Ok(Method::ErrorMessage(m)) = Method::try_from(msg) { - let _ = format!("{:?}", m); + Message::Response(response) => { + let _ = ServerToClient::from_response(&response, &Method::Subscribe); + let _ = ServerToClient::from_response(&response, &Method::Configure); + let _ = ServerToClient::from_response(&response, &Method::Submit); } } } fuzz_target!(|data: &[u8]| { if let Ok(s) = std::str::from_utf8(data) { - if let Ok(msg) = serde_json::from_str::(s) { - test_msg_conversions(msg); + if let Ok(msg) = Message::decode(s) { + test_msg_conversions(msg.clone()); + round_trip(msg); } } if let Ok(val) = serde_json::from_slice::(data) { let _ = serde_json::from_value::(val); } if let Ok(input) = arbitrary::Unstructured::new(data).arbitrary::() { + // A string ID over 64 bytes can be built locally, but is rejected when decoding. + let oversized_id = !matches!(input.kind, MsgKind::Notification) + && input.string_id.as_ref().is_some_and(|id| id.len() > 64); let msg: Message = input.into(); - let msg_for_serde = msg.clone(); - - test_msg_conversions(msg); - - if let Ok(json) = serde_json::to_string(&msg_for_serde) { - let _ = serde_json::from_str::(&json); + test_msg_conversions(msg.clone()); + if oversized_id { + let line = serde_json::to_string(&msg).expect("messages always serialize"); + assert!(Message::decode(&line).is_err()); + } else { + round_trip(msg); } } }); diff --git a/stratum-core/Cargo.toml b/stratum-core/Cargo.toml index a04da46d3b..7467eef383 100644 --- a/stratum-core/Cargo.toml +++ b/stratum-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" @@ -25,8 +25,8 @@ common_messages_sv2 = { path = "../sv2/subprotocols/common-messages", version = mining_sv2 = { path = "../sv2/subprotocols/mining", version = "^13.0.0" } template_distribution_sv2 = { path = "../sv2/subprotocols/template-distribution", version = "^8.0.0" } job_declaration_sv2 = { path = "../sv2/subprotocols/job-declaration", version = "^11.0.0" } -sv1_api = { path = "../sv1", version = "^7.0.0", optional = true } -stratum_translation = { path = "stratum-translation", version = "^0.6.0", optional = true } +sv1_api = { path = "../sv1", version = "^8.0.0", optional = true } +stratum_translation = { path = "stratum-translation", version = "^0.7.0", optional = true } bitcoin = { workspace = true } [features] diff --git a/stratum-core/stratum-translation/Cargo.toml b/stratum-core/stratum-translation/Cargo.toml index eb3f1644b4..06bd4bf190 100644 --- a/stratum-core/stratum-translation/Cargo.toml +++ b/stratum-core/stratum-translation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stratum_translation" -version = "0.6.0" +version = "0.7.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Stratum V1 ↔ Stratum V2 translation utilities for reuse across proxies, apps, and firmware" @@ -13,7 +13,7 @@ path = "src/lib.rs" binary_sv2 = { path = "../../sv2/binary-sv2", version = "^8.0.0" } mining_sv2 = { path = "../../sv2/subprotocols/mining", version = "^13.0.0" } channels_sv2 = { path = "../../sv2/channels-sv2", version = "^9.0.0" } -v1 = { path = "../../sv1", package = "sv1_api", version = "^7.0.0" } +v1 = { path = "../../sv1", package = "sv1_api", version = "^8.0.0" } tracing = { workspace = true } bitcoin = { workspace = true } serde_json = { workspace = true } diff --git a/stratum-core/stratum-translation/src/sv1_to_sv2.rs b/stratum-core/stratum-translation/src/sv1_to_sv2.rs index 47e3d8997a..49f3c9d478 100644 --- a/stratum-core/stratum-translation/src/sv1_to_sv2.rs +++ b/stratum-core/stratum-translation/src/sv1_to_sv2.rs @@ -1,7 +1,7 @@ use crate::error::{Result, StratumTranslationError}; use bitcoin::Target; use mining_sv2::{OpenExtendedMiningChannelOwned, SubmitSharesExtendedOwned}; -use v1::{client_to_server, utils::HexU32Be}; +use v1::{utils::HexU32Be, Submit}; /// Builds an SV2 `OpenExtendedMiningChannel` message from the provided inputs. /// @@ -48,13 +48,13 @@ pub fn build_sv2_open_extended_mining_channel( /// * `Ok(SubmitSharesExtended)` if the conversion is successful. /// * `Err(())` if any required field is missing or conversion fails. pub fn build_sv2_submit_shares_extended_from_sv1_submit( - submit: &client_to_server::Submit, + submit: &Submit, channel_id: u32, sequence_number: u32, job_version: u32, version_rolling_mask: Option, ) -> Result { - let version = match (submit.version_bits.clone(), version_rolling_mask) { + let version = match (submit.version_bits, version_rolling_mask) { (Some(version_bits), Some(rolling_mask)) => { (job_version & !rolling_mask.0) | (version_bits.0 & rolling_mask.0) } @@ -62,7 +62,7 @@ pub fn build_sv2_submit_shares_extended_from_sv1_submit( _ => return Err(StratumTranslationError::IncompatibleVersionRollingMask), }; - let extranonce: Vec = submit.extra_nonce2.clone().into(); + let extranonce: Vec = submit.extranonce2.clone().into(); let submit_share_extended = SubmitSharesExtendedOwned { channel_id, sequence_number, @@ -71,7 +71,7 @@ pub fn build_sv2_submit_shares_extended_from_sv1_submit( .parse::() .map_err(|_| StratumTranslationError::InvalidJobId)?, nonce: submit.nonce.0, - ntime: submit.time.0, + ntime: submit.ntime.0, version, extranonce: extranonce .try_into() @@ -83,20 +83,16 @@ pub fn build_sv2_submit_shares_extended_from_sv1_submit( #[cfg(test)] mod tests { use super::*; - use v1::{ - client_to_server::Submit, - utils::{HexU32Be, VERSION_ROLLING_MASK}, - }; + use v1::utils::{HexU32Be, VERSION_ROLLING_MASK}; fn submit_template() -> Submit { Submit { - user_name: "w".to_string(), + worker_name: "w".to_string(), job_id: "1".to_string(), - extra_nonce2: v1::utils::Extranonce::try_from(vec![0, 1, 2, 3]).unwrap(), - time: HexU32Be(0), + extranonce2: v1::utils::Extranonce::try_from(vec![0, 1, 2, 3]).unwrap(), + ntime: HexU32Be(0), nonce: HexU32Be(0), version_bits: Some(HexU32Be(0)), - id: 0, } } diff --git a/stratum-core/stratum-translation/src/sv2_to_sv1.rs b/stratum-core/stratum-translation/src/sv2_to_sv1.rs index 57193473cf..fe239bde02 100644 --- a/stratum-core/stratum-translation/src/sv2_to_sv1.rs +++ b/stratum-core/stratum-translation/src/sv2_to_sv1.rs @@ -15,8 +15,9 @@ use mining_sv2::{NewExtendedMiningJobOwned, SetNewPrevHashOwned, SetTargetOwned} use serde_json::Value; use tracing::debug; use v1::{ - json_rpc, server_to_client, + json_rpc, utils::{HexU32Be, MerkleNode, PrevHash}, + Method, Notify, SetDifficulty, }; /// Builds an SV1 `mining.notify` message from SV2 messages. @@ -33,7 +34,7 @@ use v1::{ /// block is found). /// /// # Returns -/// * `Ok(server_to_client::Notify)` - The constructed SV1 mining.notify message. +/// * `Ok(Notify)` - The constructed SV1 mining.notify message. /// * `Err(StratumTranslationError)` - If BIP141 stripping or serialization fails. /// /// # Errors @@ -43,7 +44,7 @@ pub fn build_sv1_notify_from_sv2( new_prev_hash: SetNewPrevHashOwned, mut new_job: NewExtendedMiningJobOwned, clean_jobs: bool, -) -> Result { +) -> Result { if let Some((coinbase_tx_prefix_stripped, coinbase_tx_suffix_stripped)) = try_strip_bip141( new_job.coinbase_tx_prefix.as_bytes(), new_job.coinbase_tx_suffix.as_bytes(), @@ -60,13 +61,13 @@ pub fn build_sv1_notify_from_sv2( let job_id = new_job.job_id.to_string(); let prev_hash = PrevHash(new_prev_hash.prev_hash); - let coin_base1 = new_job.coinbase_tx_prefix.to_owned_bytes().into(); - let coin_base2 = new_job.coinbase_tx_suffix.to_owned_bytes().into(); + let coinbase1 = new_job.coinbase_tx_prefix.to_owned_bytes().into(); + let coinbase2 = new_job.coinbase_tx_suffix.to_owned_bytes().into(); let merkle_path = new_job.merkle_path.clone().into_inner(); let merkle_branch: Vec = merkle_path.into_iter().map(MerkleNode).collect(); let version = HexU32Be(new_job.version); - let bits = HexU32Be(new_prev_hash.nbits); - let time = HexU32Be( + let nbits = HexU32Be(new_prev_hash.nbits); + let ntime = HexU32Be( new_job .ntime_start .clone() @@ -74,18 +75,18 @@ pub fn build_sv1_notify_from_sv2( .unwrap_or(new_prev_hash.ntime_start), ); - let notify_response = server_to_client::Notify { + let notify_response = Notify { job_id, prev_hash, - coin_base1, - coin_base2, + coinbase1, + coinbase2, merkle_branch, version, - bits, - time, + nbits, + ntime, clean_jobs, }; - debug!("\nNextMiningNotify: {}\n", notify_response); + debug!("\nNextMiningNotify: {:?}\n", notify_response); Ok(notify_response) } @@ -111,10 +112,14 @@ pub fn build_sv1_set_difficulty_from_sv2_set_target( /// /// # Returns /// * `Ok(json_rpc::Message)` - The constructed SV1 mining.set_difficulty message. +/// * `Err(InvalidSv1Difficulty)` - If the target gives a difficulty that is not finite and +/// positive, such as an all-zero target. pub fn build_sv1_set_difficulty_from_sv2_target(target: Target) -> Result { - let value = target.difficulty_float(); - let set_target = v1::methods::server_to_client::SetDifficulty { value }; - Ok(set_target.into()) + let difficulty = target.difficulty_float(); + if !difficulty.is_finite() || difficulty <= 0.0 { + return Err(StratumTranslationError::InvalidSv1Difficulty(difficulty)); + } + Ok(SetDifficulty { difficulty }.into()) } /// The SV1 difficulty selected by the integer power-of-two rounding policy. @@ -249,8 +254,9 @@ fn integer_power_of_two_sv1_difficulty_value_from_difficulty( } fn build_sv1_set_difficulty_notification(value: Value) -> json_rpc::Message { - json_rpc::Message::Notification(json_rpc::Notification { - method: "mining.set_difficulty".to_string(), + json_rpc::Message::Request(json_rpc::Request { + id: None, + method: Method::SetDifficulty, params: Value::Array(vec![value]), }) } @@ -271,8 +277,8 @@ mod tests { fn set_difficulty_value(msg: &json_rpc::Message) -> &Value { match msg { - json_rpc::Message::Notification(notif) => { - assert_eq!(notif.method, "mining.set_difficulty"); + json_rpc::Message::Request(notif) if notif.id.is_none() => { + assert_eq!(notif.method, Method::SetDifficulty); notif .params .as_array() @@ -289,14 +295,15 @@ mod tests { let msg = build_sv1_set_difficulty_from_sv2_target(dummy_target()) .expect("Should convert target to difficulty"); - // Check that we get a JSON-RPC Notification message - assert!(matches!(msg, v1::json_rpc::Message::Notification(_))); + assert!(set_difficulty_value(&msg).as_f64().unwrap() > 0.0); + } - if let v1::json_rpc::Message::Notification(notif) = msg { - assert_eq!(notif.method, "mining.set_difficulty"); - assert!(!notif.params.is_null()); - // Just verify it has parameters - detailed checking would require serde_json - } + #[test] + fn test_build_sv1_set_difficulty_rejects_zero_target() { + assert!(matches!( + build_sv1_set_difficulty_from_sv2_target(Target::from_le_bytes([0; 32])), + Err(StratumTranslationError::InvalidSv1Difficulty(_)) + )); } #[test] @@ -308,14 +315,7 @@ mod tests { let msg = build_sv1_set_difficulty_from_sv2_set_target(set_target) .expect("Should convert SetTarget to difficulty"); - // Verify the result is a proper JSON-RPC Notification message - assert!(matches!(msg, v1::json_rpc::Message::Notification(_))); - - if let v1::json_rpc::Message::Notification(notif) = msg { - assert_eq!(notif.method, "mining.set_difficulty"); - assert!(!notif.params.is_null()); - // Just verify it has parameters - detailed checking would require serde_json - } + assert!(set_difficulty_value(&msg).as_f64().unwrap() > 0.0); } #[test] @@ -512,7 +512,7 @@ mod tests { // Verify it uses prev_hash.ntime_start since job is future let notify = res.unwrap(); - assert_eq!(notify.time.0, 1746839904); + assert_eq!(notify.ntime.0, 1746839904); } #[test] @@ -565,11 +565,11 @@ mod tests { assert!(!notify.clean_jobs); // clean_jobs set to false assert_eq!(notify.merkle_branch.len(), 1); // One merkle node assert_eq!(notify.version.0, 536870912); - assert_eq!(notify.bits.0, 503543726); - assert_eq!(notify.time.0, 1746839905); // Should use job's ntime_start since not future + assert_eq!(notify.nbits.0, 503543726); + assert_eq!(notify.ntime.0, 1746839905); // Should use job's ntime_start since not future // Verify coinbase prefix and suffix are properly set - assert!(!notify.coin_base1.is_empty()); - assert!(!notify.coin_base2.is_empty()); + assert!(!notify.coinbase1.is_empty()); + assert!(!notify.coinbase2.is_empty()); } } diff --git a/sv1/Cargo.toml b/sv1/Cargo.toml index 33b1b3233c..10fbcb1821 100644 --- a/sv1/Cargo.toml +++ b/sv1/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sv1_api" -version = "7.0.0" +version = "8.0.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" @@ -16,10 +16,9 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"] [dependencies] binary_sv2 = { path = "../sv2/binary-sv2", version = "^8.0.0" } bitcoin = { workspace = true } -byteorder = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -tracing = { workspace = true } +trait-variant = { workspace = true } [dev-dependencies] quickcheck = { workspace = true } diff --git a/sv1/examples/client_and_server.rs b/sv1/examples/client_and_server.rs index 0cff7df98d..7d0d8aea3a 100644 --- a/sv1/examples/client_and_server.rs +++ b/sv1/examples/client_and_server.rs @@ -1,196 +1,77 @@ +//! An SV1 server and client talking over a local TCP connection for 30 seconds. +//! +//! The server sends a job every 5 seconds. The client configures version rolling, subscribes and +//! authorizes, then submits a share for the latest job every 2 seconds. It exits with an error +//! if no share was accepted. + use std::{ - convert::{TryFrom, TryInto}, + collections::HashMap, + convert::TryFrom, io::{BufRead, BufReader, Write}, - net::{SocketAddr, TcpListener, TcpStream}, + net::{TcpListener, TcpStream}, process::exit, - sync::{mpsc, Arc, Mutex}, + sync::mpsc::{self, RecvTimeoutError}, thread, - time::{Duration, SystemTime}, + time::{Duration, Instant}, }; -const ADDR: &str = "127.0.0.1:0"; -const TEST_DURATION: i32 = 30; - -type Receiver = mpsc::Receiver; -type Sender = mpsc::Sender; - use sv1_api::{ - client_to_server, error::Error, - json_rpc, server_to_client, - utils::{Extranonce, HexU32Be, MerkleNode, PrevHash}, - ClientStatus, IsClient, IsServer, Message, + utils::{Extranonce, HexBytes, HexU32Be, MerkleNode, PrevHash}, + Authorize, ClientToServer, Configure, ConfigureResult, Id, IsClient, IsServer, Message, Method, + Notify, Request, Response, RpcError, ServerToClient, SetDifficulty, SetExtranonce, + SetVersionMask, Submit, SubmitError, SubmitOutcome, Subscribe, SubscribeResult, + SuggestDifficulty, VersionRollingResult, }; -fn new_extranonce() -> Extranonce { - extranonce_from_hex("08000002") -} - -fn extranonce_from_hex(hex: &str) -> Extranonce { - let data = utils::decode_hex(hex).unwrap(); - Extranonce::try_from(data).expect("Failed to convert hex to U256") -} - -fn merklenode_from_hex(hex: &str) -> MerkleNode { - let data = utils::decode_hex(hex).unwrap(); - let len = data.len(); - if hex.len() >= 64 { - // panic if hex is larger than 32 bytes - MerkleNode::try_from(hex).expect("Failed to convert hex to U256") - } else { - // prepend hex with zeros so that it is 32 bytes - let mut new_vec = vec![0_u8; 32 - len]; - new_vec.extend(data.iter()); - MerkleNode::try_from(utils::encode_hex(&new_vec).as_str()) - .expect("Failed to convert hex to U256") - } -} - -fn prevhash_from_hex(hex: &str) -> PrevHash { - let data = utils::decode_hex(hex).unwrap(); - let len = data.len(); - if hex.len() >= 64 { - // panic if hex is larger than 32 bytes - PrevHash::try_from(hex).expect("Failed to convert hex to U256") - } else { - // prepend hex with zeros so that it is 32 bytes - let mut new_vec = vec![0_u8; 32 - len]; - new_vec.extend(data.iter()); - PrevHash::try_from(utils::encode_hex(&new_vec).as_str()) - .expect("Failed to convert hex to U256") - } -} - -fn new_extranonce2_size() -> usize { - 4 -} - -fn new_version_rolling_mask() -> HexU32Be { - HexU32Be(0xffffffff) -} -fn new_version_rolling_min() -> HexU32Be { - HexU32Be(0x00000000) -} - -struct Server { - authorized_names: Vec, - extranonce1: Extranonce, - extranonce2_size: usize, - version_rolling_mask: Option, - version_rolling_min_bit: Option, - receiver_incoming: Receiver, - sender_outgoing: Sender, -} - -fn server_pool_listen(listener: TcpListener) { - loop { - match listener.accept() { - Ok((stream, addr)) => { - println!("SERVER - Accepting from: {addr}"); - let server = Server::new(stream); - let _ = Arc::new(Mutex::new(server)); - } - Err(e) => { - eprintln!("SERVER - Accept error: {e}"); - break; - } - } - } -} - -impl Server { - pub fn new(stream: TcpStream) -> Arc> { - let (sender_incoming, receiver_incoming) = mpsc::channel::(); - let (sender_outgoing, receiver_outgoing) = mpsc::channel::(); - - let reader_stream = stream.try_clone().expect("Failed to clone stream (read)"); - let mut writer_stream = stream; - - // read thread - thread::spawn(move || { - let reader = BufReader::new(reader_stream); - for line in reader.lines().map_while(Result::ok) { - if sender_incoming.send(line).is_err() { - break; - } - } - }); - - thread::spawn(move || { - for msg in receiver_outgoing { - let _ = writer_stream.write_all(msg.as_bytes()); - } - }); - - let server = Server { - authorized_names: vec![], - extranonce1: extranonce_from_hex("00000000"), - extranonce2_size: 2, - version_rolling_mask: None, - version_rolling_min_bit: None, - receiver_incoming, - sender_outgoing, - }; - - let server_arc = Arc::new(Mutex::new(server)); - - { - let cloned = Arc::clone(&server_arc); - thread::spawn(move || loop { - if let Ok(mut self_) = cloned.try_lock() { - if let Ok(line) = self_.receiver_incoming.try_recv() { - println!("SERVER - message: {line}"); - let message: Result = serde_json::from_str(&line); - if let Ok(message) = message { - if let Ok(Some(resp)) = self_.handle_message(message) { - Self::send_message( - &self_.sender_outgoing, - json_rpc::Message::OkResponse(resp), - ); - } - } +const RUN_FOR: Duration = Duration::from_secs(30); +const JOB_INTERVAL: Duration = Duration::from_secs(5); +const SUBMIT_INTERVAL: Duration = Duration::from_secs(2); +const EXTRANONCE2_SIZE: usize = 4; +const WORKER: &str = "user"; + +/// Decodes newline-delimited messages from `stream` into a channel, and writes the messages sent +/// on the returned sender. +fn connect(stream: TcpStream) -> (mpsc::Receiver, mpsc::Sender) { + let (incoming_tx, incoming) = mpsc::channel(); + let reader = BufReader::new(stream.try_clone().expect("failed to clone the stream")); + thread::spawn(move || { + for line in reader.lines().map_while(Result::ok) { + match Message::decode(&line) { + Ok(message) => { + if incoming_tx.send(message).is_err() { + break; } } - thread::sleep(Duration::from_millis(100)); - }); + Err(e) => eprintln!("dropping line: {e}"), + } } + }); - { - let cloned = Arc::clone(&server_arc); - thread::spawn(move || { - let mut run_time = TEST_DURATION; - loop { - let notify_time = 5; - if let Ok(mut self_) = cloned.try_lock() { - let sender = self_.sender_outgoing.clone(); - if let Ok(notify_msg) = self_.notify(None) { - Server::send_message(&sender, notify_msg); - } - } - thread::sleep(Duration::from_secs(notify_time)); - run_time -= notify_time as i32; - - if run_time <= 0 { - println!("Test Success - ran for {TEST_DURATION} seconds"); - exit(0) - } - } - }); + let (outgoing, outgoing_rx) = mpsc::channel::(); + let mut writer = stream; + thread::spawn(move || { + for message in outgoing_rx { + let line = format!( + "{}\n", + serde_json::to_string(&message).expect("serializable") + ); + if writer.write_all(line.as_bytes()).is_err() { + break; + } } + }); + (incoming, outgoing) +} - server_arc - } - - fn handle_message( - &mut self, - _message: json_rpc::Message, - ) -> Result, Error> { - Ok(None) - } +struct Server { + outgoing: mpsc::Sender, + workers: Vec, +} - fn send_message(sender_outgoing: &Sender, msg: json_rpc::Message) { - let msg = format!("{}\n", serde_json::to_string(&msg).unwrap()); - let _ = sender_outgoing.send(msg); +impl Server { + fn reply(&self, response: impl Into) { + let _ = self.outgoing.send(response.into()); } } @@ -200,543 +81,365 @@ impl IsServer for Server { fn handle_configure( &mut self, _client_id: Option, - _request: &client_to_server::Configure, - ) -> Result<(Option, Option), Error> { - self.version_rolling_mask - .get_or_insert_with(new_version_rolling_mask); - self.version_rolling_min_bit - .get_or_insert_with(new_version_rolling_min); - - let mask = self.version_rolling_mask.as_ref().unwrap().clone(); - let min_bit = self.version_rolling_min_bit.as_ref().unwrap().clone(); - - Ok(( - Some(server_to_client::VersionRollingParams::new(mask, min_bit)), - Some(false), - )) + id: Id, + request: Configure, + ) -> Result<(), Error> { + let min_bit_count = request.version_rolling_min_bit_count().unwrap_or(0); + let result = ConfigureResult { + version_rolling: request + .version_rolling_mask() + .map(|mask| VersionRollingResult::new(mask, min_bit_count)), + minimum_difficulty: None, + }; + self.reply(Response::success(id, result)); + Ok(()) } fn handle_subscribe( - &self, - _client_id: Option, - _request: &client_to_server::Subscribe, - ) -> Result, Error> { - Ok(vec![]) - } - - fn handle_authorize( - &self, - _client_id: Option, - _request: &client_to_server::Authorize, - ) -> Result { - Ok(true) - } - - fn handle_submit( - &self, + &mut self, _client_id: Option, - _request: &client_to_server::Submit, - ) -> Result { - Ok(client_to_server::SubmitOutcome::Accepted) - } - - /// Indicates to the server that the client supports the mining.set_extranonce method. - fn handle_extranonce_subscribe(&mut self, _client_id: Option) -> Result<(), Error> { - Ok(()) - } - - fn is_authorized(&self, _client_id: Option, _name: &str) -> Result { - Ok(true) - } - - fn authorize(&mut self, _client_id: Option, name: &str) -> Result<(), Error> { - self.authorized_names.push(name.to_string()); + id: Id, + _request: Subscribe, + ) -> Result<(), Error> { + let result = SubscribeResult { + subscriptions: vec![("mining.notify".to_string(), "1".to_string())], + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).expect("4 bytes"), + extranonce2_size: EXTRANONCE2_SIZE, + }; + self.reply(Response::success(id, result)); Ok(()) } - /// Set extranonce1 to extranonce1 if provided. If not create a new one and set it. - fn set_extranonce1( + fn handle_authorize( &mut self, _client_id: Option, - extranonce1: Option, - ) -> Result { - self.extranonce1 = extranonce1.unwrap_or_else(new_extranonce); - Ok(self.extranonce1.clone()) - } - - fn extranonce1(&self, _client_id: Option) -> Result { - Ok(self.extranonce1.clone()) + id: Id, + request: Authorize, + ) -> Result<(), Error> { + self.workers.push(request.worker_name); + self.reply(Response::success(id, true)); + Ok(()) } - /// Set extranonce2_size to extranonce2_size if provided. If not create a new one and set it. - fn set_extranonce2_size( + /// Accepts every share from an authorized worker. + fn handle_submit( &mut self, _client_id: Option, - extra_nonce2_size: Option, - ) -> Result { - self.extranonce2_size = extra_nonce2_size.unwrap_or_else(new_extranonce2_size); - Ok(self.extranonce2_size) - } - - fn extranonce2_size(&self, _client_id: Option) -> Result { - Ok(self.extranonce2_size) - } - - fn version_rolling_mask(&self, _client_id: Option) -> Result, Error> { - Ok(self.version_rolling_mask.clone()) + id: Id, + request: Submit, + ) -> Result<(), Error> { + let outcome = if self.workers.contains(&request.worker_name) { + SubmitOutcome::Accepted + } else { + SubmitOutcome::Rejected(SubmitError::UnauthorizedWorker) + }; + self.reply(outcome.into_response(id)); + Ok(()) } - fn set_version_rolling_mask( + fn handle_extranonce_subscribe( &mut self, _client_id: Option, - mask: Option, + id: Id, ) -> Result<(), Error> { - self.version_rolling_mask = mask; + self.reply(Response::success(id, true)); Ok(()) } - fn set_version_rolling_min_bit( + fn handle_suggest_difficulty( &mut self, _client_id: Option, - mask: Option, + _id: Id, + _request: SuggestDifficulty, ) -> Result<(), Error> { - self.version_rolling_min_bit = mask; Ok(()) } - - fn notify(&mut self, _client_id: Option) -> Result { - let hex = "ffff"; - Ok(server_to_client::Notify { - job_id: "ciao".to_string(), - prev_hash: prevhash_from_hex(hex), - coin_base1: hex.try_into()?, - coin_base2: hex.try_into()?, - merkle_branch: vec![merklenode_from_hex(hex)], - version: HexU32Be(5667), - bits: HexU32Be(5678), - time: HexU32Be(5609), - clean_jobs: true, - } - .into()) - } } -struct Client { - client_id: u32, - extranonce1: Extranonce, - extranonce2_size: usize, - version_rolling_mask: Option, - version_rolling_min_bit: Option, - status: ClientStatus, - last_notify: Option, - sented_authorize_request: Vec<(u64, String)>, // (id, user_name) - authorized: Vec, - receiver_incoming: Receiver, - sender_outgoing: Sender, +fn job(id: u32) -> Notify { + Notify { + job_id: id.to_string(), + prev_hash: PrevHash::try_from("00".repeat(32).as_str()).expect("32 bytes"), + coinbase1: HexBytes::from(vec![1, 0, 0, 0]), + coinbase2: HexBytes::from(vec![0xff; 4]), + merkle_branch: vec![MerkleNode::try_from(vec![0; 32]).expect("32 bytes")], + version: HexU32Be(0x2000_0000), + nbits: HexU32Be(0x1705_ae3a), + ntime: HexU32Be(0x6470_25b5), + clean_jobs: true, + } } -impl Client { - pub fn new(client_id: u32, socket: SocketAddr) -> Arc> { - loop { - thread::sleep(Duration::from_secs(1)); - match TcpStream::connect(socket) { - Ok(st) => { - println!("CLIENT - connected to server at {socket}"); - let (sender_incoming, receiver_incoming) = mpsc::channel::(); - let (sender_outgoing, receiver_outgoing) = mpsc::channel::(); - - let reader_stream = st.try_clone().unwrap(); - let mut writer_stream = st; - - thread::spawn(move || { - let reader = BufReader::new(reader_stream); - for line in reader.lines().map_while(Result::ok) { - if sender_incoming.send(line).is_err() { - break; - } - } - }); - - thread::spawn(move || { - for msg in receiver_outgoing { - let _ = writer_stream.write_all(msg.as_bytes()); - } - }); - - let client = Client { - client_id, - extranonce1: extranonce_from_hex("00000000"), - extranonce2_size: 2, - version_rolling_mask: None, - version_rolling_min_bit: None, - status: ClientStatus::Init, - last_notify: None, - sented_authorize_request: vec![], - authorized: vec![], - receiver_incoming, - sender_outgoing, - }; - - let arc_client = Arc::new(Mutex::new(client)); - - { - let cloned = Arc::clone(&arc_client); - thread::spawn(move || loop { - if let Ok(mut this) = cloned.try_lock() { - if let Ok(line) = this.receiver_incoming.try_recv() { - println!("CLIENT {} - message: {}", this.client_id, line); - if let Ok(msg) = - serde_json::from_str::(&line) - { - this.handle_message(None, msg).ok(); - } - } - } - thread::sleep(Duration::from_millis(100)); - }); - } - - return arc_client; - } - Err(_) => { - println!("Server not ready... retry"); - continue; - } +fn serve(stream: TcpStream) { + let (incoming, outgoing) = connect(stream); + let jobs = outgoing.clone(); + thread::spawn(move || { + let _ = jobs.send(SetDifficulty { difficulty: 1.0 }.into()); + for id in 0.. { + if jobs.send(job(id).into()).is_err() { + break; } + thread::sleep(JOB_INTERVAL); } - } + }); - fn send_message(sender_outgoing: &Sender, msg: json_rpc::Message) { - let s = format!("{}\n", serde_json::to_string(&msg).unwrap()); - let _ = sender_outgoing.send(s); + let mut server = Server { + outgoing, + workers: vec![], + }; + for message in incoming { + println!("SERVER <- {message}"); + let Message::Request(request) = message else { + continue; + }; + match ClientToServer::try_from(request) { + Ok(request) => server + .handle_request(Some(0), request) + .expect("this server's handlers never fail"), + Err(e) => eprintln!("SERVER - {e}"), + } } +} - pub fn send_subscribe(&mut self) { - while let Ok(ClientStatus::Init) = self.status(None) { - thread::sleep(Duration::from_millis(100)); - } - let id = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - .as_secs(); - if let Ok(subscribe) = self.subscribe(None, id, None) { - Self::send_message(&self.sender_outgoing, subscribe); +struct Client { + outgoing: mpsc::Sender, + next_id: u64, + pending: HashMap, + extranonce2_size: Option, + mask: Option, + authorized: bool, + job_id: Option, + accepted: usize, +} + +impl Client { + fn new(outgoing: mpsc::Sender) -> Self { + Client { + outgoing, + next_id: 1, + pending: HashMap::new(), + extranonce2_size: None, + mask: None, + authorized: false, + job_id: None, + accepted: 0, } } - pub fn send_authorize(&mut self) { - let id = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - .as_secs(); - if let Ok(authorize) = self.authorize(None, id, "user".to_string(), "user".to_string()) { - Self::send_message(&self.sender_outgoing, authorize); - } + /// Records the request's method so its response can be routed, then sends it. + fn send

(&mut self, request: fn(Request

) -> ClientToServer, params: P) { + let id = Id::from(self.next_id); + self.next_id += 1; + let request = request(Request { + id: id.clone(), + params, + }); + self.pending.insert(id, request.method()); + let _ = self.outgoing.send(request.into()); } - pub fn send_submit(&mut self) { - let id = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - .as_secs(); - let extranonce2 = extranonce_from_hex("00"); - let nonce = 78; - let version_bits = None; - if let Ok(submit) = self.submit( - None, - id, - "user".to_string(), - extranonce2, - nonce, - nonce, - version_bits, - ) { - Self::send_message(&self.sender_outgoing, submit); - } + fn submit(&mut self) { + let (Some(size), Some(job_id), true) = + (self.extranonce2_size, self.job_id.clone(), self.authorized) + else { + return; + }; + let submit = Submit { + worker_name: WORKER.to_string(), + job_id, + extranonce2: Extranonce::try_from(vec![0; size]).expect("at most 32 bytes"), + ntime: HexU32Be(0x6470_25b5), + nonce: HexU32Be(78), + version_bits: self.mask.map(|mask| HexU32Be(0x2000 & mask.0)), + }; + self.send(ClientToServer::Submit, submit); } +} - pub fn send_configure(&mut self) { - let id = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - .as_secs(); - if let Ok(configure) = self.configure(None, id) { - Self::send_message(&self.sender_outgoing, configure); - } +impl Client { + /// Types a message from the server and passes it to its handler. A reply does not name the + /// method it answers, so it is typed by the method of the request sent with its ID. + fn receive(&mut self, message: Message) -> Result<(), Error> { + let message = match message { + Message::Request(request) => ServerToClient::try_from(request)?, + Message::Response(response) => { + let method = response.id.as_ref().and_then(|id| self.pending.remove(id)); + let typed = match &method { + Some(method) => ServerToClient::from_response(&response, method)?, + None => None, + }; + let Some(typed) = typed else { + eprintln!("CLIENT - unexpected response {response}"); + return Ok(()); + }; + typed + } + }; + self.handle_message(None, message) } } impl IsClient for Client { type Error = Error; - fn handle_set_difficulty( - &mut self, - _server_id: Option, - _conf: &mut server_to_client::SetDifficulty, - ) -> Result<(), Error> { + fn handle_notify(&mut self, _server_id: Option, notify: Notify) -> Result<(), Error> { + self.job_id = Some(notify.job_id); Ok(()) } - fn handle_set_extranonce( + fn handle_set_difficulty( &mut self, _server_id: Option, - _conf: &mut server_to_client::SetExtranonce, + _set: SetDifficulty, ) -> Result<(), Error> { Ok(()) } - fn handle_set_version_mask( + fn handle_set_extranonce( &mut self, _server_id: Option, - _conf: &mut server_to_client::SetVersionMask, + set: SetExtranonce, ) -> Result<(), Error> { + self.extranonce2_size = Some(set.extranonce2_size); Ok(()) } - fn handle_notify( + fn handle_set_version_mask( &mut self, _server_id: Option, - notify: server_to_client::Notify, + set: SetVersionMask, ) -> Result<(), Error> { - self.last_notify = Some(notify); + self.mask = Some(set.mask); Ok(()) } - fn handle_configure( + fn handle_configure_result( &mut self, _server_id: Option, - _conf: &mut server_to_client::Configure, + _id: &Id, + result: ConfigureResult, ) -> Result<(), Error> { + self.mask = result + .version_rolling + .filter(|version_rolling| version_rolling.enabled) + .map(|version_rolling| version_rolling.mask); Ok(()) } - fn handle_subscribe( + fn handle_subscribe_result( &mut self, _server_id: Option, - _subscribe: &server_to_client::Subscribe, + _id: &Id, + result: SubscribeResult, ) -> Result<(), Error> { + self.extranonce2_size = Some(result.extranonce2_size); Ok(()) } - fn set_extranonce1( + fn handle_authorize_result( &mut self, _server_id: Option, - extranonce1: Extranonce, + _id: &Id, + authorized: bool, ) -> Result<(), Error> { - self.extranonce1 = extranonce1; + self.authorized = authorized; Ok(()) } - fn extranonce1(&self, _server_id: Option) -> Result { - Ok(self.extranonce1.clone()) - } - - fn set_extranonce2_size( + fn handle_submit_result( &mut self, _server_id: Option, - extra_nonce2_size: usize, + _id: &Id, + accepted: bool, ) -> Result<(), Error> { - self.extranonce2_size = extra_nonce2_size; + if accepted { + self.accepted += 1; + } Ok(()) } - fn extranonce2_size(&self, _server_id: Option) -> Result { - Ok(self.extranonce2_size) - } - - fn version_rolling_mask(&self, _server_id: Option) -> Result, Error> { - Ok(self.version_rolling_mask.clone()) - } - - fn set_version_rolling_mask( + fn handle_extranonce_subscribe_result( &mut self, _server_id: Option, - mask: Option, + _id: &Id, + _acknowledged: bool, ) -> Result<(), Error> { - self.version_rolling_mask = mask; Ok(()) } - fn set_version_rolling_min_bit( + fn handle_error_response( &mut self, _server_id: Option, - min: Option, + id: &Id, + method: Method, + error: RpcError, ) -> Result<(), Error> { - self.version_rolling_min_bit = min; - Ok(()) - } - - fn set_status(&mut self, _server_id: Option, status: ClientStatus) -> Result<(), Error> { - self.status = status; - Ok(()) - } - - fn signature(&self, _server_id: Option) -> Result { - Ok(format!("{}", self.client_id)) - } - - fn status(&self, _server_id: Option) -> Result { - Ok(self.status) - } - - fn version_rolling_min_bit( - &mut self, - _server_id: Option, - ) -> Result, Error> { - Ok(self.version_rolling_min_bit.clone()) - } - - fn id_is_authorize( - &mut self, - _server_id: Option, - id: &u64, - ) -> Result, Error> { - let req: Vec<&(u64, String)> = self - .sented_authorize_request - .iter() - .filter(|x| x.0 == *id) - .collect(); - match req.len() { - 0 => Ok(None), - _ => Ok(Some(req[0].1.clone())), - } - } - - fn id_is_submit(&mut self, _server_id: Option, _: &u64) -> Result { - Ok(false) - } - - fn authorize_user_name( - &mut self, - _server_id: Option, - name: String, - ) -> Result<(), Error> { - self.authorized.push(name); + eprintln!( + "CLIENT - {method} {id} rejected: {} {}", + error.code, error.message + ); Ok(()) } - - fn is_authorized(&self, _server_id: Option, name: &String) -> Result { - Ok(self.authorized.contains(name)) - } - - fn authorize( - &mut self, - _server_id: Option, - id: u64, - name: String, - password: String, - ) -> Result { - match self.status(None)? { - ClientStatus::Init => Err(Error::IncorrectClientStatus("mining.authorize".to_string())), - _ => { - self.sented_authorize_request.push((id, "user".to_string())); - Ok(client_to_server::Authorize { id, name, password }.into()) - } - } - } - - fn last_notify( - &self, - _server_id: Option, - ) -> Result, Error> { - Ok(self.last_notify.clone()) - } - - fn handle_error_message( - &mut self, - _server_id: Option, - message: Message, - ) -> Result, Error> { - println!("{message:?}"); - Ok(None) - } -} - -fn initialize_client(client: Arc>) { - loop { - { - let mut client_ = client.lock().unwrap(); - match client_.status { - ClientStatus::Init => client_.send_configure(), - ClientStatus::Configured => client_.send_subscribe(), - ClientStatus::Subscribed => { - client_.send_authorize(); - break; - } - } - } - thread::sleep(Duration::from_millis(1000)); - } - - thread::sleep(Duration::from_millis(2000)); - loop { - { - let mut client_ = client.lock().unwrap(); - client_.send_submit(); - } - thread::sleep(Duration::from_millis(2000)); - } } fn main() { - let listener = TcpListener::bind(ADDR).unwrap(); - println!("Server listening on: {}", listener.local_addr().unwrap()); - let socket = listener.local_addr().unwrap(); - + let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind"); + let address = listener.local_addr().expect("bound address"); + println!("Server listening on: {address}"); thread::spawn(move || { - server_pool_listen(listener); + for stream in listener.incoming().map_while(Result::ok) { + thread::spawn(move || serve(stream)); + } }); - let client = Client::new(80, socket); - initialize_client(client); -} - -mod utils { - use std::fmt::Write; - - pub fn decode_hex(s: &str) -> Result, core::num::ParseIntError> { - let s = match s.strip_prefix("0x") { - Some(s) => s, - None => s, - }; - (0..s.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&s[i..i + 2], 16)) - .collect() - } - - pub fn encode_hex(bytes: &[u8]) -> String { - let mut s = String::with_capacity(bytes.len() * 2); - for &b in bytes { - write!(&mut s, "{b:02x}").unwrap(); + let stream = TcpStream::connect(address).expect("failed to connect"); + let (incoming, outgoing) = connect(stream); + let mut client = Client::new(outgoing); + client.send( + ClientToServer::Configure, + Configure::with_version_rolling(Some(HexU32Be(0xffff_ffff)), Some(2)), + ); + client.send( + ClientToServer::Subscribe, + Subscribe { + agent: "sv1-example/1.0".to_string(), + subscription_id: None, + }, + ); + client.send( + ClientToServer::Authorize, + Authorize { + worker_name: WORKER.to_string(), + password: "x".to_string(), + }, + ); + + let deadline = Instant::now() + RUN_FOR; + let mut next_submit = Instant::now() + SUBMIT_INTERVAL; + while Instant::now() < deadline { + match incoming.recv_timeout(Duration::from_millis(100)) { + Ok(message) => { + println!("CLIENT <- {message}"); + if let Err(e) = client.receive(message) { + eprintln!("CLIENT - {e}"); + } + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => { + eprintln!("CLIENT - connection closed"); + exit(1); + } + } + if Instant::now() >= next_submit { + client.submit(); + next_submit += SUBMIT_INTERVAL; } - s } - #[cfg(test)] - #[test] - fn test() { - let test_vec = vec![222, 173, 190, 239]; - let hex_og = "deadbeef"; - let hex_og_w_prefix = "0xdeadbeef"; - // decode hex strings - let decoded = decode_hex(hex_og).unwrap(); - let decoded_w_prefix = decode_hex(hex_og_w_prefix).unwrap(); - - assert_eq!(&decoded, &test_vec, "Hex not decoded correctly"); - assert_eq!( - &decoded_w_prefix, &test_vec, - "Hex w/ prefix not decoded correctly" - ); - - // reencode - let reencoded = encode_hex(&decoded); - let reencoded_prefix = encode_hex(&decoded); - - assert_eq!(&reencoded, hex_og, "Hex not encoded correctly"); - assert_eq!( - &reencoded_prefix, &hex_og, - "Hex w/ prefix not encoded correctly" - ); - } + println!( + "Ran for {} seconds; {} shares accepted", + RUN_FOR.as_secs(), + client.accepted + ); + exit(if client.accepted > 0 { 0 } else { 1 }); } diff --git a/sv1/src/error.rs b/sv1/src/error.rs index 6b592ce26c..163ef27144 100644 --- a/sv1/src/error.rs +++ b/sv1/src/error.rs @@ -1,33 +1,21 @@ -use crate::methods::{Method, MethodError}; use bitcoin::hashes::hex::HexToBytesError; + #[derive(Debug)] #[non_exhaustive] pub enum Error { BadBytesConvert(binary_sv2::Error), /// Errors on bad hex decode/encode. HexError(HexToBytesError), - /// Errors if `ClientStatus` is in an unexpected state when a message is received. For example, - /// if a `mining.subscribed` is received when the `ClientStatus` is in the `Init` state. - IncorrectClientStatus(String), - Infallible(std::convert::Infallible), - /// Errors if server receives a `json_rpc` request as the server should only receive responses. - /// TODO: Should update to accommodate miner requesting a difficulty change - InvalidJsonRpcMessageKind, - /// Errors when a hex string has invalid length (input too short or too long). - InvalidHexLen(String), - /// Errors if the client receives an invalid message that was intended to be sent from the - /// client to the server, NOT from the server to the client. - #[allow(clippy::upper_case_acronyms)] - InvalidReceiver(Box), - /// Errors encountered during conversion between valid `json_rpc` messages and SV1 messages. - Method(Box), - /// Errors if action is attempted that requires the client to be authorized, but it is - /// unauthorized. The client username is given in the error message. - UnauthorizedClient(String), - /// Errors if server does not recognize the client's `id`. - UnknownID(u64), - /// Errors when an unexpected or unsupported message/method is called. - UnexpectedMessage(String), + /// A hex string has an invalid length, in characters. + InvalidHexLen(usize), + Decode(DecodeError), + /// The result of the outstanding `method` request with this ID does not have that method's + /// result type. + InvalidResult { + id: crate::json_rpc::Id, + method: crate::json_rpc::Method, + error: serde_json::Error, + }, } impl std::fmt::Display for Error { @@ -38,56 +26,137 @@ impl std::fmt::Display for Error { "Bad U256 or B032 conversion (U256 length must be exactly 32 bytes; B032 length must be <= 32 bytes): {e:?}" ), Error::HexError(ref e) => write!(f, "Bad hex encode/decode: `{e}`"), - Error::InvalidHexLen(ref val) => write!(f, "Hex string length is invalid: `{val}`"), - Error::IncorrectClientStatus(s) => { - write!(f, "Client status is incompatible with message: `{s}`") + Error::InvalidHexLen(len) => write!(f, "Hex string has an invalid length of {len}"), + Error::Decode(e) => e.fmt(f), + Error::InvalidResult { id, method, error } => { + write!(f, "malformed result for {method} request {id}: {error}") } - Error::Infallible(ref e) => write!(f, "Infallible error{e:?}"), - Error::InvalidJsonRpcMessageKind => write!( - f, - "Server received a `json_rpc` response when it should only receive requests" - ), - Error::InvalidReceiver(ref e) => write!( - f, - "Client received an invalid message that was intended to be sent from the - client to the server, NOT from the server to the client. Invalid message: `{e:?}`" - ), - Error::Method(ref e) => { - write!( - f, - "Error converting valid `json_rpc` SV1 message: `{e:?}`" - ) - } - Error::UnauthorizedClient(id) => write!( - f, - "Client with id `{id}` expected to be authorized but is unauthorized." - ), - Error::UnknownID(e) => write!(f, "Server did not recognize the client id: `{e}`."), - Error::UnexpectedMessage(method) => write!(f, "Unexpected or unsupported message/method called: `{method}`."), } } } +impl std::error::Error for Error {} + impl From for Error { fn from(e: HexToBytesError) -> Self { Error::HexError(e) } } -impl From for Error { - fn from(e: std::convert::Infallible) -> Self { - Error::Infallible(e) +impl From for Error { + fn from(inner: binary_sv2::Error) -> Self { + Error::BadBytesConvert(inner) } } -impl From for Error { - fn from(inner: MethodError) -> Self { - Error::Method(Box::new(inner)) +impl From for Error { + fn from(e: DecodeError) -> Self { + Error::Decode(e) } } -impl From for Error { - fn from(inner: binary_sv2::Error) -> Self { - Error::BadBytesConvert(inner) +/// The longest method name a [`DecodeError`] keeps. +const MAX_ECHOED_LEN: usize = 64; + +/// A message that could not be decoded. +/// +/// `id` is set only when the message carried a valid ID, so a reply never reflects an invalid +/// one. +#[derive(Debug)] +pub struct DecodeError { + pub id: Option, + pub method: Option, + pub kind: DecodeErrorKind, +} + +#[derive(Debug)] +#[non_exhaustive] +pub enum DecodeErrorKind { + /// The line is not JSON, not an object, or repeats a reserved member. + Json(serde_json::Error), + InvalidEnvelope(&'static str), + /// The method is unknown, or is not sent in this direction. + UnknownMethod, + /// A request that needs a reply has no ID. + MissingId, + /// A response arrived where a request was expected. + UnexpectedResponse, + InvalidParams { + field: &'static str, + reason: &'static str, + }, +} + +/// A parameter that failed validation, before the request it belongs to is known. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ParamError { + pub(crate) field: &'static str, + pub(crate) reason: &'static str, +} + +impl ParamError { + pub(crate) fn new(field: &'static str, reason: &'static str) -> Self { + ParamError { field, reason } } } + +impl From for DecodeErrorKind { + fn from(e: ParamError) -> Self { + DecodeErrorKind::InvalidParams { + field: e.field, + reason: e.reason, + } + } +} + +impl std::fmt::Display for ParamError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{}: {}", self.field, self.reason) + } +} + +impl DecodeError { + pub(crate) fn new(kind: DecodeErrorKind) -> Self { + DecodeError::about(None, None, kind) + } + + /// Keeps the method only while it is short, so the error stays small whatever the size of + /// the message. A decoded ID is always short. + pub(crate) fn about( + id: Option, + method: Option, + kind: DecodeErrorKind, + ) -> Self { + DecodeError { + id, + method: method.filter(|method| method.as_str().len() <= MAX_ECHOED_LEN), + kind, + } + } +} + +impl std::fmt::Display for DecodeError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match &self.kind { + DecodeErrorKind::Json(e) => write!(f, "invalid SV1 message: {e}")?, + DecodeErrorKind::InvalidEnvelope(reason) => { + write!(f, "invalid SV1 envelope: {reason}")? + } + DecodeErrorKind::UnknownMethod => f.write_str("unknown SV1 method")?, + DecodeErrorKind::MissingId => f.write_str("SV1 request has no id")?, + DecodeErrorKind::UnexpectedResponse => f.write_str("unexpected SV1 response")?, + DecodeErrorKind::InvalidParams { field, reason } => { + write!(f, "invalid SV1 params: {field}: {reason}")? + } + } + if let Some(method) = &self.method { + write!(f, " (method {method})")?; + } + if let Some(id) = &self.id { + write!(f, " (id {id})")?; + } + Ok(()) + } +} + +impl std::error::Error for DecodeError {} diff --git a/sv1/src/json_rpc.rs b/sv1/src/json_rpc.rs index 7400b8fe08..28be6aae45 100644 --- a/sv1/src/json_rpc.rs +++ b/sv1/src/json_rpc.rs @@ -1,169 +1,293 @@ -//! https://www.jsonrpc.org/specification#response_object -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{fmt, fmt::Display}; +//! SV1 message envelope: one newline-delimited JSON object. +//! +//! An object with a string `method` is a [`Request`]; it is a notification when its `id` is +//! absent or null. Any other object is a [`Response`]. -#[derive(Clone, Serialize, Debug)] -#[serde(untagged)] +use crate::error::{DecodeError, DecodeErrorKind}; +use serde::{ + de::{self, DeserializeOwned, IgnoredAny, MapAccess, Visitor}, + ser::SerializeMap, + Deserialize, Deserializer, Serialize, Serializer, +}; +use serde_json::Value; +use std::fmt; + +#[derive(Clone, Debug, PartialEq)] pub enum Message { - StandardRequest(StandardRequest), - Notification(Notification), - OkResponse(Response), - ErrorResponse(Response), + Request(Request), + Response(Response), } -impl<'de> Deserialize<'de> for Message { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - #[derive(Deserialize)] - #[serde(untagged)] - enum MessageWire { - StandardRequest(StandardRequest), - Notification(Notification), - Response(Response), +#[derive(Clone, PartialEq)] +pub struct Request { + /// `None` makes this a notification, which never gets a reply. + pub id: Option, + pub method: Method, + pub params: Value, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Response { + /// `None` for an error the peer could not correlate with a request. + pub id: Option, + pub result: Result, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Method { + Configure, + Subscribe, + Authorize, + Submit, + ExtranonceSubscribe, + SuggestDifficulty, + Notify, + SetDifficulty, + SetExtranonce, + SetVersionMask, + Other(String), +} + +/// A request ID: an unsigned integer, a negative integer, or a string. +/// +/// Numeric `1` and string `"1"` are different IDs. A string ID longer than 64 bytes is rejected +/// when decoding, so an ID is always small enough to keep and to echo. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Id(IdRepr); + +/// The longest string ID a decoded message carries. +const MAX_ID_LEN: usize = 64; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum IdRepr { + Unsigned(u64), + Negative(i64), + String(String), +} + +/// An SV1 error, serialized as `[code, message, data]`. +/// +/// The three-element format is used by the [original Stratum implementation][a] and the +/// [NiceHash extranonce extension][b]. Deserialization additionally accepts `[code, message]` +/// with absent data, and object-form errors, for compatibility. +/// +/// [a]: https://github.com/slush0/stratum/blob/master/stratum/protocol.py +/// [b]: https://github.com/nicehash/Specifications/blob/master/NiceHash_extranonce_subscribe_extension.txt +#[derive(Clone, Debug, PartialEq)] +pub struct RpcError { + pub code: i32, + pub message: String, + pub data: Option, +} + +impl Message { + pub(crate) fn request(id: Option, method: Method, params: Value) -> Self { + Message::Request(Request { id, method, params }) + } + + pub(crate) fn notification(method: Method, params: Vec) -> Self { + Message::request(None, method, Value::Array(params)) + } + + pub fn decode(line: &str) -> Result { + let raw: RawEnvelope = + serde_json::from_str(line).map_err(|e| DecodeError::new(DecodeErrorKind::Json(e)))?; + raw.classify() + } +} + +impl From for Message { + fn from(response: Response) -> Self { + Message::Response(response) + } +} + +impl Response { + pub fn success(id: Id, result: impl Into) -> Self { + Response { + id: Some(id), + result: Ok(result.into()), } + } - Ok(match MessageWire::deserialize(deserializer)? { - MessageWire::StandardRequest(request) => Self::StandardRequest(request), - MessageWire::Notification(notification) => Self::Notification(notification), - MessageWire::Response(response) => response.into(), - }) + pub fn failure(id: Option, error: RpcError) -> Self { + Response { + id, + result: Err(error), + } } } -impl Message { - // TODO: Remove this. Keeping this in to avoid upgrading the major version of the crate. - pub fn is_response(&self) -> bool { +/// The longest message kept from a result that does not have the expected shape. +const MAX_RESULT_ERROR_LEN: usize = 128; + +/// Decodes `value` as `T`. +/// +/// serde_json quotes a mismatched string in its error, so the message is cut to keep the error +/// small whatever the size of the value. +pub(crate) fn decode_value(value: &Value) -> Result { + T::deserialize(value).map_err(|error| { + let message: String = error + .to_string() + .chars() + .take(MAX_RESULT_ERROR_LEN) + .collect(); + de::Error::custom(message) + }) +} + +impl Method { + pub fn as_str(&self) -> &str { match self { - Message::StandardRequest(_) => false, - Message::Notification(_) => false, - Message::OkResponse(_) => true, - Message::ErrorResponse(_) => true, + Method::Configure => "mining.configure", + Method::Subscribe => "mining.subscribe", + Method::Authorize => "mining.authorize", + Method::Submit => "mining.submit", + Method::ExtranonceSubscribe => "mining.extranonce.subscribe", + Method::SuggestDifficulty => "mining.suggest_difficulty", + Method::Notify => "mining.notify", + Method::SetDifficulty => "mining.set_difficulty", + Method::SetExtranonce => "mining.set_extranonce", + Method::SetVersionMask => "mining.set_version_mask", + Method::Other(method) => method, } } + + fn known(method: &str) -> Option { + Some(match method { + "mining.configure" => Method::Configure, + "mining.subscribe" => Method::Subscribe, + "mining.authorize" => Method::Authorize, + "mining.submit" => Method::Submit, + "mining.extranonce.subscribe" => Method::ExtranonceSubscribe, + "mining.suggest_difficulty" => Method::SuggestDifficulty, + "mining.notify" => Method::Notify, + "mining.set_difficulty" => Method::SetDifficulty, + "mining.set_extranonce" => Method::SetExtranonce, + "mining.set_version_mask" => Method::SetVersionMask, + _ => return None, + }) + } +} + +impl From<&str> for Method { + fn from(method: &str) -> Self { + Method::known(method).unwrap_or_else(|| Method::Other(method.to_string())) + } +} + +impl From for Method { + fn from(method: String) -> Self { + Method::known(&method).unwrap_or(Method::Other(method)) + } } -impl Display for Message { +/// Unknown method names come from the peer, so they are escaped. +impl fmt::Display for Method { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Message::StandardRequest(sr) => write!(f, "{}", sr), - Message::Notification(n) => write!(f, "{}", n), - Message::OkResponse(r) => write!(f, "{}", r), - Message::ErrorResponse(r) => write!(f, "{}", r), + Method::Other(method) => write!(f, "{method:?}"), + known => f.write_str(known.as_str()), } } } -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] -pub struct StandardRequest { - pub id: u64, - pub method: String, - pub params: serde_json::Value, +impl Id { + fn from_value(value: Value) -> Result { + match value { + Value::Number(number) => { + if let Some(id) = number.as_u64() { + Ok(Id(IdRepr::Unsigned(id))) + } else if let Some(id) = number.as_i64() { + Ok(Id(IdRepr::Negative(id))) + } else { + Err("id is not an integer") + } + } + Value::String(id) if id.len() > MAX_ID_LEN => Err("id is longer than 64 bytes"), + Value::String(id) => Ok(Id(IdRepr::String(id))), + _ => Err("id is not a number or a string"), + } + } } -impl fmt::Display for StandardRequest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let params = - serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string()); - write!( - f, - "{{ id: {}, method: {}, params: {} }}", - self.id, self.method, params - ) +impl From for Id { + fn from(id: u64) -> Self { + Id(IdRepr::Unsigned(id)) } } -#[derive(Clone, Serialize, Deserialize, Debug)] -pub struct Notification { - pub method: String, - pub params: serde_json::Value, +impl From for Id { + fn from(id: i64) -> Self { + match u64::try_from(id) { + Ok(id) => Id(IdRepr::Unsigned(id)), + Err(_) => Id(IdRepr::Negative(id)), + } + } } -impl fmt::Display for Notification { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let params = - serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string()); - - write!(f, "{{ method: \"{}\", params: {} }}", self.method, params) +impl From for Id { + fn from(id: String) -> Self { + Id(IdRepr::String(id)) } } -#[derive(Clone, Serialize, Deserialize, Debug)] -pub struct Response { - pub id: u64, - pub error: Option, - pub result: serde_json::Value, +impl From<&str> for Id { + fn from(id: &str) -> Self { + Id(IdRepr::String(id.to_string())) + } } -impl fmt::Display for Response { +impl fmt::Display for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let result = - serde_json::to_string_pretty(&self.result).unwrap_or_else(|_| self.result.to_string()); - - if let Some(err) = &self.error { - write!( - f, - "{{ id: {}, error: {:?}, result: {} }}", - self.id, err, result - ) - } else { - write!(f, "{{ id: {}, result: {} }}", self.id, result) + match &self.0 { + IdRepr::Unsigned(id) => write!(f, "{id}"), + IdRepr::Negative(id) => write!(f, "{id}"), + IdRepr::String(id) => write!(f, "{id:?}"), } } } -/// An SV1 response error, serialized as `[code, message, data]`. -/// -/// The three-element format is used by the [original Stratum implementation][a] and the -/// [NiceHash extranonce extension][b]. Deserialization additionally accepts `[code, message]` -/// with absent data, and object-form errors, for compatibility. -/// -/// [a]: https://github.com/slush0/stratum/blob/master/stratum/protocol.py -/// [b]: https://github.com/nicehash/Specifications/blob/master/NiceHash_extranonce_subscribe_extension.txt -#[derive(Clone, Debug, PartialEq)] -pub struct JsonRpcError { - pub code: i32, // json do not specify precision which one should be used? - pub message: String, - pub data: Option, +impl Serialize for Id { + fn serialize(&self, serializer: S) -> Result { + match &self.0 { + IdRepr::Unsigned(id) => serializer.serialize_u64(*id), + IdRepr::Negative(id) => serializer.serialize_i64(*id), + IdRepr::String(id) => serializer.serialize_str(id), + } + } } -impl Serialize for JsonRpcError { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { +impl Serialize for RpcError { + fn serialize(&self, serializer: S) -> Result { (&self.code, &self.message, &self.data).serialize(serializer) } } -impl<'de> Deserialize<'de> for JsonRpcError { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { +impl<'de> Deserialize<'de> for RpcError { + fn deserialize>(deserializer: D) -> Result { #[derive(Deserialize)] #[serde(untagged)] - enum JsonRpcErrorWire { - Legacy((i32, String, Option)), + enum RpcErrorWire { + Legacy((i32, String, Option)), LegacyWithoutData((i32, String)), Object { code: i32, message: String, - data: Option, + data: Option, }, } - let (code, message, data) = match JsonRpcErrorWire::deserialize(deserializer)? { - JsonRpcErrorWire::Legacy((code, message, data)) - | JsonRpcErrorWire::Object { + let (code, message, data) = match RpcErrorWire::deserialize(deserializer)? { + RpcErrorWire::Legacy((code, message, data)) + | RpcErrorWire::Object { code, message, data, } => (code, message, data), - JsonRpcErrorWire::LegacyWithoutData((code, message)) => (code, message, None), + RpcErrorWire::LegacyWithoutData((code, message)) => (code, message, None), }; - Ok(Self { + Ok(RpcError { code, message, data, @@ -171,160 +295,474 @@ impl<'de> Deserialize<'de> for JsonRpcError { } } -impl From for Message { - fn from(res: Response) -> Self { - if res.error.is_some() { - Message::ErrorResponse(res) - } else { - Message::OkResponse(res) +impl Serialize for Message { + fn serialize(&self, serializer: S) -> Result { + match self { + Message::Request(request) => request.serialize(serializer), + Message::Response(response) => response.serialize(serializer), } } } -impl From for Message { - fn from(sr: StandardRequest) -> Self { - Message::StandardRequest(sr) +impl Serialize for Request { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(3))?; + map.serialize_entry("id", &self.id)?; + map.serialize_entry("method", self.method.as_str())?; + map.serialize_entry("params", &self.params)?; + map.end() + } +} + +impl Serialize for Response { + fn serialize(&self, serializer: S) -> Result { + let (result, error) = match &self.result { + Ok(result) => (result, None), + Err(error) => (&Value::Null, Some(error)), + }; + let mut map = serializer.serialize_map(Some(3))?; + map.serialize_entry("id", &self.id)?; + map.serialize_entry("result", result)?; + map.serialize_entry("error", &error)?; + map.end() + } +} + +impl<'de> Deserialize<'de> for Message { + fn deserialize>(deserializer: D) -> Result { + RawEnvelope::deserialize(deserializer)? + .classify() + .map_err(de::Error::custom) + } +} + +/// The reserved envelope members, each recorded only when present. +#[derive(Default)] +struct RawEnvelope { + id: Option, + method: Option, + params: Option, + result: Option, + error: Option, +} + +impl RawEnvelope { + fn classify(self) -> Result { + let id = match self.id { + None | Some(Value::Null) => None, + Some(id) => Some(Id::from_value(id).map_err(|reason| { + DecodeError::about(None, None, DecodeErrorKind::InvalidEnvelope(reason)) + })?), + }; + let invalid = + |reason| DecodeError::about(id.clone(), None, DecodeErrorKind::InvalidEnvelope(reason)); + match self.method { + Some(Value::String(method)) => { + let method = Method::from(method); + let Some(params) = self.params else { + return Err(DecodeError::about( + id, + Some(method), + DecodeErrorKind::InvalidEnvelope("missing params"), + )); + }; + Ok(Message::Request(Request { id, method, params })) + } + None | Some(Value::Null) => { + let result = match self.error { + Some(error) if !error.is_null() => Err(serde_json::from_value(error) + .map_err(|_| invalid("error is not an SV1 error"))?), + _ => Ok(self.result.ok_or_else(|| invalid("missing result"))?), + }; + Ok(Message::Response(Response { id, result })) + } + Some(_) => Err(invalid("method is not a string")), + } } } -impl From for Message { - fn from(n: Notification) -> Self { - Message::Notification(n) +impl<'de> Deserialize<'de> for RawEnvelope { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(RawEnvelopeVisitor) + } +} + +struct RawEnvelopeVisitor; + +impl<'de> Visitor<'de> for RawEnvelopeVisitor { + type Value = RawEnvelope; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an SV1 message object") + } + + /// A string is rejected without being quoted, so the error stays small whatever its size. + fn visit_str(self, _: &str) -> Result { + Err(E::invalid_type(de::Unexpected::Other("string"), &self)) + } + + fn visit_map>(self, mut map: A) -> Result { + fn member<'de, A: MapAccess<'de>>( + map: &mut A, + slot: &mut Option, + name: &'static str, + ) -> Result<(), A::Error> { + if slot.is_some() { + return Err(de::Error::duplicate_field(name)); + } + *slot = Some(map.next_value()?); + Ok(()) + } + + let mut raw = RawEnvelope::default(); + while let Some(key) = map.next_key::()? { + match key.as_str() { + "id" => member(&mut map, &mut raw.id, "id")?, + "method" => member(&mut map, &mut raw.method, "method")?, + "params" => member(&mut map, &mut raw.params, "params")?, + "result" => member(&mut map, &mut raw.result, "result")?, + "error" => member(&mut map, &mut raw.error, "error")?, + _ => { + map.next_value::()?; + } + } + } + Ok(raw) + } +} + +impl fmt::Display for Message { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Message::Request(request) => request.fmt(f), + Message::Response(response) => response.fmt(f), + } + } +} + +fn display_id(id: &Option) -> String { + id.as_ref().map_or("null".to_string(), Id::to_string) +} + +impl fmt::Display for Request { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{{ id: {}, method: {}, params: {} }}", + display_id(&self.id), + self.method, + RedactedParams(self) + ) + } +} + +impl fmt::Debug for Request { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Request") + .field("id", &self.id) + .field("method", &self.method) + .field("params", &format_args!("{}", RedactedParams(self))) + .finish() + } +} + +/// `mining.authorize` params carry the worker password, and a configure `info.connection-url` +/// may carry credentials. +struct RedactedParams<'a>(&'a Request); + +const CONNECTION_URL: &str = "/1/info.connection-url"; + +impl fmt::Display for RedactedParams<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let params = &self.0.params; + match self.0.method { + Method::Authorize => f.write_str(""), + Method::Configure if params.pointer(CONNECTION_URL).is_some() => { + let mut params = params.clone(); + if let Some(url) = params.pointer_mut(CONNECTION_URL) { + *url = Value::from(""); + } + write!(f, "{params}") + } + _ => write!(f, "{params}"), + } + } +} + +impl fmt::Display for Response { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.result { + Ok(result) => write!(f, "{{ id: {}, result: {result} }}", display_id(&self.id)), + Err(error) => write!( + f, + "{{ id: {}, error: [{}, {:?}] }}", + display_id(&self.id), + error.code, + error.message + ), + } } } #[cfg(test)] mod tests { use super::*; + use serde_json::json; + + fn decode(line: &str) -> Message { + Message::decode(line).unwrap_or_else(|e| panic!("{line}: {e}")) + } + + fn request(line: &str) -> Request { + match decode(line) { + Message::Request(request) => request, + other => panic!("{line}: not a request: {other:?}"), + } + } + + fn response(line: &str) -> Response { + match decode(line) { + Message::Response(response) => response, + other => panic!("{line}: not a response: {other:?}"), + } + } + + fn reject(line: &str) -> DecodeError { + match Message::decode(line) { + Ok(message) => panic!("{line}: unexpectedly decoded as {message:?}"), + Err(error) => error, + } + } #[test] - fn deserializes_legacy_sv1_error_array() { - let response: Response = serde_json::from_value(serde_json::json!({ - "id": 42, - "result": null, - "error": [22, "Duplicate share", null], - })) - .unwrap(); + fn method_classifies_requests() { + for (line, id) in [ + ( + r#"{"id":1,"method":"mining.subscribe","params":[]}"#, + Some(Id::from(1u64)), + ), + ( + r#"{"jsonrpc":"2.0","id":1,"method":"mining.subscribe","params":[]}"#, + Some(Id::from(1u64)), + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":[],"error":null}"#, + Some(Id::from(1u64)), + ), + ( + r#"{"id":"1","method":"mining.subscribe","params":[]}"#, + Some(Id::from("1")), + ), + ( + r#"{"id":-3,"method":"mining.subscribe","params":[]}"#, + Some(Id::from(-3i64)), + ), + ( + r#"{"id":18446744073709551615,"method":"mining.subscribe","params":[]}"#, + Some(Id::from(u64::MAX)), + ), + (r#"{"method":"mining.set_difficulty","params":[2]}"#, None), + ( + r#"{"id":null,"method":"mining.set_difficulty","params":[2]}"#, + None, + ), + ( + r#"{"id":null,"method":"mining.set_difficulty","params":[2],"result":null,"error":null}"#, + None, + ), + ] { + assert_eq!(request(line).id, id, "{line}"); + } + } - assert_eq!( - response.error, - Some(JsonRpcError { - code: 22, - message: "Duplicate share".to_string(), - data: None, - }) - ); + #[test] + fn null_params_are_kept() { + let request = request(r#"{"id":1,"method":"mining.extranonce.subscribe","params":null}"#); + assert_eq!(request.method, Method::ExtranonceSubscribe); + assert_eq!(request.params, Value::Null); } #[test] - fn deserializes_two_element_errors_and_serializes_three_elements() { - for code in 20..=25 { - let message: Message = serde_json::from_value(serde_json::json!({ - "id": 42, - "result": null, - "error": [code, "Rejected"], - })) - .unwrap(); - - let Message::ErrorResponse(response) = &message else { - panic!("a two-element error must remain an error response"); - }; - assert_eq!( - response.error, - Some(JsonRpcError { - code, - message: "Rejected".to_string(), - data: None, - }) - ); - assert_eq!( - serde_json::to_value(&message).unwrap(), - serde_json::json!({ - "id": 42, - "result": null, - "error": [code, "Rejected", null], - }) - ); - assert!(matches!( - crate::methods::Method::try_from(message), - Ok(crate::methods::Method::ErrorMessage(_)) - )); + fn responses() { + for (line, id, result) in [ + ( + r#"{"id":1,"result":true,"error":null}"#, + Some(1u64), + Ok(json!(true)), + ), + (r#"{"id":1,"result":true}"#, Some(1), Ok(json!(true))), + (r#"{"id":1,"result":null}"#, Some(1), Ok(Value::Null)), + ( + r#"{"id":1,"result":true,"error":null,"method":null,"params":null}"#, + Some(1), + Ok(json!(true)), + ), + ( + r#"{"id":1,"result":null,"error":[22,"Duplicate share",null]}"#, + Some(1), + Err(22), + ), + ( + r#"{"id":1,"result":null,"error":[22,"Duplicate share"]}"#, + Some(1), + Err(22), + ), + ( + r#"{"id":1,"result":null,"error":{"code":22,"message":"Duplicate share","data":null}}"#, + Some(1), + Err(22), + ), + ( + r#"{"id":1,"error":[22,"Duplicate share",null]}"#, + Some(1), + Err(22), + ), + ( + r#"{"id":null,"result":null,"error":[20,"Other/Unknown",null]}"#, + None, + Err(20), + ), + ( + r#"{"id":3,"result":false,"error":[20,"Not supported.",null]}"#, + Some(3), + Err(20), + ), + ] { + let response = response(line); + assert_eq!(response.id, id.map(Id::from), "{line}"); + assert_eq!(response.result.map_err(|e| e.code), result, "{line}"); } } #[test] - fn legacy_error_round_trip_preserves_additional_data() { - let wire = serde_json::json!([20, "Rejected", {"detail": "invalid share"}]); - let error: JsonRpcError = serde_json::from_value(wire.clone()).unwrap(); - assert_eq!( - error.data, - Some(serde_json::json!({"detail": "invalid share"})) - ); - assert_eq!(serde_json::to_value(error).unwrap(), wire); + fn rejects_malformed_envelopes() { + for line in [ + r#"{"id":1,"method":"mining.subscribe"}"#, + r#"{"id":1}"#, + r#"{"id":1,"error":null}"#, + r#"{"id":1.0,"method":"mining.subscribe","params":[]}"#, + r#"{"id":true,"method":"mining.subscribe","params":[]}"#, + r#"{"id":1,"method":5,"params":[]}"#, + r#"{"id":1,"id":2,"method":"mining.subscribe","params":[]}"#, + r#"{"id":1,"result":true,"error":[20]}"#, + r#"[{"id":1,"method":"mining.subscribe","params":[]}]"#, + r#"{"id":1,"method":"mining.subscribe","params":[]"#, + ] { + reject(line); + } + } + + #[test] + fn errors_do_not_quote_peer_strings() { + let long = "a".repeat(1000); + let line = format!("\"{long}\""); + let error = reject(&line); + assert!(matches!(error.kind, DecodeErrorKind::Json(_))); + assert!(error.to_string().len() < 200); + assert!(format!("{error:?}").len() < 200); + let error = serde_json::from_str::(&line).unwrap_err(); + assert!(error.to_string().len() < 200); + + let error = decode_value::(&Value::String(long)).unwrap_err(); + assert!(error.to_string().len() < 200); + assert!(format!("{error:?}").len() < 200); } #[test] - fn rejects_legacy_errors_with_invalid_types_or_arity() { - for wire in [ - serde_json::json!([]), - serde_json::json!([20]), - serde_json::json!([20, "Rejected", null, null]), - serde_json::json!(["20", "Rejected"]), - serde_json::json!(["20", "Rejected", null]), - serde_json::json!([20.5, "Rejected"]), - serde_json::json!([20, 42]), - serde_json::json!([20, 42, null]), + fn errors_carry_only_a_validated_id() { + let error = reject(r#"{"id":7,"method":"mining.submit"}"#); + assert_eq!(error.id, Some(Id::from(7u64))); + assert_eq!(error.method, Some(Method::Submit)); + + let error = reject(r#"{"id":1.5,"method":"mining.submit","params":[]}"#); + assert_eq!(error.id, None); + } + + #[test] + fn method_names_round_trip() { + for method in [ + Method::Configure, + Method::Subscribe, + Method::Authorize, + Method::Submit, + Method::ExtranonceSubscribe, + Method::SuggestDifficulty, + Method::Notify, + Method::SetDifficulty, + Method::SetExtranonce, + Method::SetVersionMask, + Method::Other("client.reconnect".to_string()), ] { - assert!( - serde_json::from_value::(wire.clone()).is_err(), - "invalid error unexpectedly accepted: {wire}" - ); + assert_eq!(Method::from(method.as_str()), method); + assert_eq!(Method::from(method.as_str().to_string()), method); } } #[test] - fn deserializes_json_rpc_error_object_for_compatibility() { - let response: Response = serde_json::from_value(serde_json::json!({ - "id": 42, - "result": null, - "error": { - "code": 22, - "message": "Duplicate share", - "data": null, - }, - })) - .unwrap(); + fn encoding() { + let notification = Message::Request(Request { + id: None, + method: Method::SetVersionMask, + params: json!(["1fffe000"]), + }); + assert_eq!( + serde_json::to_value(¬ification).unwrap(), + json!({"id": null, "method": "mining.set_version_mask", "params": ["1fffe000"]}) + ); + let success = Message::Response(Response::success(Id::from("a"), true)); assert_eq!( - response.error, - Some(JsonRpcError { - code: 22, - message: "Duplicate share".to_string(), + serde_json::to_value(&success).unwrap(), + json!({"id": "a", "result": true, "error": null}) + ); + + let failure = Message::Response(Response::failure( + Some(Id::from(4u64)), + RpcError { + code: 23, + message: "Low difficulty share".to_string(), data: None, - }) + }, + )); + assert_eq!( + serde_json::to_value(&failure).unwrap(), + json!({"id": 4, "result": null, "error": [23, "Low difficulty share", null]}) ); + + for message in [notification, success, failure] { + let line = serde_json::to_string(&message).unwrap(); + assert_eq!(decode(&line), message, "{line}"); + assert_eq!( + serde_json::from_str::(&line).unwrap(), + message, + "{line}" + ); + } } #[test] - fn message_classifies_response_from_error_field() { - let error: Message = serde_json::from_value(serde_json::json!({ - "id": 42, - "result": null, - "error": [22, "Duplicate share", null], - })) - .unwrap(); - assert!(matches!(&error, Message::ErrorResponse(_))); - assert!(matches!( - crate::methods::Method::try_from(error), - Ok(crate::methods::Method::ErrorMessage(_)) - )); + fn ids_are_mirrored_exactly() { + for id in [ + Id::from(1u64), + Id::from("1"), + Id::from(-1i64), + Id::from(u64::MAX), + ] { + let line = serde_json::to_string(&Response::success(id.clone(), true)).unwrap(); + assert_eq!(response(&line).id, Some(id), "{line}"); + } + assert_ne!(Id::from(1u64), Id::from("1")); + assert_eq!(Id::from(1u64), Id::from(1i64)); + } + + #[test] + fn authorize_params_are_redacted() { + let authorize = request(r#"{"id":2,"method":"mining.authorize","params":["w","hunter2"]}"#); + assert!(!authorize.to_string().contains("hunter2")); + assert!(!format!("{authorize:?}").contains("hunter2")); + assert!(!Message::Request(authorize).to_string().contains("hunter2")); - let success: Message = serde_json::from_value(serde_json::json!({ - "id": 43, - "result": true, - "error": null, - })) - .unwrap(); - assert!(matches!(success, Message::OkResponse(_))); + let subscribe = request(r#"{"id":1,"method":"mining.subscribe","params":["cgminer"]}"#); + assert!(subscribe.to_string().contains("cgminer")); } } diff --git a/sv1/src/lib.rs b/sv1/src/lib.rs index 26dcac8a05..8770abca70 100644 --- a/sv1/src/lib.rs +++ b/sv1/src/lib.rs @@ -1,13 +1,11 @@ -#![allow(clippy::result_unit_err)] //! Stratum V1 application protocol: //! -//! json-rpc has two types of messages: **request** and **response**. -//! A request message can be either a **notification** or a **standard message**. -//! Standard messages expect a response, notifications do not. A typical example of a notification -//! is the broadcasting of a new block. +//! Messages are newline-delimited JSON objects of two kinds: **requests** and **responses**. +//! A request is either a **notification**, which never gets a reply, or a **standard request**, +//! which does. A typical example of a notification is the broadcasting of a new block. //! -//! Every RPC request contains three parts: -//! * message ID: integer or string +//! Every request contains three parts: +//! * message ID: integer or string, or null for a notification //! * remote method: unicode string //! * parameters: list of parameters //! @@ -17,13 +15,6 @@ //! server and clients can initiate request with id “1”). Client or server can choose string/UUID //! identifier for example in the case when standard “atomic” counter isn’t available. //! -//! ## Notifications -//! Notifications are like Request, but it does not expect any response and message ID is always -//! null: -//! * message ID: null -//! * remote method: unicode string -//! * parameters: list of parameters -//! //! ## Responses //! Every response contains the following parts //! * message ID: same ID as in request, for pairing request-response together @@ -32,6 +23,10 @@ //! element is null when no additional data is provided. For compatibility, deserialization also //! accepts two-element lists with absent data and object-form errors. //! +//! [`ClientToServer`] and [`ServerToClient`] are the typed messages of each direction. +//! [`IsServer`] and [`IsClient`], with their `Async` variants, route them to one handler per +//! message. Their handlers are required, so an implementor cannot miss a message. +//! //! References: //! [https://docs.google.com/document/d/17zHy1SUlhgtCMbypO8cHgpWH73V5iUQKk_0rWvMqSNs/edit?hl=en_US#] //! [https://braiins.com/stratum-v1/docs] @@ -41,714 +36,508 @@ pub mod error; pub mod json_rpc; -pub mod methods; +mod messages; pub mod utils; -use crate::utils::hex_decode; -use std::convert::{TryFrom, TryInto}; -use tracing::debug; - -// use error::Result; -use error::Error; -pub use json_rpc::Message; -pub use methods::{client_to_server, server_to_client, Method, MethodError, ParsingMethodError}; -use utils::{Extranonce, HexU32Be}; +pub use json_rpc::{Id, Message, Method, RpcError}; +pub use messages::{ + Authorize, ClientToServer, Configure, ConfigureExtension, ConfigureResult, ExtranonceSubscribe, + InfoParams, Notify, Request, Response, ServerToClient, SetDifficulty, SetExtranonce, + SetVersionMask, Submit, SubmitError, SubmitOutcome, Subscribe, SubscribeResult, + SuggestDifficulty, VersionRolling, VersionRollingResult, +}; -/// json_rpc Response are not handled because stratum v1 does not have any request from a server to -/// a client -/// TODO: Should update to accommodate miner requesting a difficulty change +/// Routes requests from SV1 clients to one handler per method. +/// +/// The router keeps no session state and checks none: a handler acts on its request and sends +/// the reply, which must carry the request's `id`. The reply is [`Response::success`] with the +/// result named on the handler, or [`SubmitOutcome::into_response`] for a submit. /// -/// A stratum v1 server represent a single connection with a client +/// `client_id` identifies the connection, so one implementor can serve many clients. pub trait IsServer { - /// Error returned by the server implementation. - /// - /// Implementations can use their application error type as long as native SV1 errors can be - /// converted into it. This allows default trait methods to report protocol errors while - /// implementors can also propagate errors from their own state and synchronization layers. - type Error: From; - - /// handle the received message and return a response if the message is a request or - /// notification. - fn handle_message( - &mut self, - client_id: Option, - msg: json_rpc::Message, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { - match msg { - Message::StandardRequest(_) => { - // handle valid standard request - self.handle_request(client_id, msg) - } - Message::Notification(_) => { - // handle valid server notification - self.handle_request(client_id, msg) - } - _ => { - // Server shouldn't receive json_rpc responses - Err(Error::InvalidJsonRpcMessageKind.into()) - } - } - } - - /// Call the right handler according with the called method - fn handle_request( - &mut self, - client_id: Option, - msg: json_rpc::Message, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { - let request = msg.try_into().map_err(Error::from)?; - - self.handle_parsed_request(client_id, request) - } + type Error; - /// Handles a request already decoded by [`methods::Client2Server::try_from`]. + /// Calls the handler for `request`. /// - /// Servers may use the typed request to check session ordering before allocating resources, - /// then dispatch it here without parsing it again. This is the same dispatch path used by - /// [`Self::handle_message`]; decoding alone does not execute handlers or authorize a client. - fn handle_parsed_request( + /// The request is already decoded, so callers can check session ordering or queue it first. + fn handle_request( &mut self, client_id: Option, - request: methods::Client2Server, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { + request: ClientToServer, + ) -> Result<(), Self::Error> { match request { - // TODO: Handle suggested difficulty - methods::Client2Server::SuggestDifficulty() => Ok(None), - methods::Client2Server::Authorize(authorize) => { - let authorized = self.handle_authorize(client_id, &authorize)?; - if authorized { - self.authorize(client_id, &authorize.name)?; - } - Ok(Some(authorize.respond(authorized))) + ClientToServer::Configure(Request { id, params }) => { + self.handle_configure(client_id, id, params) } - methods::Client2Server::Configure(configure) => { - debug!("{:?}", configure); - self.set_version_rolling_mask(client_id, configure.version_rolling_mask())?; - self.set_version_rolling_min_bit( - client_id, - configure.version_rolling_min_bit_count(), - )?; - let (version_rolling, min_diff) = self.handle_configure(client_id, &configure)?; - Ok(Some(configure.respond(version_rolling, min_diff))) + ClientToServer::Subscribe(Request { id, params }) => { + self.handle_subscribe(client_id, id, params) } - methods::Client2Server::ExtranonceSubscribe(subscribe) => { - self.handle_extranonce_subscribe(client_id)?; - Ok(Some(subscribe.respond())) + ClientToServer::Authorize(Request { id, params }) => { + self.handle_authorize(client_id, id, params) } - methods::Client2Server::Submit(submit) => { - let has_valid_version_bits = match &submit.version_bits { - Some(a) => { - if let Some(version_rolling_mask) = self.version_rolling_mask(client_id)? { - version_rolling_mask.check_mask(a) - } else { - false - } - } - None => self.version_rolling_mask(client_id)?.is_none(), - }; - - if !self.is_authorized(client_id, &submit.user_name)? { - return Ok(Some(submit.respond( - client_to_server::SubmitOutcome::Rejected( - client_to_server::SubmitError::UnauthorizedWorker, - ), - ))); - } - - let outcome = if self.extranonce2_size(client_id)? != submit.extra_nonce2.len() - || !has_valid_version_bits - { - client_to_server::SubmitOutcome::Rejected(client_to_server::SubmitError::Other) - } else { - self.handle_submit(client_id, &submit)? - }; - - Ok(Some(submit.respond(outcome))) + ClientToServer::Submit(Request { id, params }) => { + self.handle_submit(client_id, id, params) } - methods::Client2Server::Subscribe(subscribe) => { - let subscriptions = self.handle_subscribe(client_id, &subscribe)?; - let extra_n1 = self.set_extranonce1(client_id, None)?; - let extra_n2_size = self.set_extranonce2_size(client_id, None)?; - Ok(Some(subscribe.respond( - subscriptions, - extra_n1, - extra_n2_size, - ))) + ClientToServer::ExtranonceSubscribe(Request { id, .. }) => { + self.handle_extranonce_subscribe(client_id, id) + } + ClientToServer::SuggestDifficulty(Request { id, params }) => { + self.handle_suggest_difficulty(client_id, id, params) } } } - /// This message (JSON RPC Request) SHOULD be the first message sent by the miner after the - /// connection with the server is established. + /// Replies with a [`ConfigureResult`]. fn handle_configure( &mut self, client_id: Option, - request: &client_to_server::Configure, - ) -> Result<(Option, Option), Self::Error>; + id: Id, + request: Configure, + ) -> Result<(), Self::Error>; - /// On the beginning of the session, client subscribes current connection for receiving mining - /// jobs. - /// - /// The client can specify [mining.notify][a] job_id the client wishes to resume working with - /// - /// The result contains three items: - /// * Subscriptions details: 2-tuple with name of subscribed notification and subscription ID. - /// Teoretically it may be used for unsubscribing, but obviously miners won't use it. - /// * Extranonce1 - Hex-encoded, per-connection unique string which will be used for coinbase - /// serialization later. Keep it safe! - /// * Extranonce2_size - Represents expected length of extranonce2 which will be generated by - /// the miner. - /// - /// Almost instantly after the subscription server start to send [jobs][a] - /// - /// This function return the first item of the result (2 tuple with name of subscibed ...) - /// - /// [a]: crate::methods::server_to_client::Notify + /// Replies with a [`SubscribeResult`]. fn handle_subscribe( - &self, + &mut self, client_id: Option, - request: &client_to_server::Subscribe, - ) -> Result, Self::Error>; + id: Id, + request: Subscribe, + ) -> Result<(), Self::Error>; - /// You can authorize as many workers as you wish and at any - /// time during the session. In this way, you can handle big basement of independent mining rigs - /// just by one Stratum connection. - /// - /// https://bitcoin.stackexchange.com/questions/29416/how-do-pool-servers-handle-multiple-workers-sharing-one-connection-with-stratum + /// Replies with whether the worker is authorized. A worker may be authorized at any time + /// during the session, so one connection can carry many workers. fn handle_authorize( - &self, + &mut self, client_id: Option, - request: &client_to_server::Authorize, - ) -> Result; + id: Id, + request: Authorize, + ) -> Result<(), Self::Error>; - /// Validates a share after the default request handler has checked its SV1 session fields. - /// - /// [`Self::handle_parsed_request`] calls this only when the worker is authorized, extranonce2 - /// has the size returned by [`Self::extranonce2_size`], and the version bits match the negotiated - /// version-rolling mask (including whether version bits must be present). + /// Replies with a [`SubmitOutcome`]. /// - /// Unauthorized workers receive [`client_to_server::SubmitError::UnauthorizedWorker`] (24). - /// Invalid extranonce2 sizes or version bits receive [`client_to_server::SubmitError::Other`] - /// (20). These rejections bypass this method and return `Ok(Some(response))`, not a Rust error; - /// applications that log or count them should inspect the returned response's `error` field. - /// Errors returned by the session-state accessors are still propagated to the caller. + /// Every submit reaches this handler, so it is the one that rejects a submit from an + /// unauthorized worker, with an extranonce2 of the wrong size, or with version bits the + /// negotiated mask does not allow. fn handle_submit( - &self, + &mut self, client_id: Option, - request: &client_to_server::Submit, - ) -> Result; - - /// Records that the identified client supports the `mining.set_extranonce` - /// notification. - /// - /// The mutable receiver allows an implementation to retain this capability - /// for the lifetime of the client session. - fn handle_extranonce_subscribe(&mut self, client_id: Option) -> Result<(), Self::Error>; - - fn is_authorized(&self, client_id: Option, name: &str) -> Result; - - fn authorize(&mut self, client_id: Option, name: &str) -> Result<(), Self::Error>; + id: Id, + request: Submit, + ) -> Result<(), Self::Error>; - /// Set extranonce1 to extranonce1 if provided. If not create a new one and set it. - fn set_extranonce1( + /// The client supports `mining.set_extranonce`. Replies with `true`. + fn handle_extranonce_subscribe( &mut self, client_id: Option, - extranonce1: Option, - ) -> Result; - - fn extranonce1(&self, client_id: Option) -> Result; + id: Id, + ) -> Result<(), Self::Error>; - /// Set extranonce2_size to extranonce2_size if provided. If not create a new one and set it. - fn set_extranonce2_size( + /// Servers are not required to honour the suggestion, nor to reply. + fn handle_suggest_difficulty( &mut self, client_id: Option, - extra_nonce2_size: Option, - ) -> Result; + id: Id, + request: SuggestDifficulty, + ) -> Result<(), Self::Error>; +} - fn extranonce2_size(&self, client_id: Option) -> Result; +/// [`IsServer`] for handlers that wait, such as on a channel to the client. +#[trait_variant::make(Send)] +pub trait IsServerAsync { + type Error; - fn version_rolling_mask( - &self, + /// Calls the handler for `request`. + /// + /// The request is already decoded, so callers can check session ordering or queue it first. + async fn handle_request( + &mut self, client_id: Option, - ) -> Result, Self::Error>; + request: ClientToServer, + ) -> Result<(), Self::Error> { + async move { + match request { + ClientToServer::Configure(Request { id, params }) => { + self.handle_configure(client_id, id, params).await + } + ClientToServer::Subscribe(Request { id, params }) => { + self.handle_subscribe(client_id, id, params).await + } + ClientToServer::Authorize(Request { id, params }) => { + self.handle_authorize(client_id, id, params).await + } + ClientToServer::Submit(Request { id, params }) => { + self.handle_submit(client_id, id, params).await + } + ClientToServer::ExtranonceSubscribe(Request { id, .. }) => { + self.handle_extranonce_subscribe(client_id, id).await + } + ClientToServer::SuggestDifficulty(Request { id, params }) => { + self.handle_suggest_difficulty(client_id, id, params).await + } + } + } + } - fn set_version_rolling_mask( + /// Replies with a [`ConfigureResult`]. + async fn handle_configure( &mut self, client_id: Option, - mask: Option, + id: Id, + request: Configure, ) -> Result<(), Self::Error>; - fn set_version_rolling_min_bit( + /// Replies with a [`SubscribeResult`]. + async fn handle_subscribe( &mut self, client_id: Option, - mask: Option, + id: Id, + request: Subscribe, ) -> Result<(), Self::Error>; - fn update_extranonce( + /// Replies with whether the worker is authorized. A worker may be authorized at any time + /// during the session, so one connection can carry many workers. + async fn handle_authorize( &mut self, client_id: Option, - extra_nonce1: Extranonce, - extra_nonce2_size: usize, - ) -> Result { - self.set_extranonce1(client_id, Some(extra_nonce1.clone()))?; - self.set_extranonce2_size(client_id, Some(extra_nonce2_size))?; - - Ok(server_to_client::SetExtranonce { - extra_nonce1, - extra_nonce2_size, - } - .into()) - } - // {"params":["00003000"], "id":null, "method": "mining.set_version_mask"} - // fn update_version_rolling_mask + id: Id, + request: Authorize, + ) -> Result<(), Self::Error>; - fn notify(&mut self, client_id: Option) -> Result; + /// Replies with a [`SubmitOutcome`]. + /// + /// Every submit reaches this handler, so it is the one that rejects a submit from an + /// unauthorized worker, with an extranonce2 of the wrong size, or with version bits the + /// negotiated mask does not allow. + async fn handle_submit( + &mut self, + client_id: Option, + id: Id, + request: Submit, + ) -> Result<(), Self::Error>; - fn handle_set_difficulty( + /// The client supports `mining.set_extranonce`. Replies with `true`. + async fn handle_extranonce_subscribe( &mut self, - _client_id: Option, - value: f64, - ) -> Result { - let set_difficulty = server_to_client::SetDifficulty { value }; - Ok(set_difficulty.into()) - } -} + client_id: Option, + id: Id, + ) -> Result<(), Self::Error>; -fn route_general_response( - general: server_to_client::GeneralResponse, - authorize_user_name: Option, - is_submit: bool, - is_extranonce_subscribe: bool, -) -> Result { - match (authorize_user_name, is_submit, is_extranonce_subscribe) { - (Some(previous_name), false, false) => Ok(methods::Server2ClientResponse::Authorize( - general.into_authorize(previous_name), - )), - (None, false, true) => Ok(methods::Server2ClientResponse::ExtranonceSubscribe( - general.into_extranonce_subscribe(), - )), - (None, false, false) => Ok(methods::Server2ClientResponse::Submit( - general.into_submit(), - )), - _ => Err(Error::UnknownID(general.id)), - } + /// Servers are not required to honour the suggestion, nor to reply. + async fn handle_suggest_difficulty( + &mut self, + client_id: Option, + id: Id, + request: SuggestDifficulty, + ) -> Result<(), Self::Error>; } +/// Routes messages from an SV1 server to one handler per notification and result. +/// +/// The router keeps no session state and checks none. The caller types each message: a +/// notification with `ServerToClient::try_from`, and a reply with +/// [`ServerToClient::from_response`], naming the method of the request that reply answers. pub trait IsClient { - /// Error returned by the client implementation. - /// - /// Implementations can use their application error type as long as native SV1 errors can be - /// converted into it. This allows default trait methods to report protocol errors while - /// implementors can also propagate errors from their own state and synchronization layers. - type Error: From; + type Error; - /// Deserialize a [raw json_rpc message][a] into a [stratum v1 message][b] and handle the - /// result. - /// - /// [a]: crate::... - /// [b]: + /// Calls the handler for `message`. fn handle_message( &mut self, server_id: Option, - msg: json_rpc::Message, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { - let method: Result = msg.try_into(); - - match method { - Ok(m) => match m { - Method::Server2ClientResponse(response) => { - let response = self.update_response(server_id, response)?; - self.handle_response(server_id, response) - } - Method::Server2Client(request) => self.handle_request(server_id, request), - Method::Client2Server(_) => Err(Error::InvalidReceiver(m.into()).into()), - Method::ErrorMessage(msg) => self.handle_error_message(server_id, msg), - }, - Err(e) => Err(Error::from(e).into()), - } - } - - fn update_response( - &mut self, - server_id: Option, - response: methods::Server2ClientResponse, - ) -> Result { - match response { - methods::Server2ClientResponse::GeneralResponse(general) => { - let is_authorize = self.id_is_authorize(server_id, &general.id)?; - let is_submit = self.id_is_submit(server_id, &general.id)?; - let is_extranonce_subscribe = - self.id_is_extranonce_subscribe(server_id, &general.id)?; - route_general_response(general, is_authorize, is_submit, is_extranonce_subscribe) - .map_err(Self::Error::from) - } - response => Ok(response), - } - } - - /// Call the right handler according with the called method - fn handle_request( - &mut self, - server_id: Option, - request: methods::Server2Client, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { - match request { - methods::Server2Client::Notify(notify) => { - self.handle_notify(server_id, notify)?; - Ok(None) - } - methods::Server2Client::SetDifficulty(mut set_diff) => { - self.handle_set_difficulty(server_id, &mut set_diff)?; - Ok(None) - } - methods::Server2Client::SetExtranonce(mut set_extra_nonce) => { - self.handle_set_extranonce(server_id, &mut set_extra_nonce)?; - Ok(None) - } - methods::Server2Client::SetVersionMask(mut set_version_mask) => { - self.handle_set_version_mask(server_id, &mut set_version_mask)?; - Ok(None) - } - } - } - - fn handle_response( - &mut self, - server_id: Option, - response: methods::Server2ClientResponse, - ) -> Result, Self::Error> - where - Self: std::marker::Sized, - { - match response { - methods::Server2ClientResponse::Configure(mut configure) => { - self.handle_configure(server_id, &mut configure)?; - self.set_version_rolling_mask(server_id, configure.version_rolling_mask())?; - self.set_version_rolling_min_bit(server_id, configure.version_rolling_min_bit())?; - self.set_status(server_id, ClientStatus::Configured)?; - - //in sv1 the mining.configure message should be the first message to come in before - // the subscribe - the subscribe response is where the server hands out the - // extranonce so it doesnt really matter what the server sets the - // extranonce to in the mining.configure handler - debug!("NOTICE: Subscribe extranonce is hardcoded by server"); - let subscribe = self - .subscribe( - server_id, - configure.id, - Some(Extranonce::try_from(hex_decode("08000002")?)?), - ) - .ok(); - Ok(subscribe) - } - methods::Server2ClientResponse::Subscribe(subscribe) => { - self.handle_subscribe(server_id, &subscribe)?; - self.set_extranonce1(server_id, subscribe.extra_nonce1)?; - self.set_extranonce2_size(server_id, subscribe.extra_nonce2_size)?; - self.set_status(server_id, ClientStatus::Subscribed)?; - Ok(None) - } - methods::Server2ClientResponse::Authorize(authorize) => { - if authorize.is_ok() { - self.authorize_user_name(server_id, authorize.user_name())?; - }; - Ok(None) - } - methods::Server2ClientResponse::ExtranonceSubscribe(_) => Ok(None), - methods::Server2ClientResponse::Submit(_) => Ok(None), - // impossible state - methods::Server2ClientResponse::GeneralResponse(_) => panic!(), - methods::Server2ClientResponse::SetDifficulty(_) => Ok(None), + message: ServerToClient, + ) -> Result<(), Self::Error> { + let method = message.method(); + match message { + ServerToClient::Notify(notify) => self.handle_notify(server_id, notify), + ServerToClient::SetDifficulty(set) => self.handle_set_difficulty(server_id, set), + ServerToClient::SetExtranonce(set) => self.handle_set_extranonce(server_id, set), + ServerToClient::SetVersionMask(set) => self.handle_set_version_mask(server_id, set), + ServerToClient::Configure(Response { + id, + result: Ok(result), + }) => self.handle_configure_result(server_id, &id, result), + ServerToClient::Subscribe(Response { + id, + result: Ok(result), + }) => self.handle_subscribe_result(server_id, &id, result), + ServerToClient::Authorize(Response { + id, + result: Ok(authorized), + }) => self.handle_authorize_result(server_id, &id, authorized), + ServerToClient::Submit(Response { + id, + result: Ok(accepted), + }) => self.handle_submit_result(server_id, &id, accepted), + ServerToClient::ExtranonceSubscribe(Response { + id, + result: Ok(acknowledged), + }) => self.handle_extranonce_subscribe_result(server_id, &id, acknowledged), + ServerToClient::Configure(Response { + id, + result: Err(error), + }) + | ServerToClient::Subscribe(Response { + id, + result: Err(error), + }) + | ServerToClient::Authorize(Response { + id, + result: Err(error), + }) + | ServerToClient::Submit(Response { + id, + result: Err(error), + }) + | ServerToClient::ExtranonceSubscribe(Response { + id, + result: Err(error), + }) => self.handle_error_response(server_id, &id, method, error), } } - fn handle_error_message( + fn handle_notify( &mut self, server_id: Option, - message: Message, - ) -> Result, Self::Error>; + notify: Notify, + ) -> Result<(), Self::Error>; - /// Check if the client sent an Authorize request with the given id, if so it return the - /// authorized name - fn id_is_authorize( + fn handle_set_difficulty( &mut self, server_id: Option, - id: &u64, - ) -> Result, Self::Error>; - - /// Check if the client sent a Submit request with the given id - fn id_is_submit(&mut self, server_id: Option, id: &u64) -> Result; - - /// Returns whether `id` belongs to a `mining.extranonce.subscribe` request. - /// - /// Clients that do not send this extension can use the default implementation. - fn id_is_extranonce_subscribe( - &mut self, - _server_id: Option, - _id: &u64, - ) -> Result { - Ok(false) - } + set: SetDifficulty, + ) -> Result<(), Self::Error>; - fn handle_notify( + fn handle_set_extranonce( &mut self, server_id: Option, - notify: server_to_client::Notify, + set: SetExtranonce, ) -> Result<(), Self::Error>; - fn handle_configure( + fn handle_set_version_mask( &mut self, server_id: Option, - conf: &mut server_to_client::Configure, + set: SetVersionMask, ) -> Result<(), Self::Error>; - fn handle_set_difficulty( + fn handle_configure_result( &mut self, server_id: Option, - m: &mut server_to_client::SetDifficulty, + id: &Id, + result: ConfigureResult, ) -> Result<(), Self::Error>; - fn handle_set_extranonce( + fn handle_subscribe_result( &mut self, server_id: Option, - m: &mut server_to_client::SetExtranonce, + id: &Id, + result: SubscribeResult, ) -> Result<(), Self::Error>; - fn handle_set_version_mask( + fn handle_authorize_result( &mut self, server_id: Option, - m: &mut server_to_client::SetVersionMask, + id: &Id, + authorized: bool, ) -> Result<(), Self::Error>; - fn handle_subscribe( + fn handle_submit_result( &mut self, server_id: Option, - subscribe: &server_to_client::Subscribe, + id: &Id, + accepted: bool, ) -> Result<(), Self::Error>; - fn set_extranonce1( + fn handle_extranonce_subscribe_result( &mut self, server_id: Option, - extranonce1: Extranonce, + id: &Id, + acknowledged: bool, ) -> Result<(), Self::Error>; - fn extranonce1(&self, server_id: Option) -> Result; - - fn set_extranonce2_size( + /// The server rejected the `method` request with this ID. + fn handle_error_response( &mut self, server_id: Option, - extra_nonce2_size: usize, + id: &Id, + method: Method, + error: RpcError, ) -> Result<(), Self::Error>; +} - fn extranonce2_size(&self, server_id: Option) -> Result; +/// [`IsClient`] for handlers that wait. +#[trait_variant::make(Send)] +pub trait IsClientAsync { + type Error; - fn version_rolling_mask( - &self, + /// Calls the handler for `message`. + async fn handle_message( + &mut self, server_id: Option, - ) -> Result, Self::Error>; + message: ServerToClient, + ) -> Result<(), Self::Error> { + async move { + let method = message.method(); + match message { + ServerToClient::Notify(notify) => self.handle_notify(server_id, notify).await, + ServerToClient::SetDifficulty(set) => { + self.handle_set_difficulty(server_id, set).await + } + ServerToClient::SetExtranonce(set) => { + self.handle_set_extranonce(server_id, set).await + } + ServerToClient::SetVersionMask(set) => { + self.handle_set_version_mask(server_id, set).await + } + ServerToClient::Configure(Response { + id, + result: Ok(result), + }) => self.handle_configure_result(server_id, &id, result).await, + ServerToClient::Subscribe(Response { + id, + result: Ok(result), + }) => self.handle_subscribe_result(server_id, &id, result).await, + ServerToClient::Authorize(Response { + id, + result: Ok(authorized), + }) => { + self.handle_authorize_result(server_id, &id, authorized) + .await + } + ServerToClient::Submit(Response { + id, + result: Ok(accepted), + }) => self.handle_submit_result(server_id, &id, accepted).await, + ServerToClient::ExtranonceSubscribe(Response { + id, + result: Ok(acknowledged), + }) => { + self.handle_extranonce_subscribe_result(server_id, &id, acknowledged) + .await + } + ServerToClient::Configure(Response { + id, + result: Err(error), + }) + | ServerToClient::Subscribe(Response { + id, + result: Err(error), + }) + | ServerToClient::Authorize(Response { + id, + result: Err(error), + }) + | ServerToClient::Submit(Response { + id, + result: Err(error), + }) + | ServerToClient::ExtranonceSubscribe(Response { + id, + result: Err(error), + }) => { + self.handle_error_response(server_id, &id, method, error) + .await + } + } + } + } - fn set_version_rolling_mask( + async fn handle_notify( &mut self, server_id: Option, - mask: Option, + notify: Notify, ) -> Result<(), Self::Error>; - fn set_version_rolling_min_bit( + async fn handle_set_difficulty( &mut self, server_id: Option, - min: Option, + set: SetDifficulty, ) -> Result<(), Self::Error>; - fn version_rolling_min_bit( + async fn handle_set_extranonce( &mut self, server_id: Option, - ) -> Result, Self::Error>; + set: SetExtranonce, + ) -> Result<(), Self::Error>; - fn set_status( + async fn handle_set_version_mask( &mut self, server_id: Option, - status: ClientStatus, + set: SetVersionMask, ) -> Result<(), Self::Error>; - fn signature(&self, server_id: Option) -> Result; - - fn status(&self, server_id: Option) -> Result; - - fn last_notify( - &self, + async fn handle_configure_result( + &mut self, server_id: Option, - ) -> Result, Self::Error>; - - /// Check if the given user_name has been authorized by the server - #[allow(clippy::ptr_arg)] - fn is_authorized(&self, server_id: Option, name: &String) -> Result; + id: &Id, + result: ConfigureResult, + ) -> Result<(), Self::Error>; - /// Register the given user_name has authorized by the server - fn authorize_user_name( + async fn handle_subscribe_result( &mut self, server_id: Option, - name: String, + id: &Id, + result: SubscribeResult, ) -> Result<(), Self::Error>; - fn configure( + async fn handle_authorize_result( &mut self, server_id: Option, - id: u64, - ) -> Result { - if self.version_rolling_min_bit(server_id)?.is_none() - && self.version_rolling_mask(server_id)?.is_none() - { - Ok(client_to_server::Configure::void(id).into()) - } else { - Ok(client_to_server::Configure::new( - id, - self.version_rolling_mask(server_id)?, - self.version_rolling_min_bit(server_id)?, - ) - .into()) - } - } + id: &Id, + authorized: bool, + ) -> Result<(), Self::Error>; - fn subscribe( + async fn handle_submit_result( &mut self, server_id: Option, - id: u64, - extranonce1: Option, - ) -> Result { - match self.status(server_id)? { - ClientStatus::Init => { - Err(Error::IncorrectClientStatus("mining.subscribe".to_string()).into()) - } - _ => Ok(client_to_server::Subscribe { - id, - agent_signature: self.signature(server_id)?, - extranonce1, - } - .try_into()?), - } - } + id: &Id, + accepted: bool, + ) -> Result<(), Self::Error>; - fn authorize( + async fn handle_extranonce_subscribe_result( &mut self, server_id: Option, - id: u64, - name: String, - password: String, - ) -> Result { - match self.status(server_id)? { - ClientStatus::Init => { - Err(Error::IncorrectClientStatus("mining.authorize".to_string()).into()) - } - _ => Ok(client_to_server::Authorize { id, name, password }.into()), - } - } + id: &Id, + acknowledged: bool, + ) -> Result<(), Self::Error>; - #[allow(clippy::too_many_arguments)] - fn submit( + /// The server rejected the `method` request with this ID. + async fn handle_error_response( &mut self, server_id: Option, - id: u64, - user_name: String, - extra_nonce2: Extranonce, - time: i64, - nonce: i64, - version_bits: Option, - ) -> Result { - match self.status(server_id)? { - ClientStatus::Init => { - Err(Error::IncorrectClientStatus("mining.submit".to_string()).into()) - } - _ => { - if let Some(notify) = self.last_notify(server_id)? { - if !self.is_authorized(server_id, &user_name)? { - return Err(Error::UnauthorizedClient(user_name).into()); - } - Ok(client_to_server::Submit { - job_id: notify.job_id, - user_name, - extra_nonce2, - time: HexU32Be(time as u32), - nonce: HexU32Be(nonce as u32), - version_bits, - id, - } - .into()) - } else { - Err(Error::IncorrectClientStatus("No Notify instance found".to_string()).into()) - } - } - } - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum ClientStatus { - Init, - Configured, - Subscribed, + id: &Id, + method: Method, + error: RpcError, + ) -> Result<(), Self::Error>; } #[cfg(test)] mod tests { use super::*; - use std::collections::HashSet; - - #[test] - fn extranonce_subscribe_acknowledgement_has_distinct_response_route() { - let response = route_general_response( - server_to_client::GeneralResponse { - id: 42, - result: true, - }, - None, - false, - true, - ) - .unwrap(); - - let methods::Server2ClientResponse::ExtranonceSubscribe(response) = response else { - panic!("extranonce subscription acknowledgement was routed as another response"); + use crate::{ + error::Error, + utils::{Extranonce, HexU32Be}, + }; + use serde_json::json; + use std::convert::TryFrom; + + fn request(line: &str) -> ClientToServer { + let Message::Request(request) = Message::decode(line).unwrap() else { + panic!("{line}: not a request"); }; - assert_eq!(response.id, 42); - assert!(response.is_ok()); + ClientToServer::try_from(request).unwrap() } - // A minimal implementation of IsServer trait for testing - struct TestServer { - authorized_users: HashSet, - extranonce_subscriptions: HashSet>, - extranonce1: Extranonce, - extranonce2_size: usize, - version_rolling_mask: Option, - version_rolling_min_bit: Option, + fn reply(server: &mut TestServer, line: &str) -> Option { + server.handle_request(Some(1), request(line)).unwrap(); + let reply = server.replies.pop(); + assert!(server.replies.is_empty()); + reply.map(|reply| serde_json::to_value(reply).unwrap()) } - impl TestServer { - fn new(extranonce1: Extranonce, extranonce2_size: usize) -> Self { - Self { - authorized_users: HashSet::new(), - extranonce_subscriptions: HashSet::new(), - extranonce1, - extranonce2_size, - version_rolling_mask: None, - version_rolling_min_bit: None, - } - } + #[derive(Default)] + struct TestServer { + submits: usize, + extranonce_subscribed: bool, + suggested: Option, + replies: Vec, } impl IsServer for TestServer { @@ -756,304 +545,527 @@ mod tests { fn handle_configure( &mut self, - _client_id: Option, - _request: &client_to_server::Configure, - ) -> Result<(Option, Option), Error> { - Ok((None, None)) + _: Option, + id: Id, + request: Configure, + ) -> Result<(), Error> { + let result = ConfigureResult { + version_rolling: request + .version_rolling_mask() + .map(|mask| VersionRollingResult::new(mask, 0)), + minimum_difficulty: None, + }; + self.replies.push(Response::success(id, result).into()); + Ok(()) } fn handle_subscribe( - &self, - _client_id: Option, - _request: &client_to_server::Subscribe, - ) -> Result, Error> { - Ok(vec![("mining.notify".to_string(), "1".to_string())]) + &mut self, + _: Option, + id: Id, + _: Subscribe, + ) -> Result<(), Error> { + let result = SubscribeResult { + subscriptions: vec![("mining.notify".to_string(), "1".to_string())], + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).unwrap(), + extranonce2_size: 4, + }; + self.replies.push(Response::success(id, result).into()); + Ok(()) } fn handle_authorize( - &self, - _client_id: Option, - _request: &client_to_server::Authorize, - ) -> Result { - Ok(true) + &mut self, + _: Option, + id: Id, + request: Authorize, + ) -> Result<(), Error> { + self.replies + .push(Response::success(id, request.password == "x").into()); + Ok(()) } - fn notify(&mut self, _client_id: Option) -> Result { - Ok(json_rpc::Message::StandardRequest( - json_rpc::StandardRequest { - id: 1, - method: "mining.notify".to_string(), - params: serde_json::json!([]), - }, - )) + fn handle_submit(&mut self, _: Option, id: Id, _: Submit) -> Result<(), Error> { + self.submits += 1; + let outcome = SubmitOutcome::Rejected(SubmitError::LowDifficultyShare); + self.replies.push(outcome.into_response(id).into()); + Ok(()) } - fn handle_submit( - &self, - _client_id: Option, - _request: &client_to_server::Submit, - ) -> Result { - Ok(client_to_server::SubmitOutcome::Accepted) + fn handle_extranonce_subscribe(&mut self, _: Option, id: Id) -> Result<(), Error> { + self.extranonce_subscribed = true; + self.replies.push(Response::success(id, true).into()); + Ok(()) } - fn handle_extranonce_subscribe(&mut self, client_id: Option) -> Result<(), Error> { - self.extranonce_subscriptions.insert(client_id); + fn handle_suggest_difficulty( + &mut self, + _: Option, + _: Id, + request: SuggestDifficulty, + ) -> Result<(), Error> { + self.suggested = request.difficulty; Ok(()) } + } - fn is_authorized(&self, _client_id: Option, name: &str) -> Result { - Ok(self.authorized_users.contains(name)) - } + #[test] + fn replies_carry_the_request_id() { + let mut server = TestServer::default(); + assert_eq!( + reply( + &mut server, + r#"{"id":"a","method":"mining.authorize","params":["w","x"]}"# + ), + Some(json!({"id": "a", "result": true, "error": null})) + ); + assert_eq!( + reply( + &mut server, + r#"{"id":7,"method":"mining.authorize","params":["w","bad"]}"# + ), + Some(json!({"id": 7, "result": false, "error": null})) + ); + assert_eq!( + reply( + &mut server, + r#"{"id":2,"method":"mining.subscribe","params":[]}"# + ), + Some( + json!({"id": 2, "result": [[["mining.notify", "1"]], "08000002", 4], "error": null}) + ) + ); + assert_eq!( + reply( + &mut server, + r#"{"id":3,"method":"mining.configure","params":[["version-rolling"],{"version-rolling.mask":"ffffffff"}]}"# + ), + Some(json!({"id": 3, "result": { + "version-rolling": true, + "version-rolling.mask": "1fffffe0", + "version-rolling.min-bit-count": "00000000", + }, "error": null})) + ); + assert_eq!( + reply( + &mut server, + r#"{"id":4,"method":"mining.extranonce.subscribe","params":[]}"# + ), + Some(json!({"id": 4, "result": true, "error": null})) + ); + assert!(server.extranonce_subscribed); + } - fn authorize(&mut self, _client_id: Option, name: &str) -> Result<(), Error> { - self.authorized_users.insert(name.to_string()); - Ok(()) - } + #[test] + fn suggest_difficulty_gets_no_reply() { + let mut server = TestServer::default(); + assert_eq!( + reply( + &mut server, + r#"{"id":5,"method":"mining.suggest_difficulty","params":[512]}"# + ), + None + ); + assert_eq!(server.suggested, Some(512.0)); + } - fn set_extranonce1( - &mut self, - _client_id: Option, - extranonce1: Option, - ) -> Result { - if let Some(extranonce1) = extranonce1 { - self.extranonce1 = extranonce1; - } - Ok(self.extranonce1.clone()) - } + #[test] + fn every_submit_reaches_its_handler() { + let mut server = TestServer::default(); + assert_eq!( + reply( + &mut server, + r#"{"id":"s","method":"mining.submit","params":["w","bf","00","647025b5","1d2e3f40","e0000000"]}"# + ), + Some(json!({"id": "s", "result": null, "error": [23, "Low difficulty share", null]})) + ); + assert_eq!(server.submits, 1); + } - fn extranonce1(&self, _client_id: Option) -> Result { - Ok(self.extranonce1.clone()) - } + /// Records which handler ran, to check the async router against the sync one. + #[derive(Default)] + struct AsyncTestServer { + events: Vec, + } - fn set_extranonce2_size( + impl IsServerAsync for AsyncTestServer { + type Error = Error; + + async fn handle_configure( &mut self, - _client_id: Option, - extra_nonce2_size: Option, - ) -> Result { - if let Some(extra_nonce2_size) = extra_nonce2_size { - self.extranonce2_size = extra_nonce2_size; - } - Ok(self.extranonce2_size) + _: Option, + id: Id, + _: Configure, + ) -> Result<(), Error> { + self.events.push(format!("configure {id}")); + Ok(()) } - fn extranonce2_size(&self, _client_id: Option) -> Result { - Ok(self.extranonce2_size) + async fn handle_subscribe( + &mut self, + _: Option, + id: Id, + _: Subscribe, + ) -> Result<(), Error> { + self.events.push(format!("subscribe {id}")); + Ok(()) } - fn version_rolling_mask( - &self, - _client_id: Option, - ) -> Result, Error> { - Ok(None) + async fn handle_authorize( + &mut self, + _: Option, + id: Id, + _: Authorize, + ) -> Result<(), Error> { + self.events.push(format!("authorize {id}")); + Ok(()) } - fn set_version_rolling_mask( + async fn handle_submit( &mut self, - _client_id: Option, - mask: Option, + _: Option, + id: Id, + _: Submit, ) -> Result<(), Error> { - self.version_rolling_mask = mask; + self.events.push(format!("submit {id}")); Ok(()) } - fn set_version_rolling_min_bit( + async fn handle_extranonce_subscribe( &mut self, - _client_id: Option, - mask: Option, + _: Option, + id: Id, ) -> Result<(), Error> { - self.version_rolling_min_bit = mask; + self.events.push(format!("extranonce_subscribe {id}")); Ok(()) } - } - #[test] - fn test_server_handle_invalid_message() { - let extranonce1 = Extranonce::try_from(hex_decode("08000002").unwrap()).unwrap(); - let mut server = TestServer::new(extranonce1, 4); - - // Create an invalid message (response) - let request_message = json_rpc::Message::StandardRequest(json_rpc::StandardRequest { - id: 42, - method: "mining.subscribe_bad".to_string(), - params: serde_json::json!([]), - }); - - let result = server.handle_message(None, request_message); - - assert!(result.is_err()); - match result.unwrap_err() { - Error::Method(inner) => match *inner { - MethodError::MethodNotFound(_) => {} - other => panic!("Expected MethodNotFound error, got {:?}", other), - }, - other => panic!("Expected Error::Method, got {:?}", other), + async fn handle_suggest_difficulty( + &mut self, + _: Option, + id: Id, + _: SuggestDifficulty, + ) -> Result<(), Error> { + self.events.push(format!("suggest_difficulty {id}")); + Ok(()) } } - #[test] - fn extranonce_subscribe_passes_client_id_to_server() { - let extranonce1 = Extranonce::try_from(hex_decode("08000002").unwrap()).unwrap(); - let mut server = TestServer::new(extranonce1, 4); - let request = json_rpc::Message::StandardRequest(json_rpc::StandardRequest { - id: 42, - method: "mining.extranonce.subscribe".to_string(), - params: serde_json::json!([]), - }); - - let response = server.handle_message(Some(7), request).unwrap(); - - let response = response.expect("extranonce subscribe should be acknowledged"); - assert_eq!(response.id, 42); - assert_eq!(response.result, serde_json::json!(true)); - assert!(response.error.is_none()); - assert_eq!(server.extranonce_subscriptions, HashSet::from([Some(7)])); - } - - #[test] - fn extranonce_subscribe_ignores_params_and_acknowledges_request_id() { - for params in [ - serde_json::Value::Null, - serde_json::json!(["ignored"]), - serde_json::json!({"ignored": true}), - ] { - let extranonce1 = vec![0; 4].try_into().unwrap(); - let mut server = TestServer::new(extranonce1, 4); - let request = serde_json::from_value(serde_json::json!({ - "id": 42, - "method": "mining.extranonce.subscribe", - "params": params, - })) - .unwrap(); - - let response = server - .handle_message(Some(7), request) - .unwrap() - .expect("extranonce subscribe should be acknowledged"); - - assert_eq!(response.id, 42); - assert_eq!(response.result, serde_json::json!(true)); - assert!(response.error.is_none()); - assert_eq!(server.extranonce_subscriptions, HashSet::from([Some(7)])); + /// Runs a future that never waits. + fn run(future: F) -> F::Output { + struct NoopWaker; + impl std::task::Wake for NoopWaker { + fn wake(self: std::sync::Arc) {} + } + let waker = std::task::Waker::from(std::sync::Arc::new(NoopWaker)); + let mut future = std::pin::pin!(future); + match future + .as_mut() + .poll(&mut std::task::Context::from_waker(&waker)) + { + std::task::Poll::Ready(output) => output, + std::task::Poll::Pending => panic!("the future waited"), } } #[test] - fn parsed_requests_use_the_same_dispatch_as_wire_messages() { - let prefix: Extranonce = vec![1, 2, 3, 4].try_into().unwrap(); - let mut wire_server = TestServer::new(prefix.clone(), 4); - let mut typed_server = TestServer::new(prefix, 4); - for wire in [ - r#"{"id":1,"method":"mining.configure","params":[[],{}]}"#, + fn async_requests_are_routed() { + let mut server = AsyncTestServer::default(); + for line in [ + r#"{"id":1,"method":"mining.configure","params":[[]]}"#, r#"{"id":2,"method":"mining.subscribe","params":[]}"#, - r#"{"id":3,"method":"mining.authorize","params":["worker",""]}"#, - r#"{"id":4,"method":"mining.extranonce.subscribe","params":[]}"#, - r#"{"id":5,"method":"mining.submit","params":["worker","1","00000000","00000001","00000000"]}"#, + r#"{"id":3,"method":"mining.authorize","params":["w","x"]}"#, + r#"{"id":4,"method":"mining.submit","params":["w","bf","00000000","647025b5","1d2e3f40"]}"#, + r#"{"id":5,"method":"mining.extranonce.subscribe","params":[]}"#, + r#"{"id":6,"method":"mining.suggest_difficulty","params":[512]}"#, ] { - let message: Message = serde_json::from_str(wire).unwrap(); - let request = methods::Client2Server::try_from(message.clone()).unwrap(); - let wire_response = wire_server.handle_message(Some(7), message).unwrap(); - let typed_response = typed_server - .handle_parsed_request(Some(7), request) - .unwrap(); - assert_eq!( - serde_json::to_value(wire_response).unwrap(), - serde_json::to_value(typed_response).unwrap() - ); - assert_eq!(wire_server.authorized_users, typed_server.authorized_users); - assert_eq!( - wire_server.extranonce_subscriptions, - typed_server.extranonce_subscriptions - ); + run(server.handle_request(Some(1), request(line))).unwrap(); } + assert_eq!( + server.events, + [ + "configure 1", + "subscribe 2", + "authorize 3", + "submit 4", + "extranonce_subscribe 5", + "suggest_difficulty 6", + ] + ); } - #[test] - fn invalid_submit_fields_return_code_20() { - let extranonce1 = Extranonce::try_from(hex_decode("08000002").unwrap()).unwrap(); - let mut server = TestServer::new(extranonce1, 4); - server.authorized_users.insert("worker".to_string()); - let request = client_to_server::Submit { - user_name: "worker".to_string(), - job_id: "job".to_string(), - extra_nonce2: vec![0; 3].try_into().unwrap(), - time: HexU32Be(0), - nonce: HexU32Be(0), - version_bits: None, - id: 42, + fn client_impl_events() -> Vec { + let notify = match Message::decode( + r#"{"id":null,"method":"mining.notify","params":["bf","000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f","01","02",[],"20000000","1705ae3a","647025b5",true]}"#, + ) + .unwrap() + { + Message::Request(request) => ServerToClient::try_from(request).unwrap(), + Message::Response(_) => panic!("not a notification"), }; + vec![ + ServerToClient::Configure(Response::success( + Id::from(1u64), + ConfigureResult::default(), + )), + ServerToClient::Subscribe(Response::success( + Id::from(2u64), + SubscribeResult { + subscriptions: vec![], + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).unwrap(), + extranonce2_size: 4, + }, + )), + ServerToClient::Authorize(Response::success(Id::from(3u64), true)), + ServerToClient::Submit(Response::success(Id::from(4u64), false)), + ServerToClient::Submit(Response::success(Id::from("4"), true)), + ServerToClient::ExtranonceSubscribe(Response::success(Id::from(5u64), true)), + ServerToClient::Submit(Response::failure( + Id::from(6u64), + SubmitError::DuplicateShare.into(), + )), + ServerToClient::Authorize(Response::failure(Id::from(7u64), SubmitError::Other.into())), + notify, + ServerToClient::SetDifficulty(SetDifficulty { difficulty: 2.0 }), + ServerToClient::SetExtranonce(SetExtranonce { + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).unwrap(), + extranonce2_size: 4, + }), + ServerToClient::SetVersionMask(SetVersionMask { + mask: HexU32Be(0x1fffe000), + }), + ] + } - let response = server - .handle_message(None, request.into()) - .unwrap() - .expect("mining.submit must receive a response"); + const CLIENT_EVENTS: [&str; 12] = [ + "configure 1", + "subscribe 2", + "authorize 3 true", + "submit 4 false", + "submit \"4\" true", + "extranonce_subscribe 5 true", + "error 6 mining.submit 22", + "error 7 mining.authorize 20", + "notify bf", + "difficulty 2", + "extranonce 4", + "mask 1fffe000", + ]; + + #[derive(Default)] + struct TestClient { + events: Vec, + } - assert_eq!(response.result, serde_json::Value::Null); - let error = response - .error - .expect("invalid submit must include an error"); - assert_eq!(error.code, 20); + impl TestClient { + fn record(&mut self, event: String) -> Result<(), Error> { + self.events.push(event); + Ok(()) + } } - #[test] - fn unauthorized_submit_returns_code_24() { - let extranonce1 = Extranonce::try_from(hex_decode("08000002").unwrap()).unwrap(); - let mut server = TestServer::new(extranonce1, 4); - let request = client_to_server::Submit { - user_name: "worker".to_string(), - job_id: "job".to_string(), - extra_nonce2: vec![0; 4].try_into().unwrap(), - time: HexU32Be(0), - nonce: HexU32Be(0), - version_bits: None, - id: 42, - }; + impl IsClient for TestClient { + type Error = Error; + + fn handle_notify(&mut self, _: Option, notify: Notify) -> Result<(), Error> { + self.record(format!("notify {}", notify.job_id)) + } - let response = server - .handle_message(None, request.into()) - .unwrap() - .expect("unauthorized mining.submit must receive a response"); + fn handle_set_difficulty( + &mut self, + _: Option, + set: SetDifficulty, + ) -> Result<(), Error> { + self.record(format!("difficulty {}", set.difficulty)) + } - assert_eq!(response.result, serde_json::Value::Null); - let error = response - .error - .expect("unauthorized mining.submit must include an error"); - assert_eq!(error.code, 24); + fn handle_set_extranonce( + &mut self, + _: Option, + set: SetExtranonce, + ) -> Result<(), Error> { + self.record(format!("extranonce {}", set.extranonce2_size)) + } + + fn handle_set_version_mask( + &mut self, + _: Option, + set: SetVersionMask, + ) -> Result<(), Error> { + self.record(format!("mask {}", set.mask)) + } + + fn handle_configure_result( + &mut self, + _: Option, + id: &Id, + _: ConfigureResult, + ) -> Result<(), Error> { + self.record(format!("configure {id}")) + } + + fn handle_subscribe_result( + &mut self, + _: Option, + id: &Id, + _: SubscribeResult, + ) -> Result<(), Error> { + self.record(format!("subscribe {id}")) + } + + fn handle_authorize_result( + &mut self, + _: Option, + id: &Id, + authorized: bool, + ) -> Result<(), Error> { + self.record(format!("authorize {id} {authorized}")) + } + + fn handle_submit_result( + &mut self, + _: Option, + id: &Id, + accepted: bool, + ) -> Result<(), Error> { + self.record(format!("submit {id} {accepted}")) + } + + fn handle_extranonce_subscribe_result( + &mut self, + _: Option, + id: &Id, + acknowledged: bool, + ) -> Result<(), Error> { + self.record(format!("extranonce_subscribe {id} {acknowledged}")) + } + + fn handle_error_response( + &mut self, + _: Option, + id: &Id, + method: Method, + error: RpcError, + ) -> Result<(), Error> { + self.record(format!("error {id} {method} {}", error.code)) + } } #[test] - fn version_mask_invalid_len() { - let raw = serde_json::json!([ - "mining.set_version_mask", - ["123456789"] // len > 8 bytes - ]); + fn server_messages_are_routed() { + let mut client = TestClient::default(); + for message in client_impl_events() { + client.handle_message(None, message).unwrap(); + } + assert_eq!(client.events, CLIENT_EVENTS); + } + + /// Records which handler ran, to check the async router against the sync one. + #[derive(Default)] + struct AsyncTestClient { + events: Vec, + } + + impl AsyncTestClient { + fn record(&mut self, event: String) -> Result<(), Error> { + self.events.push(event); + Ok(()) + } + } - let msg: Result = serde_json::from_value(raw); + impl IsClientAsync for AsyncTestClient { + type Error = Error; - if let Ok(msg) = msg { - let result = Method::try_from(msg); - assert!(result.is_err(), "Expected error for invalid hex length"); + async fn handle_notify(&mut self, _: Option, notify: Notify) -> Result<(), Error> { + self.record(format!("notify {}", notify.job_id)) + } - match result.unwrap_err() { - MethodError::ParsingMethodError((ParsingMethodError::InvalidHexLen(_), _)) => {} - other => panic!("Expected InvalidHexLen, got {:?}", other), - } - } else { - panic!("Message parsing failed unexpectedly"); + async fn handle_set_difficulty( + &mut self, + _: Option, + set: SetDifficulty, + ) -> Result<(), Error> { + self.record(format!("difficulty {}", set.difficulty)) + } + + async fn handle_set_extranonce( + &mut self, + _: Option, + set: SetExtranonce, + ) -> Result<(), Error> { + self.record(format!("extranonce {}", set.extranonce2_size)) + } + + async fn handle_set_version_mask( + &mut self, + _: Option, + set: SetVersionMask, + ) -> Result<(), Error> { + self.record(format!("mask {}", set.mask)) + } + + async fn handle_configure_result( + &mut self, + _: Option, + id: &Id, + _: ConfigureResult, + ) -> Result<(), Error> { + self.record(format!("configure {id}")) + } + + async fn handle_subscribe_result( + &mut self, + _: Option, + id: &Id, + _: SubscribeResult, + ) -> Result<(), Error> { + self.record(format!("subscribe {id}")) + } + + async fn handle_authorize_result( + &mut self, + _: Option, + id: &Id, + authorized: bool, + ) -> Result<(), Error> { + self.record(format!("authorize {id} {authorized}")) + } + + async fn handle_submit_result( + &mut self, + _: Option, + id: &Id, + accepted: bool, + ) -> Result<(), Error> { + self.record(format!("submit {id} {accepted}")) + } + + async fn handle_extranonce_subscribe_result( + &mut self, + _: Option, + id: &Id, + acknowledged: bool, + ) -> Result<(), Error> { + self.record(format!("extranonce_subscribe {id} {acknowledged}")) + } + + async fn handle_error_response( + &mut self, + _: Option, + id: &Id, + method: Method, + error: RpcError, + ) -> Result<(), Error> { + self.record(format!("error {id} {method} {}", error.code)) } } + #[test] - fn subscribe_extranonce1_too_long_must_not_panic() { - // Extranonce1 hex that decodes to 33 bytes, exceeding the B032 - // 32-byte cap. Extranonce::try_from returns Error::BadBytesConvert, - // which From for ParsingMethodError (sv1/src/methods/mod.rs) - // must map to ParsingMethodError::BadBytesConvert instead of panicking. - let extranonce1 = "00".repeat(33); - let raw = serde_json::json!({ - "id": 1, - "method": "mining.subscribe", - "params": ["agent", extranonce1], - }); - let msg: Message = serde_json::from_value(raw).unwrap(); - assert!(Method::try_from(msg).is_err()); + fn async_server_messages_are_routed() { + let mut client = AsyncTestClient::default(); + for message in client_impl_events() { + run(client.handle_message(None, message)).unwrap(); + } + assert_eq!(client.events, CLIENT_EVENTS); } } diff --git a/sv1/src/messages/authorize.rs b/sv1/src/messages/authorize.rs new file mode 100644 index 0000000000..7c0a5bd790 --- /dev/null +++ b/sv1/src/messages/authorize.rs @@ -0,0 +1,42 @@ +//! `mining.authorize`. + +use crate::{error::ParamError, utils::params_array_mut}; +use serde_json::Value; +use std::{fmt, mem::take}; + +/// `mining.authorize`. +#[derive(Clone, PartialEq, Eq)] +pub struct Authorize { + pub worker_name: String, + /// Empty when the miner omitted it or sent `null`. + pub password: String, +} + +impl Authorize { + pub(super) fn from_params(params: &mut Value) -> Result { + let (worker_name, password) = match params_array_mut(params)? { + [Value::String(name), Value::String(password)] => (take(name), take(password)), + [Value::String(name)] | [Value::String(name), Value::Null] => { + (take(name), String::new()) + } + _ => return Err(ParamError::new("params", "unexpected authorize params")), + }; + Ok(Authorize { + worker_name, + password, + }) + } + + pub(super) fn to_params(&self) -> Value { + Value::from(vec![self.worker_name.as_str(), self.password.as_str()]) + } +} + +impl fmt::Debug for Authorize { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Authorize") + .field("worker_name", &self.worker_name) + .field("password", &format_args!("")) + .finish() + } +} diff --git a/sv1/src/messages/configure.rs b/sv1/src/messages/configure.rs new file mode 100644 index 0000000000..eb5ac420ae --- /dev/null +++ b/sv1/src/messages/configure.rs @@ -0,0 +1,292 @@ +//! `mining.configure`, as defined by [BIP 310](https://github.com/bitcoin/bips/blob/master/bip-0310.mediawiki). + +use crate::{ + error::ParamError, + utils::{hex_u32, min_bit_count, params_array, HexU32Be, VERSION_ROLLING_MASK}, +}; +use serde::{de, Deserialize, Deserializer}; +use serde_json::{Map, Value}; +use std::{convert::TryFrom, fmt}; + +/// `mining.configure`, as defined by [BIP 310](https://github.com/bitcoin/bips/blob/master/bip-0310.mediawiki). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Configure { + pub extensions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ConfigureExtension { + VersionRolling(VersionRolling), + MinimumDifficulty(u64), + SubscribeExtranonce, + Info(InfoParams), +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct VersionRolling { + pub mask: Option, + pub min_bit_count: Option, +} + +#[derive(Clone, Default, PartialEq, Eq)] +pub struct InfoParams { + /// May carry credentials, so it is redacted from `Debug`. + pub connection_url: Option, + pub hw_id: Option, + pub hw_version: Option, + pub sw_version: Option, +} + +impl Configure { + pub fn with_version_rolling(mask: Option, min_bit_count: Option) -> Self { + Configure { + extensions: vec![ConfigureExtension::VersionRolling(VersionRolling { + mask, + min_bit_count, + })], + } + } + + pub fn version_rolling(&self) -> Option<&VersionRolling> { + self.extensions + .iter() + .find_map(|extension| match extension { + ConfigureExtension::VersionRolling(params) => Some(params), + _ => None, + }) + } + + /// The requested mask, defaulting to [`VERSION_ROLLING_MASK`] when only a count was sent. + pub fn version_rolling_mask(&self) -> Option { + self.version_rolling() + .map(|params| params.mask.unwrap_or(HexU32Be(VERSION_ROLLING_MASK))) + } + + /// The requested minimum bit count, defaulting to zero when only a mask was sent. + pub fn version_rolling_min_bit_count(&self) -> Option { + self.version_rolling() + .map(|params| params.min_bit_count.unwrap_or(0)) + } + + pub fn supports_extranonce(&self) -> bool { + self.extensions + .iter() + .any(|extension| matches!(extension, ConfigureExtension::SubscribeExtranonce)) + } + + /// Accepts a missing or null parameter object, and ignores elements after it. + pub(super) fn from_params(params: &Value) -> Result { + let params = params_array(params)?; + let codes = params + .first() + .ok_or(ParamError::new("extensions", "missing"))? + .as_array() + .ok_or(ParamError::new("extensions", "not an array"))?; + let parameter = |name: &str| params.get(1).and_then(|parameters| parameters.get(name)); + let string = |name: &'static str| match parameter(name) { + None => Ok(None), + Some(Value::String(value)) => Ok(Some(value.clone())), + Some(_) => Err(ParamError::new(name, "not a string")), + }; + + let mut extensions = vec![]; + if codes.iter().any(|code| code == "subscribe-extranonce") { + extensions.push(ConfigureExtension::SubscribeExtranonce); + } + + let mask = match parameter("version-rolling.mask") { + None => None, + Some(Value::String(mask)) => Some(hex_u32(mask, "version-rolling.mask")?), + Some(_) => return Err(ParamError::new("version-rolling.mask", "not a string")), + }; + let min_bit_count = match parameter("version-rolling.min-bit-count") { + None => None, + Some(_) if mask.is_none() => { + return Err(ParamError::new("version-rolling.mask", "missing")) + } + Some(count) => Some(min_bit_count(count, "version-rolling.min-bit-count")?), + }; + if mask.is_some() { + extensions.push(ConfigureExtension::VersionRolling(VersionRolling { + mask, + min_bit_count, + })); + } + + if let Some(value) = parameter("minimum-difficulty.value") { + let value = value.as_u64().ok_or(ParamError::new( + "minimum-difficulty.value", + "not an unsigned integer", + ))?; + extensions.push(ConfigureExtension::MinimumDifficulty(value)); + } + + let info = InfoParams { + connection_url: string("info.connection-url")?, + hw_id: string("info.hw-id")?, + hw_version: string("info.hw-version")?, + sw_version: string("info.sw-version")?, + }; + if info != InfoParams::default() { + extensions.push(ConfigureExtension::Info(info)); + } + + Ok(Configure { extensions }) + } + + pub(super) fn to_params(&self) -> Value { + let mut codes = vec![]; + let mut parameters = Map::new(); + for extension in &self.extensions { + match extension { + ConfigureExtension::VersionRolling(params) => { + codes.push("version-rolling"); + if let Some(mask) = ¶ms.mask { + parameters.insert("version-rolling.mask".into(), (*mask).into()); + } + if let Some(count) = params.min_bit_count { + parameters.insert("version-rolling.min-bit-count".into(), count.into()); + } + } + ConfigureExtension::MinimumDifficulty(value) => { + codes.push("minimum-difficulty"); + parameters.insert("minimum-difficulty.value".into(), (*value).into()); + } + ConfigureExtension::SubscribeExtranonce => codes.push("subscribe-extranonce"), + ConfigureExtension::Info(info) => { + codes.push("info"); + for (name, value) in [ + ("info.connection-url", &info.connection_url), + ("info.hw-id", &info.hw_id), + ("info.hw-version", &info.hw_version), + ("info.sw-version", &info.sw_version), + ] { + if let Some(value) = value { + parameters.insert(name.into(), value.clone().into()); + } + } + } + } + } + Value::Array(vec![codes.into(), parameters.into()]) + } +} + +impl fmt::Debug for InfoParams { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("InfoParams") + .field( + "connection_url", + &self + .connection_url + .as_ref() + .map(|_| format_args!("")), + ) + .field("hw_id", &self.hw_id) + .field("hw_version", &self.hw_version) + .field("sw_version", &self.sw_version) + .finish() + } +} + +/// Result of `mining.configure`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ConfigureResult { + pub version_rolling: Option, + pub minimum_difficulty: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VersionRollingResult { + pub enabled: bool, + pub mask: HexU32Be, + pub min_bit_count: u32, +} + +impl VersionRollingResult { + /// Enables version rolling, clamping the mask to [`VERSION_ROLLING_MASK`] so it never covers + /// reserved bits. + pub fn new(mask: HexU32Be, min_bit_count: u32) -> Self { + VersionRollingResult { + enabled: true, + mask: mask & VERSION_ROLLING_MASK, + min_bit_count, + } + } +} + +/// The mask is clamped to [`VERSION_ROLLING_MASK`], so reserved bits are never offered. +impl From for Value { + fn from(result: ConfigureResult) -> Self { + let mut values = Map::new(); + if let Some(version_rolling) = result.version_rolling { + values.insert("version-rolling".into(), version_rolling.enabled.into()); + values.insert( + "version-rolling.mask".into(), + (version_rolling.mask & VERSION_ROLLING_MASK).into(), + ); + values.insert( + "version-rolling.min-bit-count".into(), + HexU32Be(version_rolling.min_bit_count).into(), + ); + } + if let Some(minimum_difficulty) = result.minimum_difficulty { + values.insert("minimum-difficulty".into(), minimum_difficulty.into()); + } + values.into() + } +} + +impl ConfigureResult { + /// Version rolling needs both `version-rolling` and `version-rolling.mask`; a missing + /// `version-rolling.min-bit-count` reads as zero. The mask is clamped to + /// [`VERSION_ROLLING_MASK`], so a client never rolls reserved bits. + fn from_value(result: &Value) -> Result { + let values = result + .as_object() + .ok_or(ParamError::new("result", "not an object"))?; + let enabled = values.get("version-rolling"); + let mask = values.get("version-rolling.mask"); + let count = values.get("version-rolling.min-bit-count"); + let version_rolling = match (enabled, mask) { + (Some(enabled), Some(mask)) => Some(VersionRollingResult { + enabled: enabled + .as_bool() + .ok_or(ParamError::new("version-rolling", "not a boolean"))?, + mask: mask + .as_str() + .and_then(|mask| HexU32Be::try_from(mask).ok()) + .map(|mask| mask & VERSION_ROLLING_MASK) + .ok_or(ParamError::new( + "version-rolling.mask", + "not a 32-bit hex value", + ))?, + min_bit_count: count + .map(|count| min_bit_count(count, "version-rolling.min-bit-count")) + .transpose()? + .unwrap_or(0), + }), + (None, None) if count.is_none() => None, + _ => return Err(ParamError::new("version-rolling", "incomplete")), + }; + let minimum_difficulty = values + .get("minimum-difficulty") + .map(|value| { + value + .as_bool() + .ok_or(ParamError::new("minimum-difficulty", "not a boolean")) + }) + .transpose()?; + Ok(ConfigureResult { + version_rolling, + minimum_difficulty, + }) + } +} + +impl<'de> Deserialize<'de> for ConfigureResult { + fn deserialize>(deserializer: D) -> Result { + ConfigureResult::from_value(&Value::deserialize(deserializer)?).map_err(de::Error::custom) + } +} diff --git a/sv1/src/messages/mod.rs b/sv1/src/messages/mod.rs new file mode 100644 index 0000000000..dc17fda405 --- /dev/null +++ b/sv1/src/messages/mod.rs @@ -0,0 +1,296 @@ +//! Typed SV1 messages, grouped by operation. +//! +//! [`ClientToServer`] and [`ServerToClient`] name the direction a message travels. A request and +//! its reply are [`Request`] and [`Response`] envelopes around the operation's own types. + +mod authorize; +mod configure; +mod notifications; +mod submit; +mod subscribe; +mod suggest_difficulty; + +pub use authorize::Authorize; +pub use configure::{ + Configure, ConfigureExtension, ConfigureResult, InfoParams, VersionRolling, + VersionRollingResult, +}; +pub use notifications::{Notify, SetDifficulty, SetExtranonce, SetVersionMask}; +pub use submit::{Submit, SubmitError, SubmitOutcome}; +pub use subscribe::{ExtranonceSubscribe, Subscribe, SubscribeResult}; +pub use suggest_difficulty::SuggestDifficulty; + +use crate::{ + error::{DecodeError, DecodeErrorKind, Error}, + json_rpc::{self, decode_value, Id, Message, Method, RpcError}, +}; +use serde::de::DeserializeOwned; +use serde_json::Value; +use std::convert::TryFrom; + +/// A request, with the ID its reply must echo. +#[derive(Clone, Debug, PartialEq)] +pub struct Request

{ + pub id: Id, + pub params: P, +} + +/// The reply to a request: its result, or the error the server answered with. +#[derive(Clone, Debug, PartialEq)] +pub struct Response { + pub id: Id, + pub result: Result, +} + +impl Response { + pub fn success(id: Id, result: R) -> Self { + Response { + id, + result: Ok(result), + } + } + + pub fn failure(id: Id, error: RpcError) -> Self { + Response { + id, + result: Err(error), + } + } +} + +impl Response { + /// Types the reply to the `method` request with this ID. A malformed result keeps both, so + /// the caller can tell which request failed. + fn decode(id: Id, method: &Method, result: &Result) -> Result { + let result = match result { + Ok(value) => match decode_value(value) { + Ok(result) => Ok(result), + Err(error) => { + return Err(Error::InvalidResult { + id, + method: method.clone(), + error, + }) + } + }, + Err(error) => Err(error.clone()), + }; + Ok(Response { id, result }) + } +} + +impl> From> for json_rpc::Response { + fn from(response: Response) -> Self { + json_rpc::Response { + id: Some(response.id), + result: response.result.map(Into::into), + } + } +} + +impl> From> for Message { + fn from(response: Response) -> Self { + Message::Response(response.into()) + } +} + +/// A message a client sends to a server. +#[derive(Clone, Debug, PartialEq)] +pub enum ClientToServer { + Configure(Request), + Subscribe(Request), + Authorize(Request), + Submit(Request), + ExtranonceSubscribe(Request), + /// Servers are not required to reply. + SuggestDifficulty(Request), +} + +impl ClientToServer { + pub fn method(&self) -> Method { + match self { + ClientToServer::Configure(_) => Method::Configure, + ClientToServer::Subscribe(_) => Method::Subscribe, + ClientToServer::Authorize(_) => Method::Authorize, + ClientToServer::Submit(_) => Method::Submit, + ClientToServer::ExtranonceSubscribe(_) => Method::ExtranonceSubscribe, + ClientToServer::SuggestDifficulty(_) => Method::SuggestDifficulty, + } + } + + pub fn id(&self) -> &Id { + match self { + ClientToServer::Configure(Request { id, .. }) + | ClientToServer::Subscribe(Request { id, .. }) + | ClientToServer::Authorize(Request { id, .. }) + | ClientToServer::Submit(Request { id, .. }) + | ClientToServer::ExtranonceSubscribe(Request { id, .. }) + | ClientToServer::SuggestDifficulty(Request { id, .. }) => id, + } + } +} + +impl TryFrom for ClientToServer { + type Error = DecodeError; + + fn try_from(request: json_rpc::Request) -> Result { + let json_rpc::Request { + id, + method, + mut params, + } = request; + let error = |kind| DecodeError::about(id.clone(), Some(method.clone()), kind); + let Some(id) = id.clone() else { + return Err(error(DecodeErrorKind::MissingId)); + }; + let message = match &method { + Method::Configure => Configure::from_params(¶ms) + .map(|params| ClientToServer::Configure(Request { id, params })), + Method::Subscribe => Subscribe::from_params(&mut params) + .map(|params| ClientToServer::Subscribe(Request { id, params })), + Method::Authorize => Authorize::from_params(&mut params) + .map(|params| ClientToServer::Authorize(Request { id, params })), + Method::Submit => Submit::from_params(&mut params) + .map(|params| ClientToServer::Submit(Request { id, params })), + Method::ExtranonceSubscribe => Ok(ClientToServer::ExtranonceSubscribe(Request { + id, + params: ExtranonceSubscribe, + })), + Method::SuggestDifficulty => Ok(ClientToServer::SuggestDifficulty(Request { + id, + params: SuggestDifficulty::from_params(¶ms), + })), + _ => return Err(error(DecodeErrorKind::UnknownMethod)), + }; + message.map_err(|e| error(e.into())) + } +} + +/// A response is an error: only requests are expected. +impl TryFrom for ClientToServer { + type Error = DecodeError; + + fn try_from(message: Message) -> Result { + match message { + Message::Request(request) => ClientToServer::try_from(request), + Message::Response(response) => Err(DecodeError::about( + response.id, + None, + DecodeErrorKind::UnexpectedResponse, + )), + } + } +} + +impl From for Message { + fn from(message: ClientToServer) -> Self { + let method = message.method(); + let (id, params) = match message { + ClientToServer::Configure(Request { id, params }) => (id, params.to_params()), + ClientToServer::Subscribe(Request { id, params }) => (id, params.to_params()), + ClientToServer::Authorize(Request { id, params }) => (id, params.to_params()), + ClientToServer::Submit(Request { id, params }) => (id, params.to_params()), + ClientToServer::ExtranonceSubscribe(Request { id, .. }) => (id, Value::Array(vec![])), + ClientToServer::SuggestDifficulty(Request { id, params }) => (id, params.to_params()), + }; + Message::request(Some(id), method, params) + } +} + +/// A message a server sends to a client: the reply to a request, or a notification. +#[derive(Clone, Debug, PartialEq)] +pub enum ServerToClient { + Configure(Response), + Subscribe(Response), + Authorize(Response), + Submit(Response), + ExtranonceSubscribe(Response), + Notify(Notify), + SetDifficulty(SetDifficulty), + SetExtranonce(SetExtranonce), + SetVersionMask(SetVersionMask), +} + +impl ServerToClient { + /// The method of the notification, or of the request a reply answers. + pub fn method(&self) -> Method { + match self { + ServerToClient::Configure(_) => Method::Configure, + ServerToClient::Subscribe(_) => Method::Subscribe, + ServerToClient::Authorize(_) => Method::Authorize, + ServerToClient::Submit(_) => Method::Submit, + ServerToClient::ExtranonceSubscribe(_) => Method::ExtranonceSubscribe, + ServerToClient::Notify(_) => Method::Notify, + ServerToClient::SetDifficulty(_) => Method::SetDifficulty, + ServerToClient::SetExtranonce(_) => Method::SetExtranonce, + ServerToClient::SetVersionMask(_) => Method::SetVersionMask, + } + } + + /// Types `response` as the reply to a `method` request. A response does not name the method + /// it answers, so the caller supplies it. + /// + /// Returns `None` when the response has no ID, or `method` is not one that has a result. + pub fn from_response( + response: &json_rpc::Response, + method: &Method, + ) -> Result, Error> { + let Some(id) = response.id.clone() else { + return Ok(None); + }; + let result = &response.result; + Ok(Some(match method { + Method::Configure => ServerToClient::Configure(Response::decode(id, method, result)?), + Method::Subscribe => ServerToClient::Subscribe(Response::decode(id, method, result)?), + Method::Authorize => ServerToClient::Authorize(Response::decode(id, method, result)?), + Method::Submit => ServerToClient::Submit(Response::decode(id, method, result)?), + Method::ExtranonceSubscribe => { + ServerToClient::ExtranonceSubscribe(Response::decode(id, method, result)?) + } + _ => return Ok(None), + })) + } +} + +/// Types a notification. A reply is typed with [`ServerToClient::from_response`]. +/// +/// Any request ID is ignored, so a server that attaches one to a notification is still +/// understood. +impl TryFrom for ServerToClient { + type Error = DecodeError; + + fn try_from(mut request: json_rpc::Request) -> Result { + let error = + |kind| DecodeError::about(request.id.clone(), Some(request.method.clone()), kind); + let message = match &request.method { + Method::Notify => Notify::from_params(&mut request.params).map(ServerToClient::Notify), + Method::SetDifficulty => { + SetDifficulty::from_params(&request.params).map(ServerToClient::SetDifficulty) + } + Method::SetExtranonce => { + SetExtranonce::from_params(&request.params).map(ServerToClient::SetExtranonce) + } + Method::SetVersionMask => { + SetVersionMask::from_params(&request.params).map(ServerToClient::SetVersionMask) + } + _ => return Err(error(DecodeErrorKind::UnknownMethod)), + }; + message.map_err(|e| error(e.into())) + } +} + +impl From for Message { + fn from(message: ServerToClient) -> Self { + match message { + ServerToClient::Configure(response) => response.into(), + ServerToClient::Subscribe(response) => response.into(), + ServerToClient::Authorize(response) + | ServerToClient::Submit(response) + | ServerToClient::ExtranonceSubscribe(response) => response.into(), + ServerToClient::Notify(notify) => notify.into(), + ServerToClient::SetDifficulty(set) => set.into(), + ServerToClient::SetExtranonce(set) => set.into(), + ServerToClient::SetVersionMask(set) => set.into(), + } + } +} diff --git a/sv1/src/messages/notifications.rs b/sv1/src/messages/notifications.rs new file mode 100644 index 0000000000..b51e04ea8e --- /dev/null +++ b/sv1/src/messages/notifications.rs @@ -0,0 +1,192 @@ +//! Notifications a server sends to a client. + +use crate::{ + error::ParamError, + json_rpc::{Message, Method}, + utils::{ + extranonce2_size_param, hex_decode, hex_u32, params_array, params_array_mut, Extranonce, + HexBytes, HexU32Be, MerkleNode, PrevHash, MAX_EXTRANONCE_LEN, + }, +}; +use serde_json::Value; +use std::{convert::TryFrom, mem::take}; + +/// `mining.notify`: a new job. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notify { + pub job_id: String, + pub prev_hash: PrevHash, + pub coinbase1: HexBytes, + pub coinbase2: HexBytes, + pub merkle_branch: Vec, + pub version: HexU32Be, + pub nbits: HexU32Be, + pub ntime: HexU32Be, + /// The miner should abandon its current work. + pub clean_jobs: bool, +} + +/// `mining.set_difficulty`, applied from the next job. +#[derive(Clone, Debug, PartialEq)] +pub struct SetDifficulty { + /// Must be finite and positive to be sent. + pub difficulty: f64, +} + +/// `mining.set_extranonce`, applied from the next job. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SetExtranonce { + pub extranonce1: Extranonce, + pub extranonce2_size: usize, +} + +/// `mining.set_version_mask`, applied immediately. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SetVersionMask { + pub mask: HexU32Be, +} + +impl From for Message { + fn from(notify: Notify) -> Self { + let merkle_branch: Vec = notify + .merkle_branch + .into_iter() + .map(|node| String::from(node).into()) + .collect(); + Message::notification( + Method::Notify, + vec![ + notify.job_id.into(), + notify.prev_hash.into(), + notify.coinbase1.into(), + notify.coinbase2.into(), + merkle_branch.into(), + notify.version.into(), + notify.nbits.into(), + notify.ntime.into(), + notify.clean_jobs.into(), + ], + ) + } +} + +impl From for Message { + /// # Panics + /// + /// If the difficulty is not finite and positive, which no miner can work with. + fn from(set: SetDifficulty) -> Self { + assert!( + set.difficulty.is_finite() && set.difficulty > 0.0, + "mining.set_difficulty must be finite and positive, got {}", + set.difficulty + ); + Message::notification(Method::SetDifficulty, vec![set.difficulty.into()]) + } +} + +impl From for Message { + fn from(set: SetExtranonce) -> Self { + Message::notification( + Method::SetExtranonce, + vec![set.extranonce1.into(), set.extranonce2_size.into()], + ) + } +} + +impl From for Message { + fn from(set: SetVersionMask) -> Self { + Message::notification(Method::SetVersionMask, vec![set.mask.into()]) + } +} + +/// A block's merkle branch has at most one entry per level of a 2^32-transaction tree. +const MAX_MERKLE_BRANCH_LEN: usize = 32; + +impl Notify { + pub(super) fn from_params(params: &mut Value) -> Result { + let [Value::String(job_id), Value::String(prev_hash), Value::String(coinbase1), Value::String(coinbase2), Value::Array(merkle_branch), Value::String(version), Value::String(nbits), Value::String(ntime), Value::Bool(clean_jobs)] = + params_array_mut(params)? + else { + return Err(ParamError::new("params", "unexpected notify params")); + }; + if merkle_branch.len() > MAX_MERKLE_BRANCH_LEN { + return Err(ParamError::new("merkle_branch", "longer than 32 entries")); + } + let merkle_branch = merkle_branch + .iter() + .map(|node| { + node.as_str() + .and_then(|node| MerkleNode::try_from(node).ok()) + .ok_or(ParamError::new("merkle_branch", "not 32 bytes of hex")) + }) + .collect::>()?; + Ok(Notify { + job_id: take(job_id), + prev_hash: PrevHash::try_from(prev_hash.as_str()) + .map_err(|_| ParamError::new("prev_hash", "not 32 bytes of hex"))?, + coinbase1: HexBytes::try_from(coinbase1.as_str()) + .map_err(|_| ParamError::new("coinbase1", "not hex"))?, + coinbase2: HexBytes::try_from(coinbase2.as_str()) + .map_err(|_| ParamError::new("coinbase2", "not hex"))?, + merkle_branch, + version: hex_u32(version, "version")?, + nbits: hex_u32(nbits, "nbits")?, + ntime: hex_u32(ntime, "ntime")?, + clean_jobs: *clean_jobs, + }) + } +} + +impl SetDifficulty { + pub(super) fn from_params(params: &Value) -> Result { + match params_array(params)? { + [difficulty] => difficulty + .as_f64() + .filter(|difficulty| *difficulty > 0.0) + .map(|difficulty| SetDifficulty { difficulty }) + .ok_or(ParamError::new("difficulty", "not a positive number")), + _ => Err(ParamError::new( + "params", + "unexpected set_difficulty params", + )), + } + } +} + +impl SetExtranonce { + pub(super) fn from_params(params: &Value) -> Result { + let [Value::String(extranonce1), Value::Number(extranonce2_size)] = params_array(params)? + else { + return Err(ParamError::new( + "params", + "unexpected set_extranonce params", + )); + }; + if extranonce1.len() > 2 * MAX_EXTRANONCE_LEN { + return Err(ParamError::new( + "extranonce1", + "not hex of at most 32 bytes", + )); + } + Ok(SetExtranonce { + extranonce1: hex_decode(extranonce1) + .and_then(Extranonce::try_from) + .map_err(|_| ParamError::new("extranonce1", "not hex of at most 32 bytes"))?, + extranonce2_size: extranonce2_size_param(extranonce2_size)?, + }) + } +} + +impl SetVersionMask { + pub(super) fn from_params(params: &Value) -> Result { + match params_array(params)? { + [Value::String(mask)] => Ok(SetVersionMask { + mask: hex_u32(mask, "mask")?, + }), + _ => Err(ParamError::new( + "params", + "unexpected set_version_mask params", + )), + } + } +} diff --git a/sv1/src/messages/submit.rs b/sv1/src/messages/submit.rs new file mode 100644 index 0000000000..51efedffe3 --- /dev/null +++ b/sv1/src/messages/submit.rs @@ -0,0 +1,163 @@ +//! `mining.submit`. + +use super::Response; +use crate::{ + error::ParamError, + json_rpc::{Id, RpcError}, + utils::{ + hex_decode, hex_u32, integer_u32, params_array_mut, Extranonce, HexU32Be, + MAX_EXTRANONCE_LEN, + }, +}; +use serde_json::Value; +use std::{convert::TryFrom, mem::take}; + +/// `mining.submit`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Submit { + pub worker_name: String, + pub job_id: String, + pub extranonce2: Extranonce, + pub ntime: HexU32Be, + pub nonce: HexU32Be, + /// Present when version rolling is negotiated. + pub version_bits: Option, +} + +impl Submit { + /// `ntime` and `nonce` are hex strings, or both JSON integers; short hex is left-padded. + pub(super) fn from_params(params: &mut Value) -> Result { + let params = params_array_mut(params)?; + let (worker_name, job_id, extranonce2, ntime, nonce, version_bits) = match params { + [Value::String(worker), Value::String(job), Value::String(extranonce2), ntime, nonce, rest @ ..] + if rest.len() <= 1 => + { + (worker, job, extranonce2, ntime, nonce, rest.first()) + } + _ => return Err(ParamError::new("params", "unexpected submit params")), + }; + let (ntime, nonce) = match (ntime, nonce) { + (Value::String(ntime), Value::String(nonce)) => { + (hex_u32(ntime, "ntime")?, hex_u32(nonce, "nonce")?) + } + (Value::Number(ntime), Value::Number(nonce)) => { + (integer_u32(ntime, "ntime")?, integer_u32(nonce, "nonce")?) + } + _ => return Err(ParamError::new("params", "ntime and nonce differ in type")), + }; + let version_bits = match version_bits { + None => None, + Some(Value::String(bits)) => Some(hex_u32(bits, "version_bits")?), + Some(_) => return Err(ParamError::new("version_bits", "not a string")), + }; + if extranonce2.len() > 2 * MAX_EXTRANONCE_LEN { + return Err(ParamError::new( + "extranonce2", + "not hex of at most 32 bytes", + )); + } + let extranonce2 = hex_decode(extranonce2) + .and_then(Extranonce::try_from) + .map_err(|_| ParamError::new("extranonce2", "not hex of at most 32 bytes"))?; + Ok(Submit { + worker_name: take(worker_name), + job_id: take(job_id), + extranonce2, + ntime, + nonce, + version_bits, + }) + } + + pub(super) fn to_params(&self) -> Value { + let mut params: Vec = vec![ + self.worker_name.clone().into(), + self.job_id.clone().into(), + self.extranonce2.clone().into(), + self.ntime.into(), + self.nonce.into(), + ]; + if let Some(bits) = &self.version_bits { + params.push((*bits).into()); + } + params.into() + } +} + +/// Result of validating a `mining.submit` request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SubmitOutcome { + Accepted, + Rejected(SubmitError), +} + +/// Standard Stratum V1 share-submission errors. +/// +/// These codes originate from the original Stratum mining protocol and remain the format used by +/// production SV1 servers such as CKPool. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SubmitError { + Other, + JobNotFound, + DuplicateShare, + LowDifficultyShare, + UnauthorizedWorker, + NotSubscribed, +} + +impl SubmitOutcome { + /// `result: true` on acceptance; `result: null` with the standard error on rejection. + pub fn into_response(self, id: Id) -> Response { + match self { + SubmitOutcome::Accepted => Response::success(id, true), + SubmitOutcome::Rejected(error) => Response::failure(id, error.into()), + } + } +} + +impl SubmitError { + pub const fn code(self) -> i32 { + match self { + Self::Other => 20, + Self::JobNotFound => 21, + Self::DuplicateShare => 22, + Self::LowDifficultyShare => 23, + Self::UnauthorizedWorker => 24, + Self::NotSubscribed => 25, + } + } + + /// The error with this code, or `None` when the code is not a standard one. + pub const fn from_code(code: i32) -> Option { + Some(match code { + 20 => Self::Other, + 21 => Self::JobNotFound, + 22 => Self::DuplicateShare, + 23 => Self::LowDifficultyShare, + 24 => Self::UnauthorizedWorker, + 25 => Self::NotSubscribed, + _ => return None, + }) + } + + pub const fn message(self) -> &'static str { + match self { + Self::Other => "Other/Unknown", + Self::JobNotFound => "Job not found", + Self::DuplicateShare => "Duplicate share", + Self::LowDifficultyShare => "Low difficulty share", + Self::UnauthorizedWorker => "Unauthorized worker", + Self::NotSubscribed => "Not subscribed", + } + } +} + +impl From for RpcError { + fn from(error: SubmitError) -> Self { + RpcError { + code: error.code(), + message: error.message().to_string(), + data: None, + } + } +} diff --git a/sv1/src/messages/subscribe.rs b/sv1/src/messages/subscribe.rs new file mode 100644 index 0000000000..e4ba015f51 --- /dev/null +++ b/sv1/src/messages/subscribe.rs @@ -0,0 +1,106 @@ +//! `mining.subscribe` and `mining.extranonce.subscribe`. + +use crate::{ + error::ParamError, + utils::{extranonce2_size_param, params_array_mut, Extranonce}, +}; +use serde::{de, Deserialize, Deserializer}; +use serde_json::Value; +use std::{convert::TryFrom, mem::take}; + +/// `mining.subscribe`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Subscribe { + /// Empty when the miner sent no user agent. + pub agent: String, + /// A subscription the miner asks to resume. The server decides whether to honour it. + pub subscription_id: Option, +} + +/// `mining.extranonce.subscribe`: the client supports `mining.set_extranonce`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ExtranonceSubscribe; + +impl Subscribe { + pub(super) fn from_params(params: &mut Value) -> Result { + let (agent, subscription_id) = match params_array_mut(params)? { + [] => (String::new(), None), + [Value::String(agent)] | [Value::String(agent), Value::Null] => (take(agent), None), + // bosminer + [Value::String(agent), Value::Null, Value::String(_), Value::Null] => { + (take(agent), None) + } + [Value::String(agent), Value::String(id)] => (take(agent), Some(take(id))), + _ => return Err(ParamError::new("params", "unexpected subscribe params")), + }; + Ok(Subscribe { + agent, + subscription_id, + }) + } + + pub(super) fn to_params(&self) -> Value { + match (self.agent.as_str(), &self.subscription_id) { + ("", None) => Value::Array(vec![]), + (agent, None) => Value::from(vec![agent]), + (agent, Some(id)) => Value::from(vec![agent, id.as_str()]), + } + } +} + +/// Result of `mining.subscribe`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubscribeResult { + /// Pairs of notification method and subscription ID. + pub subscriptions: Vec<(String, String)>, + pub extranonce1: Extranonce, + pub extranonce2_size: usize, +} + +impl From for Value { + fn from(result: SubscribeResult) -> Self { + let subscriptions: Vec = result + .subscriptions + .into_iter() + .map(|(method, id)| Value::from(vec![method, id])) + .collect(); + Value::Array(vec![ + subscriptions.into(), + result.extranonce1.into(), + result.extranonce2_size.into(), + ]) + } +} + +impl SubscribeResult { + fn from_value(result: &Value) -> Result { + let Some([Value::Array(subscriptions), Value::String(extranonce1), Value::Number(size)]) = + result.as_array().map(Vec::as_slice) + else { + return Err(ParamError::new("result", "unexpected subscribe result")); + }; + let subscriptions = subscriptions + .iter() + .map( + |subscription| match subscription.as_array().map(Vec::as_slice) { + Some([Value::String(method), Value::String(id)]) => { + Ok((method.clone(), id.clone())) + } + _ => Err(ParamError::new("subscriptions", "not a pair of strings")), + }, + ) + .collect::>()?; + Ok(SubscribeResult { + subscriptions, + extranonce1: Extranonce::try_from(extranonce1.as_str()) + .map_err(|_| ParamError::new("extranonce1", "not hex of at most 32 bytes"))?, + extranonce2_size: extranonce2_size_param(size)?, + }) + } +} + +impl<'de> Deserialize<'de> for SubscribeResult { + fn deserialize>(deserializer: D) -> Result { + SubscribeResult::from_value(&Value::deserialize(deserializer)?).map_err(de::Error::custom) + } +} diff --git a/sv1/src/messages/suggest_difficulty.rs b/sv1/src/messages/suggest_difficulty.rs new file mode 100644 index 0000000000..decfeebbfc --- /dev/null +++ b/sv1/src/messages/suggest_difficulty.rs @@ -0,0 +1,24 @@ +//! `mining.suggest_difficulty`. + +use serde_json::Value; + +/// `mining.suggest_difficulty`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SuggestDifficulty { + /// `None` when the params hold no usable difficulty. Servers are not required to honour it. + pub difficulty: Option, +} + +impl SuggestDifficulty { + pub(super) fn from_params(params: &Value) -> Self { + let difficulty = match params.as_array().map(Vec::as_slice) { + Some([difficulty]) => difficulty.as_f64().filter(|d| d.is_finite() && *d >= 0.0), + _ => None, + }; + SuggestDifficulty { difficulty } + } + + pub(super) fn to_params(&self) -> Value { + Value::Array(self.difficulty.into_iter().map(Value::from).collect()) + } +} diff --git a/sv1/src/methods/client_to_server.rs b/sv1/src/methods/client_to_server.rs deleted file mode 100644 index ac98b9136b..0000000000 --- a/sv1/src/methods/client_to_server.rs +++ /dev/null @@ -1,1034 +0,0 @@ -use crate::utils::hex_decode; -use bitcoin::hashes::hex::DisplayHex; -use serde_json::{ - Value, - Value::{Array as JArrary, Null, Number as JNumber, String as JString}, -}; -use std::convert::{TryFrom, TryInto}; -use std::fmt; - -use crate::{ - error::Error, - json_rpc::{JsonRpcError, Message, Response, StandardRequest}, - methods::ParsingMethodError, - utils::{Extranonce, HexU32Be, VERSION_ROLLING_MASK}, -}; - -#[cfg(test)] -use quickcheck::{Arbitrary, Gen}; - -#[cfg(test)] -use quickcheck_macros; - -/// _mining.authorize("username", "password")_ -/// -/// The result from an authorize request is usually true (successful), or false. -/// The password may be omitted if the server does not require passwords. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Authorize { - pub id: u64, - pub name: String, - pub password: String, -} - -impl fmt::Display for Authorize { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Authorize {{ id: {}, name: {}, password: }}", - self.id, self.name - ) - } -} - -impl Authorize { - pub fn respond(self, is_ok: bool) -> Response { - // infallible - let result = serde_json::to_value(is_ok).unwrap(); - Response { - id: self.id, - result, - error: None, - } - } -} - -impl From for Message { - fn from(auth: Authorize) -> Self { - Message::StandardRequest(StandardRequest { - id: auth.id, - method: "mining.authorize".into(), - params: (&[auth.name, auth.password][..]).into(), - }) - } -} - -impl TryFrom for Authorize { - type Error = ParsingMethodError; - - fn try_from(msg: StandardRequest) -> Result { - match msg.params.as_array() { - Some(params) => { - let (name, password) = match ¶ms[..] { - [JString(a), JString(b)] => (a.into(), b.into()), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - let id = msg.id; - Ok(Self { id, name, password }) - } - None => Err(ParsingMethodError::not_array_from_value(msg.params)), - } - } -} - -#[cfg(test)] -impl Arbitrary for Authorize { - fn arbitrary(g: &mut Gen) -> Self { - Authorize { - name: String::arbitrary(g), - password: String::arbitrary(g), - id: u64::arbitrary(g), - } - } -} - -#[cfg(test)] -#[quickcheck_macros::quickcheck] -fn from_to_json_rpc(auth: Authorize) -> bool { - let message = Into::::into(auth.clone()); - let request = match message { - Message::StandardRequest(s) => s, - _ => panic!(), - }; - auth == TryInto::::try_into(request).unwrap() -} - -// mining.capabilities (DRAFT) (incompatible with mining.configure) - -/// _mining.extranonce.subscribe()_ -/// -/// Indicates to the server that the client supports the `mining.set_extranonce` method, as -/// defined by the [NiceHash extranonce subscribe extension][a]. -/// -/// Parameters are ignored for compatibility with existing clients; only the request ID is kept. -/// -/// [a]: https://github.com/nicehash/Specifications/blob/master/NiceHash_extranonce_subscribe_extension.txt -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ExtranonceSubscribe { - pub id: u64, -} - -impl ExtranonceSubscribe { - pub fn respond(self) -> Response { - Response { - id: self.id, - result: Value::Bool(true), - error: None, - } - } -} - -impl From for Message { - fn from(subscribe: ExtranonceSubscribe) -> Self { - Message::StandardRequest(StandardRequest { - id: subscribe.id, - method: "mining.extranonce.subscribe".into(), - params: Value::Array(Vec::new()), - }) - } -} - -impl TryFrom for ExtranonceSubscribe { - type Error = ParsingMethodError; - - fn try_from(msg: StandardRequest) -> Result { - Ok(Self { id: msg.id }) - } -} - -// mining.get_transactions - -/// _mining.submit("username", "job id", "ExtraNonce2", "nTime", "nOnce")_ -/// -/// Miners submit shares using the method "mining.submit". Client submissions contain: -/// -/// * Worker Name. -/// * Job ID. -/// * ExtraNonce2. -/// * nTime. -/// * nOnce. -/// * version_bits (used by version-rolling extension) -/// -/// Server response is result: true for accepted, false for rejected (or you may get an error with -/// more details). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Submit { - pub user_name: String, // root - pub job_id: String, // 6 - pub extra_nonce2: Extranonce, // "8a.." - pub time: HexU32Be, //string - pub nonce: HexU32Be, - pub version_bits: Option, - pub id: u64, -} - -/// Result of validating a `mining.submit` request at the SV1 server boundary. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SubmitOutcome { - Accepted, - Rejected(SubmitError), -} - -/// Standard Stratum V1 share-submission errors. -/// -/// These codes originate from the original Stratum mining protocol and remain the format used by -/// production SV1 servers such as CKPool. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SubmitError { - Other, - JobNotFound, - DuplicateShare, - LowDifficultyShare, - UnauthorizedWorker, - NotSubscribed, -} - -impl SubmitError { - pub const fn code(self) -> i32 { - match self { - Self::Other => 20, - Self::JobNotFound => 21, - Self::DuplicateShare => 22, - Self::LowDifficultyShare => 23, - Self::UnauthorizedWorker => 24, - Self::NotSubscribed => 25, - } - } - - pub const fn message(self) -> &'static str { - match self { - Self::Other => "Other/Unknown", - Self::JobNotFound => "Job not found", - Self::DuplicateShare => "Duplicate share", - Self::LowDifficultyShare => "Low difficulty share", - Self::UnauthorizedWorker => "Unauthorized worker", - Self::NotSubscribed => "Not subscribed", - } - } -} -//"{"params": ["spotbtc1.m30s40x16", "2", "147a3f0000000000", "6436eddf", "41d5deb0", "00000000"], -//"{"params": "id": 2196, "method": "mining.submit"}" - -impl fmt::Display for Submit { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Submit {{ user_name: {}, job_id: {}, extra_nonce2: {}, time: {}, nonce: {}, version_bits: {:?}, id: {} }}", - self.user_name, - self.job_id, - self.extra_nonce2, - self.time, - self.nonce, - self.version_bits, - self.id - ) - } -} - -impl Submit { - pub fn respond(self, outcome: SubmitOutcome) -> Response { - match outcome { - SubmitOutcome::Accepted => Response { - id: self.id, - result: Value::Bool(true), - error: None, - }, - SubmitOutcome::Rejected(error) => Response { - id: self.id, - result: Value::Null, - error: Some(JsonRpcError { - code: error.code(), - message: error.message().to_string(), - data: None, - }), - }, - } - } -} - -impl From for Message { - fn from(submit: Submit) -> Self { - let ex: String = submit.extra_nonce2.0.as_bytes().to_lower_hex_string(); - let mut params: Vec = vec![ - submit.user_name.into(), - submit.job_id.into(), - ex.into(), - submit.time.into(), - submit.nonce.into(), - ]; - if let Some(a) = submit.version_bits { - let a: String = a.into(); - params.push(a.into()); - }; - Message::StandardRequest(StandardRequest { - id: submit.id, - method: "mining.submit".into(), - params: params.into(), - }) - } -} - -impl TryFrom for Submit { - type Error = ParsingMethodError; - - #[allow(clippy::many_single_char_names)] - fn try_from(msg: StandardRequest) -> Result { - match msg.params.as_array() { - Some(params) => { - let (user_name, job_id, extra_nonce2, time, nonce, version_bits) = match ¶ms[..] - { - [JString(a), JString(b), JString(c), JNumber(d), JNumber(e), JString(f)] => ( - a.into(), - b.into(), - Extranonce::try_from(hex_decode(c)?)?, - HexU32Be(d.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(d.clone())) - })? as u32), - HexU32Be(e.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(e.clone())) - })? as u32), - Some((f.as_str()).try_into()?), - ), - [JString(a), JString(b), JString(c), JString(d), JString(e), JString(f)] => ( - a.into(), - b.into(), - Extranonce::try_from(hex_decode(c)?)?, - (d.as_str()).try_into()?, - (e.as_str()).try_into()?, - Some((f.as_str()).try_into()?), - ), - [JString(a), JString(b), JString(c), JNumber(d), JNumber(e)] => ( - a.into(), - b.into(), - Extranonce::try_from(hex_decode(c)?)?, - HexU32Be(d.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(d.clone())) - })? as u32), - HexU32Be(e.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(e.clone())) - })? as u32), - None, - ), - [JString(a), JString(b), JString(c), JString(d), JString(e)] => ( - a.into(), - b.into(), - Extranonce::try_from(hex_decode(c)?)?, - (d.as_str()).try_into()?, - (e.as_str()).try_into()?, - None, - ), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - let id = msg.id; - let res = crate::client_to_server::Submit { - user_name, - job_id, - extra_nonce2, - time, - nonce, - version_bits, - id, - }; - Ok(res) - } - None => Err(ParsingMethodError::not_array_from_value(msg.params)), - } - } -} - -#[cfg(test)] -impl Arbitrary for Submit { - fn arbitrary(g: &mut Gen) -> Self { - let mut extra = Vec::::arbitrary(g); - extra.resize(32, 0); - println!("\nEXTRA: {extra:?}\n"); - let bits = Option::::arbitrary(g); - println!("\nBITS: {bits:?}\n"); - let extra: Extranonce = extra.try_into().unwrap(); - let bits = bits.map(HexU32Be); - println!("\nBITS: {bits:?}\n"); - Submit { - user_name: String::arbitrary(g), - job_id: String::arbitrary(g), - extra_nonce2: extra, - time: HexU32Be(u32::arbitrary(g)), - nonce: HexU32Be(u32::arbitrary(g)), - version_bits: bits, - id: u64::arbitrary(g), - } - } -} - -#[cfg(test)] -#[quickcheck_macros::quickcheck] -fn submit_from_to_json_rpc(submit: Submit) -> bool { - let message = Into::::into(submit.clone()); - println!("\nMESSAGE: {message:?}\n"); - let request = match message { - Message::StandardRequest(s) => s, - _ => panic!(), - }; - println!("\nREQUEST: {request:?}\n"); - submit == TryInto::::try_into(request).unwrap() -} - -#[test] -fn rejected_submit_uses_legacy_sv1_error_array() { - let submit = Submit { - user_name: "worker".to_string(), - job_id: "job".to_string(), - extra_nonce2: vec![0; 4].try_into().unwrap(), - time: HexU32Be(0), - nonce: HexU32Be(0), - version_bits: None, - id: 42, - }; - - let response = submit.respond(SubmitOutcome::Rejected(SubmitError::DuplicateShare)); - - assert_eq!( - serde_json::to_value(response).unwrap(), - serde_json::json!({ - "id": 42, - "result": null, - "error": [22, "Duplicate share", null], - }) - ); -} - -#[test] -fn submit_errors_use_standard_sv1_codes() { - assert_eq!(SubmitError::Other.code(), 20); - assert_eq!(SubmitError::JobNotFound.code(), 21); - assert_eq!(SubmitError::DuplicateShare.code(), 22); - assert_eq!(SubmitError::LowDifficultyShare.code(), 23); - assert_eq!(SubmitError::UnauthorizedWorker.code(), 24); - assert_eq!(SubmitError::NotSubscribed.code(), 25); -} - -/// _mining.subscribe("user agent/version", "extranonce1")_ -/// -/// extranonce1 specifies a [mining.notify][a] extranonce1 the client wishes to -/// resume working with (possibly due to a dropped connection). If provided, a server MAY (at its -/// option) issue the connection the same extranonce1. Note that the extranonce1 may be the same -/// (allowing a resumed connection) even if the subscription id is changed! -/// -/// [a]: crate::methods::server_to_client::Notify -#[derive(Debug, Clone)] -pub struct Subscribe { - pub id: u64, - pub agent_signature: String, - pub extranonce1: Option, -} - -impl fmt::Display for Subscribe { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Subscribe {{ id: {}, agent_signature: {}, extranonce1: {:?} }}", - self.id, self.agent_signature, self.extranonce1 - ) - } -} - -impl Subscribe { - pub fn respond( - self, - subscriptions: Vec<(String, String)>, - extra_nonce1: Extranonce, - extra_nonce2_size: usize, - ) -> Response { - let response = crate::server_to_client::Subscribe { - subscriptions, - extra_nonce1, - extra_nonce2_size, - id: self.id, - }; - match Message::from(response) { - Message::OkResponse(r) => r, - _ => unreachable!(), - } - } -} - -impl TryFrom for Message { - type Error = Error; - - fn try_from(subscribe: Subscribe) -> Result { - let params = match (subscribe.agent_signature, subscribe.extranonce1) { - (a, Some(b)) => vec![a, b.0.as_bytes().to_lower_hex_string()], - (a, None) => vec![a], - }; - Ok(Message::StandardRequest(StandardRequest { - id: subscribe.id, - method: "mining.subscribe".into(), - params: (¶ms[..]).into(), - })) - } -} - -impl TryFrom for Subscribe { - type Error = ParsingMethodError; - - fn try_from(msg: StandardRequest) -> Result { - match msg.params.as_array() { - Some(params) => { - let (agent_signature, extranonce1) = match ¶ms[..] { - // bosminer subscribe message - [JString(a), Null, JString(_), Null] => (a.into(), None), - // bosminer subscribe message - [JString(a), Null] => (a.into(), None), - [JString(a), JString(b)] => (a.into(), Some(Extranonce::try_from(b.as_str())?)), - [JString(a)] => (a.into(), None), - [] => ("".to_string(), None), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - let id = msg.id; - let res = Subscribe { - id, - agent_signature, - extranonce1, - }; - Ok(res) - } - None => Err(ParsingMethodError::not_array_from_value(msg.params)), - } - } -} - -#[derive(Debug, Clone)] -pub struct Configure { - pub extensions: Vec, - pub id: u64, -} - -impl fmt::Display for Configure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Configure {{ id: {}, extensions: [", self.id)?; - let mut first = true; - for val in &self.extensions { - if !first { - write!(f, ", ")?; - } - first = false; - write!(f, "{}", val)?; - } - write!(f, "] }}") - } -} - -impl Configure { - /// Creates a BIP 310 version-rolling request. - /// - /// The mask is encoded as a hexadecimal string and the minimum bit count as a JSON integer. - pub fn new(id: u64, mask: Option, min_bit_count: Option) -> Self { - let extension = ConfigureExtension::VersionRolling(VersionRollingParams { - mask, - min_bit_count, - }); - Configure { - extensions: vec![extension], - id, - } - } - - pub fn void(id: u64) -> Self { - Configure { - extensions: vec![], - id, - } - } - - pub fn respond( - self, - version_rolling: Option, - minimum_difficulty: Option, - ) -> Response { - let response = crate::server_to_client::Configure { - id: self.id, - version_rolling, - minimum_difficulty, - }; - match Message::from(response) { - Message::OkResponse(r) => r, - _ => unreachable!(), - } - } - - pub fn version_rolling_mask(&self) -> Option { - let mut res = None; - for ext in &self.extensions { - if let ConfigureExtension::VersionRolling(p) = ext { - res = Some(p.mask.clone().unwrap_or(HexU32Be(VERSION_ROLLING_MASK))); - }; - } - res - } - - pub fn version_rolling_min_bit_count(&self) -> Option { - let mut res = None; - for ext in &self.extensions { - if let ConfigureExtension::VersionRolling(p) = ext { - // TODO check if 0 is the right default value - res = Some(p.min_bit_count.clone().unwrap_or(HexU32Be(0))); - }; - } - res - } -} - -impl From for Message { - fn from(conf: Configure) -> Self { - let mut params = serde_json::Map::new(); - let extension_names: Vec = conf - .extensions - .iter() - .map(|x| x.get_extension_name()) - .collect(); - for parameter in conf.extensions { - let mut parameter: serde_json::Map = parameter.into(); - params.append(&mut parameter); - } - Message::StandardRequest(StandardRequest { - id: conf.id, - method: "mining.configure".into(), - params: vec![JArrary(extension_names), params.into()].into(), - }) - } -} - -impl TryFrom for Configure { - type Error = ParsingMethodError; - - fn try_from(msg: StandardRequest) -> Result { - let extensions = ConfigureExtension::from_value(&msg.params)?; - let id = msg.id; - Ok(Self { extensions, id }) - } -} - -#[derive(Debug, Clone)] -pub enum ConfigureExtension { - VersionRolling(VersionRollingParams), - MinimumDifficulty(u64), - SubcribeExtraNonce, - Info(InfoParams), -} - -impl fmt::Display for ConfigureExtension { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ConfigureExtension::VersionRolling(p) => { - write!(f, "VersionRolling({:?})", p) - } - ConfigureExtension::MinimumDifficulty(d) => { - write!(f, "MinimumDifficulty({})", d) - } - ConfigureExtension::SubcribeExtraNonce => { - write!(f, "SubscribeExtraNonce") - } - ConfigureExtension::Info(info) => { - write!(f, "Info({:?})", info) - } - } - } -} -#[allow(clippy::unnecessary_unwrap)] -impl ConfigureExtension { - pub fn from_value(val: &Value) -> Result, ParsingMethodError> { - let mut res = vec![]; - let root = val - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(val.clone()))?; - if root.is_empty() { - return Err(ParsingMethodError::Todo); - }; - - let version_rolling_mask = val.pointer("/1/version-rolling.mask"); - let version_rolling_min_bit = val.pointer("/1/version-rolling.min-bit-count"); - let info_connection_url = val.pointer("/1/info.connection-url"); - let info_hw_version = val.pointer("/1/info.hw-version"); - let info_sw_version = val.pointer("/1/info.sw-version"); - let info_hw_id = val.pointer("/1/info.hw-id"); - let minimum_difficulty_value = val.pointer("/1/minimum-difficulty.value"); - - if root[0] - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(root[0].clone()))? - .contains(&JString("subscribe-extranonce".to_string())) - { - res.push(ConfigureExtension::SubcribeExtraNonce) - } - let (mask, min_bit_count) = match (version_rolling_mask, version_rolling_min_bit) { - (None, None) => (None, None), - // WhatsMiner sent mask without min bit count - (Some(JString(mask)), None) => { - let mask: HexU32Be = mask.as_str().try_into()?; - (Some(mask), None) - } - // Min bit can be a string cpuminer - (Some(JString(mask)), Some(JString(min_bit))) => { - let mask: HexU32Be = mask.as_str().try_into()?; - let min_bit: HexU32Be = min_bit.as_str().try_into()?; - (Some(mask), Some(min_bit)) - } - // Min bit can be a number s9, s19 - (Some(JString(mask)), Some(JNumber(min_bit))) => { - let mask: HexU32Be = mask.as_str().try_into()?; - let min_bit: HexU32Be = HexU32Be(min_bit.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(min_bit.clone())) - })? as u32); - (Some(mask), Some(min_bit)) - } - // We can not have min bit count without a mask - (None, Some(_)) => return Err(ParsingMethodError::Todo), - // Mask need to be a JString - (Some(_), None) => return Err(ParsingMethodError::Todo), - // Min bit need to be a string or a number - (Some(_), Some(_)) => return Err(ParsingMethodError::Todo), - }; - if mask.is_some() || min_bit_count.is_some() { - let params = VersionRollingParams { - mask, - min_bit_count, - }; - res.push(ConfigureExtension::VersionRolling(params)); - } - - if let Some(minimum_difficulty_value) = minimum_difficulty_value { - let min_diff = match minimum_difficulty_value { - JNumber(a) => a.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(a.clone())) - })?, - _ => { - return Err(ParsingMethodError::unexpected_value_from_value( - minimum_difficulty_value.clone(), - )) - } - }; - - res.push(ConfigureExtension::MinimumDifficulty(min_diff)); - }; - - if info_connection_url.is_some() - || info_hw_id.is_some() - || info_hw_version.is_some() - || info_sw_version.is_some() - { - let connection_url = if info_connection_url.is_some() - // infallible - && info_connection_url.unwrap().as_str().is_some() - { - // infallible - Some(info_connection_url.unwrap().as_str().unwrap().to_string()) - } else if info_connection_url.is_some() { - return Err(ParsingMethodError::Todo); - } else { - None - }; - // infallible - let hw_id = if info_hw_id.is_some() && info_hw_id.unwrap().as_str().is_some() { - // infallible - Some(info_hw_id.unwrap().as_str().unwrap().to_string()) - } else if info_hw_id.is_some() { - return Err(ParsingMethodError::Todo); - } else { - None - }; - // infallible - let hw_version = - if info_hw_version.is_some() && info_hw_version.unwrap().as_str().is_some() { - // infallible - Some(info_hw_version.unwrap().as_str().unwrap().to_string()) - } else if info_hw_version.is_some() { - return Err(ParsingMethodError::Todo); - } else { - None - }; - let sw_version = - // infallible - if info_sw_version.is_some() && info_sw_version.unwrap().as_str().is_some() { - // infallible - Some(info_sw_version.unwrap().as_str().unwrap().to_string()) - } else if info_sw_version.is_some() { - return Err(ParsingMethodError::Todo); - } else { - None - }; - let params = InfoParams { - connection_url, - hw_id, - hw_version, - sw_version, - }; - res.push(ConfigureExtension::Info(params)); - }; - Ok(res) - } -} - -impl ConfigureExtension { - pub fn get_extension_name(&self) -> Value { - match self { - ConfigureExtension::VersionRolling(_) => "version-rolling".into(), - ConfigureExtension::MinimumDifficulty(_) => "minimum-difficulty".into(), - ConfigureExtension::SubcribeExtraNonce => "subscribe-extranonce".into(), - ConfigureExtension::Info(_) => "info".into(), - } - } -} - -impl From for serde_json::Map { - fn from(conf: ConfigureExtension) -> Self { - match conf { - ConfigureExtension::VersionRolling(a) => a.into(), - ConfigureExtension::SubcribeExtraNonce => serde_json::Map::new(), - ConfigureExtension::Info(a) => a.into(), - ConfigureExtension::MinimumDifficulty(a) => { - let mut map = serde_json::Map::new(); - map.insert("minimum-difficulty".to_string(), a.into()); - map - } - } - } -} - -#[derive(Debug, Clone)] -pub struct VersionRollingParams { - mask: Option, - min_bit_count: Option, -} - -impl VersionRollingParams { - pub fn get_mask(&self) -> &Option { - &self.mask - } - - pub fn get_min_bit_count(&self) -> &Option { - &self.min_bit_count - } -} - -impl From for serde_json::Map { - fn from(conf: VersionRollingParams) -> Self { - let mut params = serde_json::Map::new(); - match (conf.mask, conf.min_bit_count) { - (Some(mask), Some(min)) => { - let mask: String = mask.into(); - params.insert("version-rolling.mask".to_string(), mask.into()); - params.insert("version-rolling.min-bit-count".to_string(), min.0.into()); - } - (Some(mask), None) => { - let mask: String = mask.into(); - params.insert("version-rolling.mask".to_string(), mask.into()); - } - (None, Some(min)) => { - params.insert("version-rolling.min-bit-count".to_string(), min.0.into()); - } - (None, None) => (), - }; - params - } -} - -#[derive(Debug, Clone)] -pub struct InfoParams { - pub connection_url: Option, - #[allow(dead_code)] - pub hw_id: Option, - #[allow(dead_code)] - pub hw_version: Option, - #[allow(dead_code)] - pub sw_version: Option, -} - -impl From for serde_json::Map { - fn from(info: InfoParams) -> Self { - let mut params = serde_json::Map::new(); - if info.connection_url.is_some() { - params.insert( - "info.connection-url".to_string(), - // infallible - info.connection_url.unwrap().into(), - ); - } - params - } -} - -// mining.suggest_difficulty - -// mining.suggest_target - -// mining.minimum_difficulty (extension) -#[test] -fn test_version_extension_with_broken_bit_count() { - let client_message = r#"{"id":0, - "method": "mining.configure", - "params":[ - ["version-rolling"], - {"version-rolling.mask":"1fffffe0", - "version-rolling.min-bit-count":"16"} - ] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let server_configure = Configure::try_from(client_message).unwrap(); - match &server_configure.extensions[0] { - ConfigureExtension::VersionRolling(params) => { - assert!(params.get_min_bit_count().as_ref().unwrap().0 == 0x16) - } - _ => panic!(), - }; -} -#[test] -fn test_version_extension_with_non_string_bit_count() { - let client_message = r#"{"id":0, - "method": "mining.configure", - "params":[ - ["version-rolling"], - {"version-rolling.mask":"1fffffe0", - "version-rolling.min-bit-count":16} - ] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let server_configure = Configure::try_from(client_message).unwrap(); - match &server_configure.extensions[0] { - ConfigureExtension::VersionRolling(params) => { - assert!(params.get_min_bit_count().as_ref().unwrap().0 == 16) - } - _ => panic!(), - }; -} - -#[test] -fn test_configure_serializes_min_bit_count_as_integer() { - let configure = Configure::new(0, Some(HexU32Be(0x1fffffe0)), Some(HexU32Be(16))); - let serialized = serde_json::to_value(Message::from(configure)).unwrap(); - assert_eq!(serialized["params"][1]["version-rolling.mask"], "1fffffe0"); - assert_eq!(serialized["params"][1]["version-rolling.min-bit-count"], 16); - - let configure = Configure::new(0, None, Some(HexU32Be(16))); - let serialized = serde_json::to_value(Message::from(configure)).unwrap(); - assert_eq!(serialized["params"][1]["version-rolling.min-bit-count"], 16); - assert!(serialized["params"][1] - .get("version-rolling.mask") - .is_none()); -} - -#[test] -fn test_version_extension_with_no_bit_count() { - let client_message = r#"{"id":0, - "method": "mining.configure", - "params":[ - ["version-rolling"], - {"version-rolling.mask":"ffffffff"} - ] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let server_configure = Configure::try_from(client_message).unwrap(); - match &server_configure.extensions[0] { - ConfigureExtension::VersionRolling(params) => { - assert!(params.get_min_bit_count().as_ref().is_none()); - } - _ => panic!(), - }; -} - -#[test] -fn test_subscribe_with_odd_length_extranonce() { - // Test that odd-length hex strings (with leading zeroes) are handled correctly - let client_message = r#"{"id":1, - "method": "mining.subscribe", - "params":["test-agent", "abc"] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let subscribe = Subscribe::try_from(client_message).unwrap(); - - // Should successfully parse odd-length hex string by prepending "0" - assert_eq!(subscribe.agent_signature, "test-agent"); - assert!(subscribe.extranonce1.is_some()); - let extranonce = subscribe.extranonce1.unwrap(); - assert_eq!(extranonce.0.as_bytes(), &[0x0a, 0xbc]); // "0abc" -> [10, 188] -} - -#[test] -fn test_subscribe_with_even_length_extranonce() { - // Test that even-length hex strings work as before - let client_message = r#"{"id":1, - "method": "mining.subscribe", - "params":["test-agent", "abcd"] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let subscribe = Subscribe::try_from(client_message).unwrap(); - - assert_eq!(subscribe.agent_signature, "test-agent"); - assert!(subscribe.extranonce1.is_some()); - let extranonce = subscribe.extranonce1.unwrap(); - assert_eq!(extranonce.0.as_bytes(), &[0xab, 0xcd]); // "abcd" -> [171, 205] -} - -#[test] -fn test_submit_negative_time_does_not_panic() { - // A malformed `mining.submit` whose `nTime` is a negative JSON number - // (e.g. -1) reaches the `[JString, JString, JString, JNumber, JNumber]` - // arm in `Submit::try_from`, where `d.as_u64().unwrap()` is called on a - // negative `serde_json::Number`. `as_u64()` returns `None` for negative - // values, so `.unwrap()` panics, crashing the parser before any auth - // check has run. The parser should return `Err` instead. - let client_message = r#"{"id":1, - "method": "mining.submit", - "params":["user", "1", "ab", -1, 0] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let result = Submit::try_from(client_message); - assert!( - result.is_err(), - "Submit::try_from should return Err for a negative nTime, not panic" - ); -} - -#[test] -fn test_submit_float_nonce_does_not_panic() { - // Same shape as the negative-time case, but with a floating-point nOnce. - // `serde_json::Number::as_u64()` also returns `None` for floats. - let client_message = r#"{"id":1, - "method": "mining.submit", - "params":["user", "1", "ab", 0, 1.5] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let result = Submit::try_from(client_message); - assert!( - result.is_err(), - "Submit::try_from should return Err for a fractional nOnce, not panic" - ); -} - -#[test] -fn test_configure_negative_min_bit_count_does_not_panic() { - // The mining.configure handler also panics: when min-bit-count is a - // negative JSON number, `min_bit.as_u64().unwrap()` blows up the - // server. Should return Err. - let client_message = r#"{"id":0, - "method": "mining.configure", - "params":[ - ["version-rolling"], - {"version-rolling.mask":"1fffffe0","version-rolling.min-bit-count":-1} - ] - }"#; - let client_message: StandardRequest = serde_json::from_str(client_message).unwrap(); - let result = Configure::try_from(client_message); - assert!( - result.is_err(), - "Configure::try_from should return Err for a negative min-bit-count, not panic" - ); -} diff --git a/sv1/src/methods/mod.rs b/sv1/src/methods/mod.rs deleted file mode 100644 index af88b81346..0000000000 --- a/sv1/src/methods/mod.rs +++ /dev/null @@ -1,312 +0,0 @@ -use crate::error::Error; -use bitcoin::hashes::hex::HexToBytesError; -use std::convert::{TryFrom, TryInto}; - -pub mod client_to_server; -pub mod server_to_client; - -use crate::json_rpc::{Message, Response}; - -/// Errors encountered during conversion between valid json_rpc messages and Sv1 messages. -#[derive(Debug)] -pub enum MethodError { - /// If the json_rpc message call a method not defined by Sv1. It contains the called method - MethodNotFound(String), - /// If the json_rpc Response co"ntain an error in this case the error should just be reported - ResponseIsAnError(Box), - /// Method can not be parsed - ParsingMethodError((ParsingMethodError, Message)), - // Method can not be serialized - // SerializeError(Box), - UnexpectedMethod(Method), - // json_rpc message is not a request - NotARequest, -} - -impl From for ParsingMethodError { - fn from(btc_err: HexToBytesError) -> Self { - ParsingMethodError::HexError(btc_err) - } -} - -impl From for ParsingMethodError { - fn from(u256_err: binary_sv2::Error) -> Self { - ParsingMethodError::BadU256Convert(Box::new(u256_err)) - } -} - -#[derive(Debug)] -pub enum ParsingMethodError { - BadU256Convert(Box), - BadBytesConvert(binary_sv2::Error), - HexError(HexToBytesError), - ValueNotAnArray(Box), - WrongArgs(Box), - ValueNotAString(Box), - ValueNotAFloat(Box), - ValueNotAnUnsigned(Box), - ValueNotAnInt(Box), - UnexpectedValue(Box), - ImpossibleToParseResultField(Box), - ImpossibleToParseAsU64(Box), - UnexpectedArrayParams(Vec), - UnexpectedObjectParams(serde_json::Map), - MultipleError(Vec), - InvalidHexLen(Box), - Todo, - UnhandledSv1Error(String), -} - -impl From for ParsingMethodError { - fn from(inner: Error) -> Self { - match inner { - Error::HexError(e) => ParsingMethodError::HexError(e), - Error::InvalidHexLen(s) => { - ParsingMethodError::InvalidHexLen(Box::new(serde_json::Value::String(s))) - } - Error::BadBytesConvert(e) => ParsingMethodError::BadBytesConvert(e), - other => ParsingMethodError::UnhandledSv1Error(format!("{other:?}")), - } - } -} - -impl ParsingMethodError { - pub fn as_method_error(self, msg: Message) -> MethodError { - MethodError::ParsingMethodError((self, msg)) - } -} - -impl ParsingMethodError { - pub fn not_array_from_value(v: serde_json::Value) -> Self { - ParsingMethodError::ValueNotAnArray(Box::new(v)) - } - - pub fn not_string_from_value(v: serde_json::Value) -> Self { - ParsingMethodError::ValueNotAString(Box::new(v)) - } - - pub fn not_float_from_value(v: serde_json::Value) -> Self { - ParsingMethodError::ValueNotAFloat(Box::new(v)) - } - - pub fn not_unsigned_from_value(v: serde_json::value::Number) -> Self { - ParsingMethodError::ValueNotAnUnsigned(Box::new(v)) - } - - pub fn not_int_from_value(v: serde_json::value::Number) -> Self { - ParsingMethodError::ValueNotAnInt(Box::new(v)) - } - - pub fn wrong_args_from_value(v: serde_json::Value) -> Self { - ParsingMethodError::WrongArgs(Box::new(v)) - } - - pub fn unexpected_value_from_value(v: serde_json::Value) -> Self { - ParsingMethodError::UnexpectedValue(Box::new(v)) - } -} - -#[derive(Debug, Clone)] -pub enum Method { - Client2Server(Client2Server), - Server2Client(Server2Client), - Server2ClientResponse(Server2ClientResponse), - ErrorMessage(Message), -} - -#[derive(Debug, Clone)] -pub enum Client2Server { - SuggestDifficulty(), - Subscribe(client_to_server::Subscribe), - Authorize(client_to_server::Authorize), - ExtranonceSubscribe(client_to_server::ExtranonceSubscribe), - Submit(client_to_server::Submit), - Configure(client_to_server::Configure), -} - -impl From for Method { - fn from(a: Client2Server) -> Self { - Method::Client2Server(a) - } -} - -impl TryFrom for Client2Server { - type Error = MethodError; - - fn try_from(msg: Message) -> Result { - let method: Method = msg.try_into()?; - match method { - Method::Client2Server(client_to_server) => Ok(client_to_server), - Method::ErrorMessage(_) => Err(MethodError::UnexpectedMethod(method)), - Method::Server2Client(_) => Err(MethodError::UnexpectedMethod(method)), - Method::Server2ClientResponse(_) => Err(MethodError::UnexpectedMethod(method)), - } - } -} - -#[derive(Debug, Clone)] -pub enum Server2Client { - Notify(server_to_client::Notify), - SetDifficulty(server_to_client::SetDifficulty), - SetExtranonce(server_to_client::SetExtranonce), - SetVersionMask(server_to_client::SetVersionMask), -} - -impl From for Method { - fn from(a: Server2Client) -> Self { - Method::Server2Client(a) - } -} - -impl TryFrom for Server2Client { - type Error = MethodError; - - fn try_from(msg: Message) -> Result { - let method: Method = msg.try_into()?; - match method { - Method::Server2Client(client_to_server) => Ok(client_to_server), - Method::ErrorMessage(_) => Err(MethodError::UnexpectedMethod(method)), - Method::Client2Server(_) => Err(MethodError::UnexpectedMethod(method)), - Method::Server2ClientResponse(_) => Err(MethodError::UnexpectedMethod(method)), - } - } -} - -#[derive(Debug, Clone)] -pub enum Server2ClientResponse { - Configure(server_to_client::Configure), - Subscribe(server_to_client::Subscribe), - GeneralResponse(server_to_client::GeneralResponse), - Authorize(server_to_client::Authorize), - ExtranonceSubscribe(server_to_client::ExtranonceSubscribe), - Submit(server_to_client::Submit), - SetDifficulty(server_to_client::SetDifficulty), -} - -impl From for Method { - fn from(a: Server2ClientResponse) -> Self { - Method::Server2ClientResponse(a) - } -} - -impl TryFrom for Server2ClientResponse { - type Error = MethodError; - - fn try_from(msg: Message) -> Result { - let method: Method = msg.try_into()?; - match method { - Method::Server2ClientResponse(server_to_client) => Ok(server_to_client), - Method::Client2Server(_) => Err(MethodError::UnexpectedMethod(method)), - Method::Server2Client(_) => Err(MethodError::UnexpectedMethod(method)), - Method::ErrorMessage(_) => Err(MethodError::UnexpectedMethod(method)), - } - } -} - -impl TryFrom for Method { - type Error = MethodError; - - fn try_from(msg: Message) -> Result { - match &msg { - Message::StandardRequest(request) => match &request.method[..] { - "mining.suggest_difficulty" => { - Ok(Method::Client2Server(Client2Server::SuggestDifficulty())) - } - "mining.subscribe" => { - let method = request - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Client2Server(Client2Server::Subscribe(method))) - } - "mining.authorize" => { - let method = request - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Client2Server(Client2Server::Authorize(method))) - } - "mining.extranonce.subscribe" => { - let method = request - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Client2Server(Client2Server::ExtranonceSubscribe( - method, - ))) - } - "mining.submit" => { - let method = request - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Client2Server(Client2Server::Submit(method))) - } - "mining.configure" => { - let method = request - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Client2Server(Client2Server::Configure(method))) - } - _ => Err(MethodError::MethodNotFound(request.clone().method)), - }, - Message::Notification(notification) => match ¬ification.method[..] { - "mining.notify" => { - let method = notification - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Server2Client(Server2Client::Notify(method))) - } - "mining.set_version_mask" => { - let method = notification - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Server2Client(Server2Client::SetVersionMask(method))) - } - "mining.set_difficulty" => { - let method = notification - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Server2Client(Server2Client::SetDifficulty(method))) - } - "mining.set_extranonce" => { - let method = notification - .clone() - .try_into() - .map_err(|e: ParsingMethodError| e.as_method_error(msg))?; - Ok(Method::Server2Client(Server2Client::SetExtranonce(method))) - } - _ => Err(MethodError::MethodNotFound(notification.clone().method)), - }, - Message::OkResponse(response) => response - .clone() - .try_into() - .map(Method::Server2ClientResponse) - .map_err(|e| e.as_method_error(msg)), - Message::ErrorResponse(_) => Ok(Method::ErrorMessage(msg)), - } - } -} - -impl TryFrom for Server2ClientResponse { - type Error = ParsingMethodError; - - fn try_from(msg: Response) -> Result { - let subscribe: Result = (&msg).try_into(); - let configure: Result = (&msg).try_into(); - let general_response: Result = - (&msg).try_into(); - match (subscribe, configure, general_response) { - (Ok(a), Err(_), Err(_)) => Ok(Server2ClientResponse::Subscribe(a)), - (Err(_), Ok(a), Err(_)) => Ok(Server2ClientResponse::Configure(a)), - (Err(_), Err(_), Ok(a)) => Ok(Server2ClientResponse::GeneralResponse(a)), - (Err(e), Err(ee), Err(eee)) => Err(ParsingMethodError::MultipleError(vec![e, ee, eee])), - // Impossible state a message can not be more than one method - _ => panic!(), - } - } -} diff --git a/sv1/src/methods/server_to_client.rs b/sv1/src/methods/server_to_client.rs deleted file mode 100644 index 0f0f04b284..0000000000 --- a/sv1/src/methods/server_to_client.rs +++ /dev/null @@ -1,819 +0,0 @@ -use serde_json::{ - Value, - Value::{Array as JArrary, Bool as JBool, Number as JNumber, String as JString}, -}; -use std::convert::{TryFrom, TryInto}; -use std::fmt; - -use crate::{ - json_rpc::{Message, Notification, Response}, - methods::ParsingMethodError, - utils::{ - hex_decode, Extranonce, HexBytes, HexU32Be, MerkleNode, PrevHash, VERSION_ROLLING_MASK, - }, -}; - -// client.get_version() - -// client.reconnect - -// client.show_message - -/// Fields in order: -/// -/// * Job ID: This is included when miners submit a results so work can be matched with proper -/// transactions. -/// * Hash of previous block: Used to build the header. -/// * Generation transaction (part 1): The miner inserts ExtraNonce1 and ExtraNonce2 after this -/// section of the transaction data. -/// * Generation transaction (part 2): The miner appends this after the first part of the -/// transaction data and the two ExtraNonce values. -/// * List of merkle branches: The generation transaction is hashed against the merkle branches to -/// build the final merkle root. -/// * Bitcoin block version: Used in the block header. -/// * nBits: The encoded network difficulty. Used in the block header. -/// * nTime: The current time. nTime rolling should be supported, but should not increase faster -/// than actual time. -/// * Clean Jobs: If true, miners should abort their current work and immediately use the new job. -/// If false, they can still use the current job, but should move to the new one after exhausting -/// the current nonce range. -#[derive(Debug, Clone)] -pub struct Notify { - pub job_id: String, - pub prev_hash: PrevHash, - pub coin_base1: HexBytes, - pub coin_base2: HexBytes, - pub merkle_branch: Vec, - pub version: HexU32Be, - pub bits: HexU32Be, - pub time: HexU32Be, - pub clean_jobs: bool, -} - -impl fmt::Display for Notify { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Notify {{ job_id: {}, prev_hash: {}, coin_base1: {}, coin_base2: {}, merkle_branch: ", - self.job_id, self.prev_hash, self.coin_base1, self.coin_base2, - )?; - - match self.merkle_branch.len() { - 0 => write!(f, "[]")?, - 1 => write!(f, "[{}]", self.merkle_branch[0])?, - 2 => write!(f, "[{}, {}]", self.merkle_branch[0], self.merkle_branch[1])?, - _ => write!( - f, - "[{}, ..., {}]", - self.merkle_branch.first().unwrap(), - self.merkle_branch.last().unwrap() - )?, - } - - write!( - f, - " ({} nodes), version: {}, bits: {}, time: {}, clean_jobs: {} }}", - self.merkle_branch.len(), - self.version, - self.bits, - self.time, - self.clean_jobs, - ) - } -} - -impl From for Message { - fn from(notify: Notify) -> Self { - let prev_hash: Value = notify.prev_hash.into(); - let coin_base1: Value = notify.coin_base1.into(); - let coin_base2: Value = notify.coin_base2.into(); - let mut merkle_branch: Vec = vec![]; - for mb in notify.merkle_branch { - let mb: Value = mb.into(); - merkle_branch.push(mb); - } - let merkle_branch = JArrary(merkle_branch); - let version: Value = notify.version.into(); - let bits: Value = notify.bits.into(); - let time: Value = notify.time.into(); - Message::Notification(Notification { - method: "mining.notify".to_string(), - params: (&[ - notify.job_id.into(), - prev_hash, - coin_base1, - coin_base2, - merkle_branch, - version, - bits, - time, - notify.clean_jobs.into(), - ][..]) - .into(), - }) - } -} - -impl TryFrom for Notify { - type Error = ParsingMethodError; - - #[allow(clippy::many_single_char_names)] - fn try_from(msg: Notification) -> Result { - let params = msg - .params - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(msg.params.clone()))?; - let ( - job_id, - prev_hash, - coin_base1, - coin_base2, - merkle_branch_, - version, - bits, - time, - clean_jobs, - ) = match ¶ms[..] { - [JString(a), JString(b), JString(c), JString(d), JArrary(e), JString(f), JString(g), JString(h), JBool(i)] => { - ( - a.into(), - b.as_str().try_into()?, - c.as_str().try_into()?, - d.as_str().try_into()?, - e, - f.as_str().try_into()?, - g.as_str().try_into()?, - h.as_str().try_into()?, - *i, - ) - } - _ => { - return Err(ParsingMethodError::wrong_args_from_value( - msg.params.clone(), - )) - } - }; - let mut merkle_branch = vec![]; - for h in merkle_branch_ { - let h: MerkleNode = h - .as_str() - .ok_or_else(|| ParsingMethodError::not_string_from_value(h.clone()))? - .try_into()?; - - merkle_branch.push(h); - } - let notify = Notify { - job_id, - prev_hash, - coin_base1, - coin_base2, - merkle_branch, - version, - bits, - time, - clean_jobs, - }; - Ok(notify.clone()) - } -} - -/// mining.set_difficulty(difficulty) -/// -/// The server can adjust the difficulty required for miner shares with the "mining.set_difficulty" -/// method. The miner should begin enforcing the new difficulty on the next job received. Some pools -/// may force a new job out when set_difficulty is sent, using clean_jobs to force the miner to -/// begin using the new difficulty immediately. -#[derive(Debug, Clone)] -pub struct SetDifficulty { - pub value: f64, -} - -impl fmt::Display for SetDifficulty { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.value) - } -} - -impl From for Message { - fn from(sd: SetDifficulty) -> Self { - let value: Value = sd.value.into(); - Message::Notification(Notification { - method: "mining.set_difficulty".to_string(), - params: (&[value][..]).into(), - }) - } -} - -impl TryFrom for SetDifficulty { - type Error = ParsingMethodError; - - fn try_from(msg: Notification) -> Result { - let params = msg - .params - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(msg.params.clone()))?; - let (value,) = match ¶ms[..] { - [a] => (a - .as_f64() - .ok_or_else(|| ParsingMethodError::not_float_from_value(a.clone()))?,), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - Ok(SetDifficulty { value }) - } -} - -/// SetExtranonce message (sent if we subscribed with `ExtranonceSubscribe`) -/// -/// mining.set_extranonce("extranonce1", extranonce2_size) -/// -/// These values, when provided, replace the initial subscription values beginning with the next -/// mining.notify job. -/// -/// check if it is a Notification or a StandardRequest this implementation assume that it is a -/// Notification -#[derive(Debug, Clone)] -pub struct SetExtranonce { - pub extra_nonce1: Extranonce, - pub extra_nonce2_size: usize, -} - -impl fmt::Display for SetExtranonce { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "SetExtranonce {{ extra_nonce1: {}, extra_nonce2_size: {} }}", - self.extra_nonce1, self.extra_nonce2_size - ) - } -} - -impl From for Message { - fn from(se: SetExtranonce) -> Self { - let extra_nonce1: Value = se.extra_nonce1.into(); - let extra_nonce2_size: Value = se.extra_nonce2_size.into(); - Message::Notification(Notification { - method: "mining.set_extranonce".to_string(), - params: (&[extra_nonce1, extra_nonce2_size][..]).into(), - }) - } -} - -impl TryFrom for SetExtranonce { - type Error = ParsingMethodError; - - fn try_from(msg: Notification) -> Result { - let params = msg - .params - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(msg.params.clone()))?; - let (extra_nonce1, extra_nonce2_size) = match ¶ms[..] { - [JString(a), JNumber(b)] => ( - Extranonce::try_from(hex_decode(a)?)?, - b.as_u64() - .ok_or_else(|| ParsingMethodError::not_unsigned_from_value(b.clone()))? - as usize, - ), - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - Ok(SetExtranonce { - extra_nonce1, - extra_nonce2_size, - }) - } -} - -#[derive(Debug, Clone)] -/// Server may arbitrarily adjust version mask -pub struct SetVersionMask { - pub version_mask: HexU32Be, -} - -impl fmt::Display for SetVersionMask { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "SetVersionMask {{ version_mask: {} }}", - self.version_mask - ) - } -} - -impl From for Message { - fn from(sv: SetVersionMask) -> Self { - let version_mask: Value = sv.version_mask.into(); - Message::Notification(Notification { - method: "mining.set_version".to_string(), - params: (&[version_mask][..]).into(), - }) - } -} - -impl TryFrom for SetVersionMask { - type Error = ParsingMethodError; - - fn try_from(msg: Notification) -> Result { - let params = msg - .params - .as_array() - .ok_or_else(|| ParsingMethodError::not_array_from_value(msg.params.clone()))?; - let version_mask = match ¶ms[..] { - [JString(a)] => a.as_str().try_into()?, - _ => return Err(ParsingMethodError::wrong_args_from_value(msg.params)), - }; - Ok(SetVersionMask { version_mask }) - } -} - -//pub struct Authorize(pub crate::json_rpc::Response, pub String); - -/// Authorize and Submit responsed are identical -#[derive(Debug, Clone)] -pub struct GeneralResponse { - pub id: u64, - pub result: bool, -} - -impl fmt::Display for GeneralResponse { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "GeneralResponse {{ id: {}, result: {} }}", - self.id, self.result - ) - } -} - -impl GeneralResponse { - pub fn into_authorize(self, prev_request_name: String) -> Authorize { - Authorize { - id: self.id, - authorized: self.result, - prev_request_name, - } - } - pub fn into_submit(self) -> Submit { - Submit { - id: self.id, - is_ok: self.result, - } - } - - pub fn into_extranonce_subscribe(self) -> ExtranonceSubscribe { - ExtranonceSubscribe { - id: self.id, - acknowledged: self.result, - } - } -} - -impl TryFrom<&Response> for GeneralResponse { - type Error = ParsingMethodError; - - fn try_from(msg: &Response) -> Result { - let id = msg.id; - let result = msg.result.as_bool().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseResultField(Box::new(msg.clone())) - })?; - Ok(GeneralResponse { id, result }) - } -} - -/// Response to `mining.extranonce.subscribe`. -#[derive(Debug, Clone)] -pub struct ExtranonceSubscribe { - pub id: u64, - pub acknowledged: bool, -} - -impl ExtranonceSubscribe { - pub fn is_ok(&self) -> bool { - self.acknowledged - } -} - -#[derive(Debug, Clone)] -pub struct Authorize { - pub id: u64, - pub authorized: bool, - pub prev_request_name: String, -} - -impl fmt::Display for Authorize { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Authorize {{ id: {}, authorized: {}, prev_request_name: {} }}", - self.id, self.authorized, self.prev_request_name - ) - } -} - -impl Authorize { - pub fn is_ok(&self) -> bool { - self.authorized - } - - pub fn user_name(self) -> String { - self.prev_request_name - } -} - -#[derive(Debug, Clone)] -pub struct Submit { - pub id: u64, - pub is_ok: bool, -} - -impl fmt::Display for Submit { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Submit {{ id: {}, is_ok: {} }}", self.id, self.is_ok) - } -} - -impl Submit { - pub fn is_ok(&self) -> bool { - self.is_ok - } -} - -/// mining.subscribe -/// mining.subscribe("user agent/version", "extranonce1") -/// The optional second parameter specifies a mining.notify subscription id the client wishes to -/// resume working with (possibly due to a dropped connection). If provided, a server MAY (at its -/// option) issue the connection the same extranonce1. Note that the extranonce1 may be the same -/// (allowing a resumed connection) even if the subscription id is changed! -/// -/// The client receives a result: -/// -/// -/// The result contains three items: -/// -/// Subscriptions. - An array of 2-item tuples, each with a subscription type and id. -/// -/// ExtraNonce1. - Hex-encoded, per-connection unique string which will be used for creating -/// generation transactions later. -/// -/// ExtraNonce2_size. - The number of bytes that the miner users for its ExtraNonce2 counter. -#[derive(Debug, Clone)] -pub struct Subscribe { - pub id: u64, - pub extra_nonce1: Extranonce, - pub extra_nonce2_size: usize, - pub subscriptions: Vec<(String, String)>, -} - -impl fmt::Display for Subscribe { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Subscribe {{ id: {}, extra_nonce1: {}, extra_nonce2_size: {}, subscriptions: {:?} }}", - self.id, self.extra_nonce1, self.extra_nonce2_size, self.subscriptions - ) - } -} - -impl From for Message { - fn from(su: Subscribe) -> Self { - let extra_nonce1: Value = su.extra_nonce1.into(); - let extra_nonce2_size: Value = su.extra_nonce2_size.into(); - let subscriptions: Vec = su - .subscriptions - .iter() - .map(|x| JArrary(vec![JString(x.0.clone()), JString(x.1.clone())])) - .collect(); - let subscriptions: Value = subscriptions.into(); - Message::OkResponse(Response { - id: su.id, - error: None, - result: (&[subscriptions, extra_nonce1, extra_nonce2_size][..]).into(), - }) - } -} - -impl TryFrom<&Response> for Subscribe { - type Error = ParsingMethodError; - - fn try_from(msg: &Response) -> Result { - let id = msg.id; - let params = msg.result.as_array().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseResultField(Box::new(msg.clone())) - })?; - let (subscriptions_, extra_nonce1, extra_nonce2_size) = match ¶ms[..] { - [JArrary(a), JString(b), JNumber(c)] => ( - a, - // infallible - b.as_str().try_into()?, - c.as_u64().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseAsU64(Box::new(c.clone())) - })? as usize, - ), - _ => return Err(ParsingMethodError::UnexpectedArrayParams(params.clone())), - }; - let mut subscriptions: Vec<(String, String)> = vec![]; - for s in subscriptions_ { - let s = s - .as_array() - .ok_or_else(|| ParsingMethodError::UnexpectedArrayParams(params.clone()))?; - if s.len() != 2 { - return Err(ParsingMethodError::UnexpectedArrayParams(params.clone())); - }; - let s = ( - s[0].as_str() - .ok_or_else(|| ParsingMethodError::UnexpectedArrayParams(params.clone()))? - .to_string(), - s[1].as_str() - .ok_or_else(|| ParsingMethodError::UnexpectedArrayParams(params.clone()))? - .to_string(), - ); - subscriptions.push(s); - } - Ok(Subscribe { - id, - extra_nonce1, - extra_nonce2_size, - subscriptions, - }) - } -} - -#[derive(Debug, Clone)] -pub struct Configure { - pub id: u64, - pub version_rolling: Option, - pub minimum_difficulty: Option, -} - -impl fmt::Display for Configure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Configure {{ id: {}, version_rolling: {:?}, minimum_difficulty: {:?} }}", - self.id, self.version_rolling, self.minimum_difficulty - ) - } -} - -impl Configure { - pub fn version_rolling_mask(&self) -> Option { - match &self.version_rolling { - None => None, - Some(a) => { - if a.version_rolling { - Some(a.version_rolling_mask.clone()) - } else { - None - } - } - } - } - pub fn version_rolling_min_bit(&self) -> Option { - match &self.version_rolling { - None => None, - Some(a) => { - if a.version_rolling { - Some(a.version_rolling_min_bit_count.clone()) - } else { - None - } - } - } - } -} - -impl From for Message { - fn from(co: Configure) -> Self { - let mut params = serde_json::Map::new(); - if let Some(version_rolling_) = co.version_rolling { - let mut version_rolling: serde_json::Map = version_rolling_.into(); - params.append(&mut version_rolling); - }; - if let Some(min_diff) = co.minimum_difficulty { - let minimum_difficulty: Value = min_diff.into(); - params.insert("minimum-difficulty".to_string(), minimum_difficulty); - }; - Message::OkResponse(Response { - id: co.id, - error: None, - result: serde_json::Value::Object(params), - }) - } -} - -impl TryFrom<&Response> for Configure { - type Error = ParsingMethodError; - - fn try_from(msg: &Response) -> Result { - let id = msg.id; - let params = msg.result.as_object().ok_or_else(|| { - ParsingMethodError::ImpossibleToParseResultField(Box::new(msg.clone())) - })?; - - let version_rolling_ = params.get("version-rolling"); - let version_rolling_mask = params.get("version-rolling.mask"); - let version_rolling_min_bit_count = params.get("version-rolling.min-bit-count"); - let minimum_difficulty = params.get("minimum-difficulty"); - - // Deserialize version-rolling response. - // Composed by 3 fields: - // version-rolling (required), - // version-rolling.mask (required) - // version-rolling.min-bit-count (optional) - let version_rolling: Option; - if version_rolling_.is_some() && version_rolling_mask.is_some() { - let vr: bool = version_rolling_ - .unwrap() - .as_bool() - .ok_or_else(|| ParsingMethodError::UnexpectedObjectParams(params.clone()))?; - - let version_rolling_mask: HexU32Be = version_rolling_mask - .unwrap() - .as_str() - .ok_or_else(|| ParsingMethodError::UnexpectedObjectParams(params.clone()))? - .try_into()?; - - // version-rolling.min-bit-count is often not returned by stratum servers, - // but min-bit-count should be taken into consideration in the returned mask - let version_rolling_min_bit_count: HexU32Be = match version_rolling_min_bit_count { - Some(version_rolling_min_bit_count) => version_rolling_min_bit_count - .as_str() - .ok_or_else(|| ParsingMethodError::UnexpectedObjectParams(params.clone()))? - .try_into()?, - None => HexU32Be(0), - }; - - version_rolling = Some(VersionRollingParams { - version_rolling: vr, - version_rolling_mask, - version_rolling_min_bit_count, - }); - } else if version_rolling_.is_none() - && version_rolling_mask.is_none() - && version_rolling_min_bit_count.is_none() - { - version_rolling = None; - } else { - return Err(ParsingMethodError::UnexpectedObjectParams(params.clone())); - }; - - let minimum_difficulty = match minimum_difficulty { - Some(a) => Some( - a.as_bool() - .ok_or_else(|| ParsingMethodError::UnexpectedObjectParams(params.clone()))?, - ), - None => None, - }; - - Ok(Configure { - id, - version_rolling, - minimum_difficulty, - }) - } -} - -#[derive(Debug, Clone)] -pub struct VersionRollingParams { - pub version_rolling: bool, - pub version_rolling_mask: HexU32Be, - pub version_rolling_min_bit_count: HexU32Be, -} - -impl fmt::Display for VersionRollingParams { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "VersionRollingParams {{ version_rolling: {}, version_rolling_mask: {}, version_rolling_min_bit_count: {} }}", - self.version_rolling, - self.version_rolling_mask, - self.version_rolling_min_bit_count - ) - } -} - -#[test] -fn configure_response_parsing_all_fields() { - let client_response_str = r#"{"id":0, - "result":{ - "version-rolling":true, - "version-rolling.mask":"1fffffe0", - "version-rolling.min-bit-count":"00000005", - "minimum-difficulty":false - } - }"#; - let client_response = serde_json::from_str(client_response_str).unwrap(); - let server_configure = Configure::try_from(&client_response).unwrap(); - println!("{server_configure:?}"); - - let version_rolling = server_configure.version_rolling.unwrap(); - assert!(version_rolling.version_rolling); - assert_eq!( - version_rolling.version_rolling_mask, - HexU32Be(VERSION_ROLLING_MASK) - ); - assert_eq!(version_rolling.version_rolling_min_bit_count, HexU32Be(5)); - - assert_eq!(server_configure.minimum_difficulty, Some(false)); -} - -#[test] -fn configure_response_parsing_no_vr_min_bit_count() { - let client_response_str = r#"{"id":0, - "result":{ - "version-rolling":true, - "version-rolling.mask":"1fffffe0", - "minimum-difficulty":false - } - }"#; - let client_response = serde_json::from_str(client_response_str).unwrap(); - let server_configure = Configure::try_from(&client_response).unwrap(); - println!("{server_configure:?}"); - - let version_rolling = server_configure.version_rolling.unwrap(); - assert!(version_rolling.version_rolling); - assert_eq!( - version_rolling.version_rolling_mask, - HexU32Be(VERSION_ROLLING_MASK) - ); - assert_eq!(version_rolling.version_rolling_min_bit_count, HexU32Be(0)); - - assert_eq!(server_configure.minimum_difficulty, Some(false)); -} - -#[test] -fn subscribe_response_crash_on_object_in_subscriptions() { - let json = r#"{ - "id": 2199023913727, - "error": null, - "result": [ - [{"": [[null, null, null], {}, null]}], - "", - 186546217025536 - ] - }"#; - let response: crate::json_rpc::Response = serde_json::from_str(json).unwrap(); - let result = crate::methods::Server2ClientResponse::try_from(response); - assert!(result.is_err()); -} - -#[test] -fn subscribe_response_crash_on_non_ascii_hex_extranonce() { - let json = r#"{ - "id": 0, - "error": null, - "result": [ - ["mining.notify", "1"], - "55555ʛ", - 4 - ] - }"#; - - let response: crate::json_rpc::Response = serde_json::from_str(json).unwrap(); - let result = crate::methods::Server2ClientResponse::try_from(response); - assert!(result.is_err(), "{:?}", result); -} - -#[test] -fn subscribe_response_crash_on_too_long_extranonce() { - let json = format!( - r#"{{"id":0,"error":null,"result":[["mining.notify","1"],"{}",4]}}"#, - "ff".repeat(33) - ); - let response: crate::json_rpc::Response = serde_json::from_str(&json).unwrap(); - let result = crate::methods::Server2ClientResponse::try_from(response); - assert!( - matches!( - result, - Err(ParsingMethodError::MultipleError(ref v)) if v.iter().any(|e| matches!(e, ParsingMethodError::BadBytesConvert(_))) - ), - "{:?}", - result - ); -} - -impl VersionRollingParams { - /// Clamps `version_rolling_mask` to the general purpose version bits defined by - /// [`VERSION_ROLLING_MASK`], so the negotiated mask can never set reserved bits. - pub fn new(version_rolling_mask: HexU32Be, version_rolling_min_bit_count: HexU32Be) -> Self { - VersionRollingParams { - version_rolling: true, - version_rolling_mask: HexU32Be(version_rolling_mask & VERSION_ROLLING_MASK), - version_rolling_min_bit_count, - } - } -} - -impl From for serde_json::Map { - fn from(vp: VersionRollingParams) -> Self { - let version_rolling: Value = vp.version_rolling.into(); - let version_rolling_mask: Value = vp.version_rolling_mask.into(); - let version_rolling_min_bit_count: Value = vp.version_rolling_min_bit_count.into(); - let mut params = serde_json::Map::new(); - params.insert("version-rolling".to_string(), version_rolling); - params.insert("version-rolling.mask".to_string(), version_rolling_mask); - params.insert( - "version-rolling.min-bit-count".to_string(), - version_rolling_min_bit_count, - ); - params - } -} diff --git a/sv1/src/utils.rs b/sv1/src/utils.rs index a013174c1f..811ea99917 100644 --- a/sv1/src/utils.rs +++ b/sv1/src/utils.rs @@ -1,10 +1,9 @@ -use crate::error::{self, Error}; -use binary_sv2::{B032Owned, U256Owned, B032, ERROR_SAMPLE_LEN}; +use crate::error::{self, Error, ParamError}; +use binary_sv2::{B032Owned, U256Owned}; use bitcoin::hashes::hex::{DisplayHex, FromHex}; -use byteorder::{BigEndian, ByteOrder, LittleEndian, WriteBytesExt}; -use serde_json::Value; +use serde_json::{Number, Value}; use std::fmt; -use std::{convert::TryFrom, mem::size_of, ops::BitAnd}; +use std::{convert::TryFrom, ops::BitAnd}; /// Version rolling mask as defined by /// [BIP323](https://github.com/bitcoin/bips/blob/master/bip-0323.mediawiki). @@ -13,6 +12,9 @@ use std::{convert::TryFrom, mem::size_of, ops::BitAnd}; /// manipulated by the miner. Bits 0-4 and 29-31 are reserved and must not be rolled. pub const VERSION_ROLLING_MASK: u32 = 0x1FFFFFE0; +/// The most bytes an [`Extranonce`] holds. +pub(crate) const MAX_EXTRANONCE_LEN: usize = 32; + /// Helper type that allows simple serialization and deserialization of byte vectors /// that are represented as hex strings in JSON. /// Extranonce must be less than or equal to 32 bytes. @@ -61,29 +63,20 @@ pub(crate) fn hex_decode(s: &str) -> Result, Error> { Ok(Vec::::from_hex(s)?) } -/// Decodes a hexadecimal string into bytes. -/// -/// Odd-length inputs are left-padded with `0`. -pub fn hex_decode_with_padding(s: &str) -> Result, Error> { - let padded; - - let s = if s.len() % 2 != 0 { - padded = format!("0{s}"); - &padded - } else { - s - }; - - hex_decode(s) -} - +/// Odd-length input is left-padded with `0`. impl TryFrom<&str> for Extranonce { type Error = error::Error; fn try_from(value: &str) -> Result { - Ok(Extranonce(B032Owned::try_from(hex_decode_with_padding( - value, - )?)?)) + if value.len() > 2 * MAX_EXTRANONCE_LEN { + return Err(Error::InvalidHexLen(value.len())); + } + let bytes = if value.len() % 2 == 0 { + hex_decode(value)? + } else { + hex_decode(&format!("0{value}"))? + }; + Extranonce::try_from(bytes) } } @@ -94,21 +87,15 @@ impl From for String { } impl BitAnd for HexU32Be { - type Output = u32; + type Output = HexU32Be; fn bitand(self, rhs: u32) -> Self::Output { - self.0 & rhs - } -} - -impl<'a> From> for Extranonce { - fn from(b: B032<'a>) -> Self { - Extranonce(b.into_owned()) + HexU32Be(self.0 & rhs) } } /// Big-endian alternative of the HexU32 -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct HexU32Be(pub u32); impl fmt::Display for HexU32Be { @@ -118,8 +105,9 @@ impl fmt::Display for HexU32Be { } impl HexU32Be { - pub fn check_mask(&self, mask: &HexU32Be) -> bool { - ((!self.0) & mask.0) == 0 + /// Whether this mask allows every bit set in `bits`. + pub fn check_mask(&self, bits: &HexU32Be) -> bool { + ((!self.0) & bits.0) == 0 } } @@ -135,7 +123,7 @@ impl TryFrom<&str> for HexU32Be { fn try_from(value: &str) -> Result { let expected_len = 8; if value.len() > expected_len { - return Err(Error::InvalidHexLen(value.to_string())); + return Err(Error::InvalidHexLen(value.len())); } let delta_len = expected_len - value.len(); @@ -146,7 +134,7 @@ impl TryFrom<&str> for HexU32Be { prefix.push_str(value); let parsed_bytes: [u8; 4] = hex_decode(&prefix)? .try_into() - .map_err(|_| Error::InvalidHexLen(prefix.clone()))?; + .map_err(|_| Error::InvalidHexLen(prefix.len()))?; Ok(HexU32Be(u32::from_be_bytes(parsed_bytes))) } } @@ -183,45 +171,26 @@ impl From for Vec { } } +/// The bytes are taken in header order, without the word swap of the hex form. +impl TryFrom> for PrevHash { + type Error = Error; + + fn try_from(value: Vec) -> Result { + Ok(PrevHash(U256Owned::try_from(value)?)) + } +} + impl TryFrom<&str> for PrevHash { type Error = Error; fn try_from(value: &str) -> Result { - // Reorder PrevHash will be stored via this cursor - // let mut prev_hash_cursor = std::io::Cursor::new([0_u8; 32]); - let mut prev_hash_arr = [0_u8; 32]; - - // Decode the plain byte array and sanity check - let prev_hash_stratum_order = hex_decode(value)?; - - match prev_hash_stratum_order.len() { - 32 => { - // Swap every u32 from big endian to little endian byte order - for (chunk, mut arr_chunks) in prev_hash_stratum_order - .chunks(size_of::()) - .zip(prev_hash_arr.chunks_mut(size_of::())) - { - let prev_hash_word = BigEndian::read_u32(chunk); - arr_chunks - .write_u32::(prev_hash_word) - .expect("Internal error: Could not write buffer"); - } - Ok(PrevHash(prev_hash_arr.into())) - } - _ => { - let len = prev_hash_stratum_order.len(); - Err(error::Error::BadBytesConvert( - binary_sv2::Error::ValueExceedsMaxSize( - true, - 32, - 0, - 0, - prev_hash_stratum_order[..len.min(ERROR_SAMPLE_LEN)].to_vec(), - len, - ), - )) - } + if value.len() != 64 { + return Err(Error::InvalidHexLen(value.len())); } + let mut bytes = hex_decode(value)?; + reverse_words(&mut bytes); + let bytes: [u8; 32] = bytes.try_into().expect("64 hex characters are 32 bytes"); + Ok(PrevHash(bytes.into())) } } @@ -235,15 +204,17 @@ impl From for Value { /// ordering impl From for String { fn from(v: PrevHash) -> Self { - let mut prev_hash_stratum_cursor = std::io::Cursor::new(Vec::new()); - // swap every u32 from little endian to big endian - for chunk in v.0.as_bytes().chunks(size_of::()) { - let prev_hash_word = LittleEndian::read_u32(chunk); - prev_hash_stratum_cursor - .write_u32::(prev_hash_word) - .expect("Internal error: Could not write buffer"); - } - prev_hash_stratum_cursor.into_inner().to_lower_hex_string() + let mut bytes = v.0.into_bytes(); + reverse_words(&mut bytes); + bytes.to_lower_hex_string() + } +} + +/// Reverses the byte order of each 4-byte word, converting between Stratum V1's previous-hash +/// encoding and the header's byte order. +fn reverse_words(bytes: &mut [u8]) { + for word in bytes.chunks_exact_mut(4) { + word.reverse(); } } @@ -254,13 +225,6 @@ impl AsRef<[u8]> for PrevHash { } } -/// Referencing the internal part of hex bytes -impl AsRef for PrevHash { - fn as_ref(&self) -> &U256Owned { - &self.0 - } -} - /// Referencing the internal part of hex bytes impl AsRef<[u8]> for Extranonce { fn as_ref(&self) -> &[u8] { @@ -277,12 +241,6 @@ impl fmt::Display for MerkleNode { } } -impl MerkleNode { - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } -} - impl TryFrom> for MerkleNode { type Error = Error; @@ -315,6 +273,9 @@ impl TryFrom<&str> for MerkleNode { type Error = Error; fn try_from(value: &str) -> Result { + if value.len() != 64 { + return Err(Error::InvalidHexLen(value.len())); + } let merkle = U256Owned::try_from(hex_decode(value)?).map_err(error::Error::from)?; Ok(MerkleNode(merkle)) } @@ -326,11 +287,9 @@ impl From for String { } } -/// Helper type that allows simple serialization and deserialization of byte vectors -/// that are represented as hex strings in JSON. -/// HexBytes must be less than or equal to 32 bytes. +/// Bytes of any length, represented as a hex string in JSON. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct HexBytes(Vec); +pub struct HexBytes(pub Vec); impl fmt::Display for HexBytes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -366,8 +325,8 @@ impl From for Value { } /// Referencing the internal part of hex bytes -impl AsRef> for HexBytes { - fn as_ref(&self) -> &Vec { +impl AsRef<[u8]> for HexBytes { + fn as_ref(&self) -> &[u8] { &self.0 } } @@ -386,6 +345,62 @@ impl From for String { } } +// Readers for positional parameters and results, shared by the message modules. + +pub(crate) fn params_array(params: &Value) -> Result<&[Value], ParamError> { + params + .as_array() + .map(Vec::as_slice) + .ok_or(ParamError::new("params", "not an array")) +} + +/// The positional parameters of a message its decoder owns, so strings can be moved out. +pub(crate) fn params_array_mut(params: &mut Value) -> Result<&mut [Value], ParamError> { + params + .as_array_mut() + .map(Vec::as_mut_slice) + .ok_or(ParamError::new("params", "not an array")) +} + +/// Short hex is left-padded. +pub(crate) fn hex_u32(value: &str, field: &'static str) -> Result { + HexU32Be::try_from(value).map_err(|_| ParamError::new(field, "not a 32-bit hex value")) +} + +pub(crate) fn integer_u32(value: &Number, field: &'static str) -> Result { + value + .as_u64() + .and_then(|value| u32::try_from(value).ok()) + .map(HexU32Be) + .ok_or(ParamError::new(field, "not a 32-bit unsigned integer")) +} + +/// Reads a `version-rolling.min-bit-count`. +/// +/// BIP 310 makes it an integer. Strings are accepted for compatibility: eight characters are the +/// zero-padded hex that older SRI clients sent, anything shorter is decimal. +pub(crate) fn min_bit_count(value: &Value, field: &'static str) -> Result { + match value { + Value::Number(count) => integer_u32(count, field).map(|count| count.0), + Value::String(count) if count.len() == 8 => hex_u32(count, field).map(|count| count.0), + Value::String(count) => count + .parse() + .map_err(|_| ParamError::new(field, "not a decimal integer")), + _ => Err(ParamError::new(field, "not an integer")), + } +} + +/// A size larger than [`MAX_EXTRANONCE_LEN`] could not be carried by a `mining.submit`. +pub(crate) fn extranonce2_size_param(size: &Number) -> Result { + size.as_u64() + .and_then(|size| usize::try_from(size).ok()) + .filter(|size| *size <= MAX_EXTRANONCE_LEN) + .ok_or(ParamError::new( + "extranonce2_size", + "not an integer up to 32", + )) +} + #[cfg(test)] mod tests { use super::*; @@ -399,7 +414,7 @@ mod tests { let back_to_hex_value = Value::from(me.clone()); let value_to_string = back_to_hex_value.as_str().unwrap(); - let chunk_size: usize = size_of::(); + let chunk_size: usize = std::mem::size_of::(); let me_chunks = me.0.as_bytes().chunks(chunk_size); for (be_chunk, le_chunk) in bytes.clone().chunks(chunk_size).zip(me_chunks) { let le_chunk = [le_chunk[0], le_chunk[1], le_chunk[2], le_chunk[3]]; @@ -415,6 +430,32 @@ mod tests { be_hex == back_to_hex && be_hex == value_to_string } + #[test] + fn oversized_hex_is_rejected_before_decoding() { + let not_hex = "zz".repeat(1000); + assert!(matches!( + PrevHash::try_from(not_hex.as_str()), + Err(Error::InvalidHexLen(2000)) + )); + assert!(matches!( + MerkleNode::try_from(not_hex.as_str()), + Err(Error::InvalidHexLen(2000)) + )); + assert!(matches!( + Extranonce::try_from(not_hex.as_str()), + Err(Error::InvalidHexLen(2000)) + )); + assert!(Extranonce::try_from("ab".repeat(32).as_str()).is_ok()); + assert!(!Error::InvalidHexLen(9).to_string().contains('z')); + } + + #[test] + fn prev_hash_try_from_vec_keeps_header_order() { + let bytes: Vec = (0..32).collect(); + assert_eq!(PrevHash::try_from(bytes.clone()).unwrap().as_ref(), bytes); + assert!(PrevHash::try_from(vec![0_u8; 31]).is_err()); + } + #[test] fn merkle_node_try_from_vec_invalid_len_returns_err() { assert!(MerkleNode::try_from(vec![0_u8; 31]).is_err()); diff --git a/sv1/tests/wire_compat.rs b/sv1/tests/wire_compat.rs new file mode 100644 index 0000000000..e0f0d84bd4 --- /dev/null +++ b/sv1/tests/wire_compat.rs @@ -0,0 +1,967 @@ +//! Wire forms that `sv1_api` accepts from peers, and the JSON it emits. + +use bitcoin::hashes::hex::DisplayHex; +use serde_json::{json, Value}; +use std::convert::TryFrom; +use sv1_api::{ + error::{DecodeError, DecodeErrorKind, Error}, + json_rpc, + utils::{Extranonce, HexU32Be}, + Authorize, ClientToServer, Configure, ConfigureExtension, ConfigureResult, Id, Message, Method, + Notify, Request, Response, RpcError, ServerToClient, SetDifficulty, SetExtranonce, + SetVersionMask, SubmitError, SubmitOutcome, SubscribeResult, VersionRollingResult, +}; + +fn decode(line: &str) -> Message { + Message::decode(line).unwrap_or_else(|e| panic!("{line}: {e}")) +} + +fn try_client_request(line: &str) -> Result { + match decode(line) { + Message::Request(request) => ClientToServer::try_from(request), + other => panic!("{line}: not a request: {other:?}"), + } +} + +fn client_request(line: &str) -> ClientToServer { + try_client_request(line).unwrap_or_else(|e| panic!("{line}: {e}")) +} + +fn server_notification(line: &str) -> ServerToClient { + match decode(line) { + Message::Request(request) => { + ServerToClient::try_from(request).unwrap_or_else(|e| panic!("{line}: {e}")) + } + other => panic!("{line}: not a notification: {other:?}"), + } +} + +fn server_response(line: &str) -> json_rpc::Response { + match decode(line) { + Message::Response(response) => response, + other => panic!("{line}: not a response: {other:?}"), + } +} + +fn typed(line: &str, method: Method) -> Result, Error> { + ServerToClient::from_response(&server_response(line), &method) +} + +fn subscribe_result(line: &str) -> SubscribeResult { + match typed(line, Method::Subscribe) { + Ok(Some(ServerToClient::Subscribe(Response { + result: Ok(result), .. + }))) => result, + other => panic!("{line}: not a subscribe result: {other:?}"), + } +} + +fn configure_result(line: &str) -> ConfigureResult { + match typed(line, Method::Configure) { + Ok(Some(ServerToClient::Configure(Response { + result: Ok(result), .. + }))) => result, + other => panic!("{line}: not a configure result: {other:?}"), + } +} + +fn kind(message: &Message) -> &'static str { + match message { + Message::Request(request) if request.id.is_some() => "request", + Message::Request(_) => "notification", + Message::Response(response) if response.result.is_ok() => "ok", + Message::Response(_) => "error", + } +} + +fn hex(bytes: impl Into>) -> String { + bytes.into().to_lower_hex_string() +} + +fn to_json(message: impl Into) -> Value { + serde_json::to_value(message.into()).unwrap() +} + +#[test] +fn envelope_kinds() { + let cases = [ + ( + r#"{"id":1,"method":"mining.subscribe","params":[]}"#, + "request", + ), + ( + r#"{"jsonrpc":"2.0","id":1,"method":"mining.subscribe","params":[]}"#, + "request", + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":[],"error":null}"#, + "request", + ), + ( + r#"{"id":1,"method":"mining.extranonce.subscribe","params":null}"#, + "request", + ), + ( + r#"{"method":"mining.set_difficulty","params":[2]}"#, + "notification", + ), + ( + r#"{"id":null,"method":"mining.set_difficulty","params":[2]}"#, + "notification", + ), + ( + r#"{"id":null,"method":"mining.set_difficulty","params":[2],"result":null,"error":null}"#, + "notification", + ), + (r#"{"id":1,"result":true,"error":null}"#, "ok"), + (r#"{"id":1,"result":true}"#, "ok"), + ( + r#"{"id":1,"result":true,"error":null,"method":null,"params":null}"#, + "ok", + ), + ( + r#"{"id":1,"result":null,"error":[22,"Duplicate share",null]}"#, + "error", + ), + ( + r#"{"id":1,"result":null,"error":[22,"Duplicate share"]}"#, + "error", + ), + ( + r#"{"id":1,"result":null,"error":{"code":22,"message":"Duplicate share","data":null}}"#, + "error", + ), + ]; + for (line, expected) in cases { + assert_eq!(kind(&decode(line)), expected, "{line}"); + } +} + +#[test] +fn request_ids() { + for (line, id) in [ + ( + r#"{"id":1,"method":"mining.subscribe","params":[]}"#, + Id::from(1u64), + ), + ( + r#"{"id":"a1","method":"mining.subscribe","params":[]}"#, + Id::from("a1"), + ), + ] { + let decoded = client_request(line); + assert!(matches!(decoded, ClientToServer::Subscribe(..)), "{line}"); + assert_eq!(decoded.id(), &id, "{line}"); + } +} + +#[test] +fn request_errors() { + let kind = |line: &str| try_client_request(line).unwrap_err().kind; + assert!(matches!( + kind(r#"{"id":null,"method":"mining.submit","params":[]}"#), + DecodeErrorKind::MissingId + )); + assert!(matches!( + kind(r#"{"id":1,"method":"client.reconnect","params":[]}"#), + DecodeErrorKind::UnknownMethod + )); + assert!(matches!( + kind(r#"{"id":1,"method":"mining.notify","params":[]}"#), + DecodeErrorKind::UnknownMethod + )); + assert!(matches!( + kind(r#"{"id":1,"method":"mining.submit","params":["w","bf","00",4294967296,1]}"#), + DecodeErrorKind::InvalidParams { field: "ntime", .. } + )); +} + +#[test] +fn server_messages_exclude_client_methods() { + for line in [ + r#"{"id":1,"method":"mining.submit","params":[]}"#, + r#"{"id":9,"method":"client.reconnect","params":[]}"#, + ] { + let Message::Request(request) = decode(line) else { + panic!("{line}: not a request"); + }; + assert!(matches!( + ServerToClient::try_from(request).unwrap_err().kind, + DecodeErrorKind::UnknownMethod + )); + } +} + +#[test] +fn responses_are_not_requests() { + let response = decode(r#"{"id":1,"result":true,"error":null}"#); + assert!(matches!( + ClientToServer::try_from(response).unwrap_err().kind, + DecodeErrorKind::UnexpectedResponse + )); +} + +#[test] +fn subscribe_forms() { + let cases = [ + ( + r#"{"id":1,"method":"mining.subscribe","params":[]}"#, + "", + None, + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["cgminer/4.10.0"]}"#, + "cgminer/4.10.0", + None, + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["cgminer/4.10.0","08000002"]}"#, + "cgminer/4.10.0", + Some("08000002"), + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["cgminer/4.10.0","session-zz"]}"#, + "cgminer/4.10.0", + Some("session-zz"), + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["bosminer/1.0",null]}"#, + "bosminer/1.0", + None, + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["bosminer/1.0",null,"pool.example",null]}"#, + "bosminer/1.0", + None, + ), + ]; + for (line, agent, resume) in cases { + let ClientToServer::Subscribe(Request { + id, + params: subscribe, + }) = client_request(line) + else { + panic!("{line}: not a subscribe"); + }; + assert_eq!(id, Id::from(1u64), "{line}"); + assert_eq!(subscribe.agent, agent, "{line}"); + assert_eq!(subscribe.subscription_id.as_deref(), resume, "{line}"); + } +} + +#[test] +fn authorize_forms() { + for (params, password) in [ + (r#"["worker.1","x"]"#, "x"), + (r#"["worker.1"]"#, ""), + (r#"["worker.1",null]"#, ""), + ] { + let line = format!(r#"{{"id":2,"method":"mining.authorize","params":{params}}}"#); + let ClientToServer::Authorize(Request { + id, + params: authorize, + }) = client_request(&line) + else { + panic!("{line}: not an authorize"); + }; + assert_eq!(id, Id::from(2u64), "{line}"); + assert_eq!(authorize.worker_name, "worker.1", "{line}"); + assert_eq!(authorize.password, password, "{line}"); + } +} + +#[test] +fn authorize_password_is_redacted() { + let authorize = Authorize { + worker_name: "w".to_string(), + password: "hunter2".to_string(), + }; + assert!(!format!("{authorize:?}").contains("hunter2")); +} + +#[test] +fn submit_forms() { + let cases = [ + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000abcd","647025b5","1d2e3f40"]}"#, + None, + ), + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000abcd","647025b5","1d2e3f40","00002000"]}"#, + Some(0x2000), + ), + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000abcd",1685071285,489570112]}"#, + None, + ), + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000abcd",1685071285,489570112,"00002000"]}"#, + Some(0x2000), + ), + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000ABCD","647025b5","1d2e3f40"]}"#, + None, + ), + ]; + for (line, version_bits) in cases { + let ClientToServer::Submit(Request { id, params: submit }) = client_request(line) else { + panic!("{line}: not a submit"); + }; + assert_eq!(id, Id::from(4u64), "{line}"); + assert_eq!(submit.worker_name, "w", "{line}"); + assert_eq!(submit.job_id, "bf", "{line}"); + assert_eq!(hex(submit.extranonce2), "0000abcd", "{line}"); + assert_eq!(submit.ntime, HexU32Be(0x647025b5), "{line}"); + assert_eq!(submit.nonce, HexU32Be(0x1d2e3f40), "{line}"); + assert_eq!(submit.version_bits, version_bits.map(HexU32Be), "{line}"); + } +} + +#[test] +fn submit_short_hex_is_left_padded() { + let line = r#"{"id":4,"method":"mining.submit","params":["w","bf","00","5f5e100","1"]}"#; + let ClientToServer::Submit(Request { params: submit, .. }) = client_request(line) else { + panic!("not a submit"); + }; + assert_eq!(submit.ntime, HexU32Be(0x05f5e100)); + assert_eq!(submit.nonce, HexU32Be(1)); +} + +#[test] +fn extranonce_subscribe_ignores_params() { + for params in ["[]", "null", "{}", r#"["x"]"#] { + let line = + format!(r#"{{"id":5,"method":"mining.extranonce.subscribe","params":{params}}}"#); + let ClientToServer::ExtranonceSubscribe(Request { id, .. }) = client_request(&line) else { + panic!("{line}: not an extranonce subscribe"); + }; + assert_eq!(id, Id::from(5u64), "{line}"); + } +} + +#[test] +fn suggest_difficulty_accepts_any_params() { + for (params, difficulty) in [ + ("[512]", Some(512.0)), + ("[0.5]", Some(0.5)), + ("[]", None), + (r#"["1024"]"#, None), + ("[-1]", None), + ("null", None), + ("{}", None), + ] { + let line = format!(r#"{{"id":6,"method":"mining.suggest_difficulty","params":{params}}}"#); + let ClientToServer::SuggestDifficulty(Request { + id, + params: suggest, + }) = client_request(&line) + else { + panic!("{line}: not a suggest_difficulty"); + }; + assert_eq!(id, Id::from(6u64), "{line}"); + assert_eq!(suggest.difficulty, difficulty, "{line}"); + } +} + +fn configure_summary(configure: &Configure) -> Vec { + configure + .extensions + .iter() + .map(|extension| match extension { + ConfigureExtension::VersionRolling(params) => format!( + "version-rolling mask={:?} min={:?}", + params.mask.as_ref().map(|m| m.0), + params.min_bit_count + ), + ConfigureExtension::MinimumDifficulty(value) => format!("minimum-difficulty {value}"), + ConfigureExtension::SubscribeExtranonce => "subscribe-extranonce".to_string(), + ConfigureExtension::Info(info) => format!("info {:?}", info.connection_url), + other => format!("{other:?}"), + }) + .collect() +} + +#[test] +fn configure_forms() { + let cases: [(&str, &[&str]); 14] = [ + ( + r#"[["version-rolling"],{"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":2}]"#, + &["version-rolling mask=Some(536862720) min=Some(2)"], + ), + ( + r#"[["version-rolling"],{"version-rolling.mask":"1fffe000"}]"#, + &["version-rolling mask=Some(536862720) min=None"], + ), + ( + r#"[["version-rolling"],{"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":"00000010"}]"#, + &["version-rolling mask=Some(536862720) min=Some(16)"], + ), + ( + r#"[["version-rolling"],{"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":"16"}]"#, + &["version-rolling mask=Some(536862720) min=Some(16)"], + ), + (r#"[["version-rolling"]]"#, &[]), + (r#"[["version-rolling"],null]"#, &[]), + ( + r#"[["version-rolling"],{"version-rolling.mask":"1fffe000"},"extra"]"#, + &["version-rolling mask=Some(536862720) min=None"], + ), + ( + r#"[["version-rolling","version-rolling"],{"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":2}]"#, + &["version-rolling mask=Some(536862720) min=Some(2)"], + ), + (r#"[[""],{}]"#, &[]), + ( + r#"[[],{"version-rolling.mask":"1fffe000"}]"#, + &["version-rolling mask=Some(536862720) min=None"], + ), + (r#"[["subscribe-extranonce"]]"#, &["subscribe-extranonce"]), + ( + r#"[["minimum-difficulty"],{"minimum-difficulty.value":1024}]"#, + &["minimum-difficulty 1024"], + ), + ( + r#"[["info"],{"info.connection-url":"stratum+tcp://pool.example:3333","info.hw-version":"S19"}]"#, + &["info Some(\"stratum+tcp://pool.example:3333\")"], + ), + ( + r#"[["version-rolling","minimum-difficulty","subscribe-extranonce"],{"version-rolling.mask":"ffffffff","version-rolling.min-bit-count":16,"minimum-difficulty.value":2048}]"#, + &[ + "subscribe-extranonce", + "version-rolling mask=Some(4294967295) min=Some(16)", + "minimum-difficulty 2048", + ], + ), + ]; + for (params, expected) in cases { + let line = format!(r#"{{"id":7,"method":"mining.configure","params":{params}}}"#); + let ClientToServer::Configure(Request { + id, + params: configure, + }) = client_request(&line) + else { + panic!("{line}: not a configure"); + }; + assert_eq!(id, Id::from(7u64), "{line}"); + assert_eq!(configure_summary(&configure), expected, "{line}"); + } +} + +#[test] +fn configure_connection_url_is_redacted() { + let line = r#"{"id":7,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://user:secret@pool.example"}]}"#; + assert!(!format!("{:?}", client_request(line)).contains("secret")); +} + +#[test] +fn client_requests_encode_canonically() { + for (line, canonical) in [ + ( + r#"{"id":1,"method":"mining.subscribe","params":[]}"#, + json!({"id": 1, "method": "mining.subscribe", "params": []}), + ), + ( + r#"{"id":1,"method":"mining.subscribe","params":["bosminer/1.0",null,"pool.example",null]}"#, + json!({"id": 1, "method": "mining.subscribe", "params": ["bosminer/1.0"]}), + ), + ( + r#"{"id":"a","method":"mining.subscribe","params":["cgminer/4.10.0","08000002"]}"#, + json!({"id": "a", "method": "mining.subscribe", "params": ["cgminer/4.10.0", "08000002"]}), + ), + ( + r#"{"id":2,"method":"mining.authorize","params":["w"]}"#, + json!({"id": 2, "method": "mining.authorize", "params": ["w", ""]}), + ), + ( + r#"{"id":4,"method":"mining.submit","params":["w","bf","0000ABCD",1685071285,489570112,"00002000"]}"#, + json!({"id": 4, "method": "mining.submit", "params": ["w", "bf", "0000abcd", "647025b5", "1d2e3f40", "00002000"]}), + ), + ( + r#"{"id":5,"method":"mining.extranonce.subscribe","params":null}"#, + json!({"id": 5, "method": "mining.extranonce.subscribe", "params": []}), + ), + ( + r#"{"id":6,"method":"mining.suggest_difficulty","params":[512]}"#, + json!({"id": 6, "method": "mining.suggest_difficulty", "params": [512.0]}), + ), + ( + r#"{"id":7,"method":"mining.configure","params":[["version-rolling","minimum-difficulty"],{"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":"00000002","minimum-difficulty.value":2048}]}"#, + json!({"id": 7, "method": "mining.configure", "params": [["version-rolling", "minimum-difficulty"], {"version-rolling.mask": "1fffe000", "version-rolling.min-bit-count": 2, "minimum-difficulty.value": 2048}]}), + ), + ] { + let request = client_request(line); + let method = request.method(); + let encoded = to_json(request.clone()); + assert_eq!(encoded["method"], method.as_str(), "{line}"); + assert_eq!(encoded, canonical, "{line}"); + assert_eq!(client_request(&encoded.to_string()), request, "{line}"); + } +} + +const NOTIFY_PARAMS: &str = r#"["bf","000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f","01000000010000","ffffffff",["2122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40"],"20000000","1705ae3a","647025b5",true]"#; + +fn notify_line() -> String { + format!(r#"{{"id":null,"method":"mining.notify","params":{NOTIFY_PARAMS}}}"#) +} + +#[test] +fn notify_form() { + for id in [r#""id":null,"#, "", r#""id":"x","#] { + let line = format!(r#"{{{id}"method":"mining.notify","params":{NOTIFY_PARAMS}}}"#); + let ServerToClient::Notify(notify) = server_notification(&line) else { + panic!("{line}: not a notify"); + }; + assert_eq!(notify.job_id, "bf", "{line}"); + assert_eq!( + hex(notify.prev_hash.clone()), + "03020100070605040b0a09080f0e0d0c13121110171615141b1a19181f1e1d1c", + "{line}" + ); + assert_eq!(hex(notify.coinbase1.clone()), "01000000010000", "{line}"); + assert_eq!(hex(notify.coinbase2.clone()), "ffffffff", "{line}"); + assert_eq!( + notify + .merkle_branch + .iter() + .cloned() + .map(hex) + .collect::>(), + ["2122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40"], + "{line}" + ); + assert_eq!(notify.version, HexU32Be(0x20000000), "{line}"); + assert_eq!(notify.nbits, HexU32Be(0x1705ae3a), "{line}"); + assert_eq!(notify.ntime, HexU32Be(0x647025b5), "{line}"); + assert!(notify.clean_jobs, "{line}"); + } +} + +fn notify() -> Notify { + match server_notification(¬ify_line()) { + ServerToClient::Notify(notify) => notify, + _ => panic!("not a notify"), + } +} + +#[test] +fn notify_encoding() { + let params: Value = serde_json::from_str(NOTIFY_PARAMS).unwrap(); + assert_eq!( + to_json(notify()), + json!({"id": null, "method": "mining.notify", "params": params}) + ); +} + +#[test] +fn other_notification_forms() { + let difficulty = |line: &str| match server_notification(line) { + ServerToClient::SetDifficulty(set) => set.difficulty, + _ => panic!("{line}: not a set_difficulty"), + }; + assert_eq!( + difficulty(r#"{"id":null,"method":"mining.set_difficulty","params":[2]}"#), + 2.0 + ); + assert_eq!( + difficulty(r#"{"id":null,"method":"mining.set_difficulty","params":[0.5]}"#), + 0.5 + ); + + let line = r#"{"id":null,"method":"mining.set_extranonce","params":["08000002",4]}"#; + let ServerToClient::SetExtranonce(set) = server_notification(line) else { + panic!("not a set_extranonce"); + }; + assert_eq!(hex(set.extranonce1), "08000002"); + assert_eq!(set.extranonce2_size, 4); + + let line = r#"{"id":null,"method":"mining.set_version_mask","params":["1fffe000"]}"#; + let ServerToClient::SetVersionMask(set) = server_notification(line) else { + panic!("not a set_version_mask"); + }; + assert_eq!(set.mask, HexU32Be(0x1fffe000)); +} + +#[test] +fn notification_encoding() { + assert_eq!( + to_json(SetDifficulty { difficulty: 2.0 }), + json!({"id": null, "method": "mining.set_difficulty", "params": [2.0]}) + ); + assert_eq!( + to_json(SetExtranonce { + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).unwrap(), + extranonce2_size: 4, + }), + json!({"id": null, "method": "mining.set_extranonce", "params": ["08000002", 4]}) + ); + assert_eq!( + to_json(SetVersionMask { + mask: HexU32Be(0x1fffe000) + }), + json!({"id": null, "method": "mining.set_version_mask", "params": ["1fffe000"]}) + ); + for notification in [ + ServerToClient::Notify(notify()), + ServerToClient::SetDifficulty(SetDifficulty { difficulty: 0.5 }), + ServerToClient::SetVersionMask(SetVersionMask { + mask: HexU32Be(0x1fffe000), + }), + ] { + let line = to_json(notification.clone()).to_string(); + assert_eq!(server_notification(&line), notification, "{line}"); + } +} + +#[test] +#[should_panic(expected = "finite and positive")] +fn set_difficulty_rejects_infinity() { + to_json(SetDifficulty { + difficulty: f64::INFINITY, + }); +} + +#[test] +#[should_panic(expected = "finite and positive")] +fn set_difficulty_rejects_zero() { + to_json(SetDifficulty { difficulty: 0.0 }); +} + +#[test] +fn subscribe_result_form() { + let line = r#"{"id":1,"result":[[["mining.set_difficulty","1"],["mining.notify","ae68"]],"08000002",4],"error":null}"#; + let result = subscribe_result(line); + assert_eq!( + result.subscriptions, + [ + ("mining.set_difficulty".to_string(), "1".to_string()), + ("mining.notify".to_string(), "ae68".to_string()), + ] + ); + assert_eq!(hex(result.extranonce1), "08000002"); + assert_eq!(result.extranonce2_size, 4); +} + +#[test] +fn odd_length_extranonce_forms() { + let line = r#"{"id":1,"result":[[],"abc",4],"error":null}"#; + let result = subscribe_result(line); + assert_eq!(hex(result.extranonce1), "0abc"); + + let line = r#"{"id":null,"method":"mining.set_extranonce","params":["abc",4]}"#; + let Message::Request(request) = decode(line) else { + panic!("not a request"); + }; + assert!(ServerToClient::try_from(request).is_err()); + let line = + r#"{"id":4,"method":"mining.submit","params":["w","bf","abc","647025b5","1d2e3f40"]}"#; + assert!(try_client_request(line).is_err()); +} + +#[test] +fn configure_result_forms() { + let cases = [ + ( + r#"{"id":7,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000"},"error":null}"#, + Some((true, 0x1fffe000, 0)), + None, + ), + ( + r#"{"id":7,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":"00000002","minimum-difficulty":false},"error":null}"#, + Some((true, 0x1fffe000, 2)), + Some(false), + ), + ( + r#"{"id":7,"result":{"version-rolling":true,"version-rolling.mask":"1fffe000","version-rolling.min-bit-count":2},"error":null}"#, + Some((true, 0x1fffe000, 2)), + None, + ), + ( + r#"{"id":7,"result":{"minimum-difficulty":true},"error":null}"#, + None, + Some(true), + ), + ]; + for (line, version_rolling, minimum_difficulty) in cases { + let result = configure_result(line); + assert_eq!( + result + .version_rolling + .map(|v| (v.enabled, v.mask.0, v.min_bit_count)), + version_rolling, + "{line}" + ); + assert_eq!(result.minimum_difficulty, minimum_difficulty, "{line}"); + } +} + +#[test] +fn boolean_result_form() { + for (line, expected) in [ + (r#"{"id":3,"result":true,"error":null}"#, true), + (r#"{"id":3,"result":false,"error":null}"#, false), + ] { + assert_eq!( + typed(line, Method::Authorize).unwrap(), + Some(ServerToClient::Authorize(Response::success( + Id::from(3u64), + expected + ))), + "{line}" + ); + } +} + +#[test] +fn server_response_encoding() { + assert_eq!( + to_json(Response::success( + Id::from(1u64), + SubscribeResult { + subscriptions: vec![("mining.notify".to_string(), "ae68".to_string())], + extranonce1: Extranonce::try_from(vec![8, 0, 0, 2]).unwrap(), + extranonce2_size: 4, + }, + )), + json!({"id": 1, "error": null, "result": [[["mining.notify", "ae68"]], "08000002", 4]}) + ); + + assert_eq!( + to_json(Response::success( + Id::from(7u64), + ConfigureResult { + version_rolling: Some(VersionRollingResult::new(HexU32Be(0xffffffff), 2)), + minimum_difficulty: Some(false), + }, + )), + json!({ + "id": 7, + "error": null, + "result": { + "version-rolling": true, + "version-rolling.mask": "1fffffe0", + "version-rolling.min-bit-count": "00000002", + "minimum-difficulty": false, + }, + }) + ); + + assert_eq!( + to_json(Response::success(Id::from(2u64), true)), + json!({"id": 2, "error": null, "result": true}) + ); + + assert_eq!( + to_json(SubmitOutcome::Accepted.into_response(Id::from(4u64))), + json!({"id": 4, "error": null, "result": true}) + ); + assert_eq!( + to_json( + SubmitOutcome::Rejected(SubmitError::LowDifficultyShare).into_response(Id::from("s4")) + ), + json!({"id": "s4", "error": [23, "Low difficulty share", null], "result": null}) + ); +} + +#[test] +fn submit_errors_round_trip_through_their_code() { + for error in [ + SubmitError::Other, + SubmitError::JobNotFound, + SubmitError::DuplicateShare, + SubmitError::LowDifficultyShare, + SubmitError::UnauthorizedWorker, + SubmitError::NotSubscribed, + ] { + let rpc_error = RpcError::from(error); + assert_eq!(rpc_error.message, error.message()); + assert_eq!(SubmitError::from_code(rpc_error.code), Some(error)); + } + assert_eq!(SubmitError::from_code(26), None); +} + +#[test] +fn offered_mask_is_clamped_whatever_the_result_holds() { + let result = ConfigureResult { + version_rolling: Some(VersionRollingResult { + enabled: true, + mask: HexU32Be(0xffffffff), + min_bit_count: 0, + }), + minimum_difficulty: None, + }; + let encoded = to_json(Response::success(Id::from(7u64), result)); + assert_eq!(encoded["result"]["version-rolling.mask"], "1fffffe0"); +} + +#[test] +fn configure_result_mask_is_clamped() { + let line = r#"{"id":7,"result":{"version-rolling":true,"version-rolling.mask":"ffffffff"},"error":null}"#; + let result = configure_result(line); + assert_eq!(result.version_rolling.unwrap().mask, HexU32Be(0x1fffffe0)); +} + +#[test] +fn raw_configure_hides_the_connection_url() { + let line = r#"{"id":7,"method":"mining.configure","params":[["info"],{"info.connection-url":"stratum+tcp://user:secret@pool.example","info.hw-version":"S19"}]}"#; + let message = decode(line); + for formatted in [message.to_string(), format!("{message:?}")] { + assert!(!formatted.contains("secret"), "{formatted}"); + assert!(formatted.contains("S19"), "{formatted}"); + } +} + +#[test] +fn peer_strings_are_escaped_in_display() { + let line = r#"{"id":1,"method":"evil\nmethod","params":["a\nb"]}"#; + let message = decode(line); + assert!(!message.to_string().contains('\n')); + let error = try_client_request(line).unwrap_err(); + assert!(!error.to_string().contains('\n')); + let line = r#"{"id":"x\ny","method":"mining.submit","params":[]}"#; + assert!(!try_client_request(line) + .unwrap_err() + .to_string() + .contains('\n')); +} + +#[test] +fn decode_errors_do_not_grow_with_the_message() { + let long = "m".repeat(1000); + let error = + try_client_request(&format!(r#"{{"id":"x","method":"{long}","params":[]}}"#)).unwrap_err(); + assert!(matches!(error.kind, DecodeErrorKind::UnknownMethod)); + assert_eq!(error.id, Some(Id::from("x"))); + assert_eq!(error.method, None); + assert!(error.to_string().len() < 200); + assert!(format!("{error:?}").len() < 200); +} + +#[test] +fn string_ids_are_at_most_64_bytes() { + let line = |id: &str| format!(r#"{{"id":"{id}","method":"mining.submit","params":[]}}"#); + let id = "i".repeat(64); + let error = try_client_request(&line(&id)).unwrap_err(); + assert_eq!(error.id, Some(Id::from(id.as_str()))); + + let error = Message::decode(&line(&"i".repeat(65))).unwrap_err(); + assert!(matches!(error.kind, DecodeErrorKind::InvalidEnvelope(_))); + assert_eq!(error.id, None); + assert!(format!("{error:?}").len() < 200); +} + +#[test] +fn extranonce2_size_fits_a_submit() { + for (size, accepted) in [(32, true), (33, false), (u64::MAX, false)] { + let line = format!( + r#"{{"id":null,"method":"mining.set_extranonce","params":["08000002",{size}]}}"# + ); + let Message::Request(request) = decode(&line) else { + panic!("not a request"); + }; + assert_eq!( + ServerToClient::try_from(request).is_ok(), + accepted, + "{line}" + ); + + let line = format!(r#"{{"id":1,"result":[[],"08000002",{size}],"error":null}}"#); + assert_eq!(typed(&line, Method::Subscribe).is_ok(), accepted, "{line}"); + } +} + +#[test] +fn merkle_branch_is_at_most_32_entries() { + let node = format!("\"{}\"", "00".repeat(32)); + for (entries, accepted) in [(32, true), (33, false)] { + let branch = vec![node.as_str(); entries].join(","); + let line = format!( + r#"{{"id":null,"method":"mining.notify","params":["bf","{prev}","01","02",[{branch}],"20000000","1705ae3a","647025b5",true]}}"#, + prev = "00".repeat(32) + ); + let Message::Request(request) = decode(&line) else { + panic!("not a request"); + }; + assert_eq!( + ServerToClient::try_from(request).is_ok(), + accepted, + "{entries} entries" + ); + } +} + +#[test] +fn set_difficulty_must_be_positive() { + for (difficulty, accepted) in [("2", true), ("0.001", true), ("0", false), ("-1", false)] { + let line = + format!(r#"{{"id":null,"method":"mining.set_difficulty","params":[{difficulty}]}}"#); + let Message::Request(request) = decode(&line) else { + panic!("not a request"); + }; + let decoded = ServerToClient::try_from(request); + assert_eq!(decoded.is_ok(), accepted, "{line}"); + if let Ok(notification) = decoded { + to_json(notification); + } + } +} + +#[test] +fn responses_are_typed_by_their_request_method() { + let line = r#"{"id":3,"result":true,"error":null}"#; + assert_eq!( + typed(line, Method::Authorize).unwrap(), + Some(ServerToClient::Authorize(Response::success( + Id::from(3u64), + true + ))) + ); + assert_eq!( + typed(line, Method::Submit).unwrap(), + Some(ServerToClient::Submit(Response::success( + Id::from(3u64), + true + ))) + ); + assert!(matches!( + typed(line, Method::Subscribe), + Err(Error::InvalidResult { id, method: Method::Subscribe, .. }) if id == Id::from(3u64) + )); + assert_eq!(typed(line, Method::SuggestDifficulty).unwrap(), None); + assert_eq!(typed(line, Method::Notify).unwrap(), None); + + let line = r#"{"id":4,"result":null,"error":[22,"Duplicate share",null]}"#; + assert_eq!( + typed(line, Method::Submit).unwrap(), + Some(ServerToClient::Submit(Response::failure( + Id::from(4u64), + SubmitError::DuplicateShare.into() + ))) + ); + + let line = r#"{"id":null,"result":true,"error":null}"#; + assert_eq!(typed(line, Method::Submit).unwrap(), None); +} + +#[test] +fn typed_responses_encode_like_their_wire_form() { + for line in [ + r#"{"id":1,"result":[[["mining.notify","ae68"]],"08000002",4],"error":null}"#, + r#"{"id":1,"result":true,"error":null}"#, + r#"{"id":"a","result":null,"error":[23,"Low difficulty share",null]}"#, + ] { + let method = if line.contains("ae68") { + Method::Subscribe + } else { + Method::Submit + }; + let typed = ServerToClient::from_response(&server_response(line), &method) + .unwrap() + .unwrap(); + assert_eq!(typed.method(), method, "{line}"); + assert_eq!( + to_json(typed), + serde_json::from_str::(line).unwrap(), + "{line}" + ); + } +}