From 2e340cd43fe0727bbd9c28effdec6b8e22da2ef3 Mon Sep 17 00:00:00 2001 From: GitGab19 Date: Thu, 16 Oct 2025 11:38:44 +0200 Subject: [PATCH 1/5] move `key-utils` and `error-handling` as modules of `stratum-apps` + adaptations --- .github/workflows/coverage-utils.yaml | 16 ----- .github/workflows/release-libs.yaml | 10 +--- .github/workflows/semver-check.yaml | 8 --- examples/ping-pong-encrypted/Cargo.toml | 1 - examples/ping-pong-encrypted/src/client.rs | 2 +- examples/ping-pong-encrypted/src/error.rs | 2 +- examples/ping-pong-encrypted/src/server.rs | 2 +- protocols/v2/codec-sv2/Cargo.toml | 2 +- roles/Cargo.lock | 30 ++-------- roles/jd-client/Cargo.toml | 1 - .../jd-client/src/lib/channel_manager/mod.rs | 2 +- roles/jd-client/src/lib/config.rs | 2 +- roles/jd-client/src/lib/job_declarator/mod.rs | 2 +- roles/jd-client/src/lib/mod.rs | 6 +- .../src/lib/template_receiver/mod.rs | 2 +- roles/jd-client/src/lib/upstream/mod.rs | 2 +- roles/jd-server/Cargo.toml | 2 - roles/jd-server/src/lib/config.rs | 6 +- roles/jd-server/src/lib/job_declarator/mod.rs | 4 +- roles/jd-server/src/lib/mod.rs | 12 ++-- roles/jd-server/src/lib/status.rs | 2 +- roles/pool/Cargo.toml | 2 - roles/pool/src/lib/channel_manager/mod.rs | 2 +- roles/pool/src/lib/config.rs | 2 +- roles/pool/src/lib/template_receiver/mod.rs | 2 +- roles/stratum-apps/Cargo.toml | 16 +++-- .../src/error_handling}/Cargo.toml | 0 .../stratum-apps/src/error_handling/mod.rs | 4 +- .../stratum-apps/src/key_utils/mod.rs | 0 roles/stratum-apps/src/lib.rs | 11 ++++ roles/test-utils/mining-device/Cargo.toml | 1 - roles/test-utils/mining-device/src/lib/mod.rs | 2 +- roles/test-utils/mining-device/src/main.rs | 2 +- roles/translator/Cargo.toml | 1 - roles/translator/src/lib/config.rs | 2 +- .../src/lib/sv1/sv1_server/sv1_server.rs | 2 +- .../src/lib/sv2/upstream/upstream.rs | 2 +- scripts/coverage-utils.sh | 2 - test/integration-tests/Cargo.lock | 31 ++-------- test/integration-tests/Cargo.toml | 1 - test/integration-tests/lib/mod.rs | 6 +- test/integration-tests/lib/utils.rs | 2 +- utils/Cargo.lock | 58 ------------------- utils/Cargo.toml | 2 - utils/key-utils/Cargo.toml | 38 ------------ utils/key-utils/README.md | 8 --- utils/key-utils/src/main.rs | 31 ---------- 47 files changed, 72 insertions(+), 274 deletions(-) rename {utils/error-handling => roles/stratum-apps/src/error_handling}/Cargo.toml (100%) rename utils/error-handling/src/lib.rs => roles/stratum-apps/src/error_handling/mod.rs (90%) rename utils/key-utils/src/lib.rs => roles/stratum-apps/src/key_utils/mod.rs (100%) delete mode 100644 utils/key-utils/Cargo.toml delete mode 100644 utils/key-utils/README.md delete mode 100644 utils/key-utils/src/main.rs diff --git a/.github/workflows/coverage-utils.yaml b/.github/workflows/coverage-utils.yaml index 6ff5e4f3a5..707d896ac0 100644 --- a/.github/workflows/coverage-utils.yaml +++ b/.github/workflows/coverage-utils.yaml @@ -45,19 +45,3 @@ jobs: flags: buffer_sv2-coverage token: ${{ secrets.CODECOV_TOKEN }} - - - name: Upload error_handling-coverage to codecov.io - uses: codecov/codecov-action@v4 - with: - directory: ./utils/target/tarpaulin-reports/error-handling-coverage - file: ./utils/target/tarpaulin-reports/error-handling-coverage/cobertura.xml - flags: error_handling-coverage - token: ${{ secrets.CODECOV_TOKEN }} - - - name: Upload key-utils-coverage to codecov.io - uses: codecov/codecov-action@v4 - with: - directory: ./utils/target/tarpaulin-reports/key-utils-coverage - file: ./utils/target/tarpaulin-reports/key-utils-coverage/cobertura.xml - flags: key-utils-coverage - token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/release-libs.yaml b/.github/workflows/release-libs.yaml index 6fc7d0d398..385e7ce8e9 100644 --- a/.github/workflows/release-libs.yaml +++ b/.github/workflows/release-libs.yaml @@ -34,14 +34,6 @@ jobs: run: | ./scripts/release-libs.sh utils/buffer - - name: Publish crate error-handling - run: | - ./scripts/release-libs.sh utils/error-handling - - - name: Publish crate key-utils - run: | - ./scripts/release-libs.sh utils/key-utils - - name: Publish crate noise_sv2 run: | ./scripts/release-libs.sh protocols/v2/noise-sv2 @@ -64,7 +56,7 @@ jobs: run: | ./scripts/release-libs.sh protocols/v2/framing-sv2 - # codec_sv2 (depends on framing_sv2, noise_sv2, binary_sv2, buffer_sv2, key-utils) + # codec_sv2 (depends on framing_sv2, noise_sv2, binary_sv2, buffer_sv2) - name: Publish crate codec_sv2 run: | ./scripts/release-libs.sh protocols/v2/codec-sv2 diff --git a/.github/workflows/semver-check.yaml b/.github/workflows/semver-check.yaml index 671e1852ce..9bccee1355 100644 --- a/.github/workflows/semver-check.yaml +++ b/.github/workflows/semver-check.yaml @@ -105,14 +105,6 @@ jobs: working-directory: utils/bip32-key-derivation run: cargo semver-checks - - name: Run semver checks for utils/error-handling - working-directory: utils/error-handling - run: cargo semver-checks - - - name: Run semver checks for utils/key-utils - working-directory: utils/key-utils - run: cargo semver-checks - - name: Run semver checks for protocols/stratum-translation working-directory: protocols/stratum-translation run: cargo semver-checks diff --git a/examples/ping-pong-encrypted/Cargo.toml b/examples/ping-pong-encrypted/Cargo.toml index 7a5220ec4c..a59daf9441 100644 --- a/examples/ping-pong-encrypted/Cargo.toml +++ b/examples/ping-pong-encrypted/Cargo.toml @@ -8,7 +8,6 @@ authors = [ "SRI Community" ] [dependencies] stratum-apps = { path = "../../roles/stratum-apps" } -key-utils = { version = "^1.0.0", path = "../../utils/key-utils" } rand = "0.8" tokio = { version = "1.44.1", features = [ "full" ] } async-channel = "1.5.1" diff --git a/examples/ping-pong-encrypted/src/client.rs b/examples/ping-pong-encrypted/src/client.rs index dbe9879a78..1fd3985513 100644 --- a/examples/ping-pong-encrypted/src/client.rs +++ b/examples/ping-pong-encrypted/src/client.rs @@ -1,6 +1,6 @@ use crate::messages::{Message, Ping, Pong, PING_MSG_TYPE, PONG_MSG_TYPE}; -use key_utils::Secp256k1PublicKey; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_connection::Connection, stratum_core::{ binary_sv2, diff --git a/examples/ping-pong-encrypted/src/error.rs b/examples/ping-pong-encrypted/src/error.rs index 0e0af61aa1..a9b5eb6982 100644 --- a/examples/ping-pong-encrypted/src/error.rs +++ b/examples/ping-pong-encrypted/src/error.rs @@ -1,5 +1,5 @@ use stratum_apps::{ - network_helpers, + key_utils, network_helpers, stratum_core::{binary_sv2, codec_sv2, framing_sv2, noise_sv2}, }; diff --git a/examples/ping-pong-encrypted/src/server.rs b/examples/ping-pong-encrypted/src/server.rs index cf023d170f..3dc8a1913e 100644 --- a/examples/ping-pong-encrypted/src/server.rs +++ b/examples/ping-pong-encrypted/src/server.rs @@ -2,8 +2,8 @@ use crate::{ error::Error, messages::{Message, Ping, Pong, PING_MSG_TYPE, PONG_MSG_TYPE}, }; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_connection::Connection, stratum_core::{ binary_sv2, diff --git a/protocols/v2/codec-sv2/Cargo.toml b/protocols/v2/codec-sv2/Cargo.toml index 80964f2205..11fbae3d4f 100644 --- a/protocols/v2/codec-sv2/Cargo.toml +++ b/protocols/v2/codec-sv2/Cargo.toml @@ -20,7 +20,7 @@ rand = { version = "0.8.5", default-features = false } tracing = { version = "0.1", optional = true } [dev-dependencies] -key-utils = { path = "../../../utils/key-utils", version = "^1.0.0" } +key-utils = { version = "1.2.0" } [features] default = ["std"] diff --git a/roles/Cargo.lock b/roles/Cargo.lock index cf7436e9ed..701b538161 100644 --- a/roles/Cargo.lock +++ b/roles/Cargo.lock @@ -1045,10 +1045,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - [[package]] name = "event-listener" version = "2.5.3" @@ -1648,7 +1644,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "key-utils", "serde", "stratum-apps", "tokio", @@ -1662,10 +1657,8 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "error_handling", "hashbrown 0.11.2", "hex", - "key-utils", "nohash-hasher", "rand", "serde", @@ -1703,18 +1696,6 @@ dependencies = [ "serde", ] -[[package]] -name = "key-utils" -version = "1.2.0" -dependencies = [ - "bs58", - "generic-array", - "rand", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - [[package]] name = "kv-log-macro" version = "1.0.7" @@ -1803,7 +1784,6 @@ dependencies = [ "criterion", "futures", "half", - "key-utils", "num-format", "num_cpus", "primitive-types", @@ -2170,8 +2150,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "error_handling", - "key-utils", "rand", "secp256k1 0.28.2", "serde", @@ -2633,16 +2611,19 @@ version = "0.1.0" dependencies = [ "async-channel 1.9.0", "base64 0.21.7", + "bs58", "clap", "config", - "error_handling", "futures", + "generic-array", "hex", "http-body-util", "hyper", "hyper-util", - "key-utils", "miniscript", + "rand", + "rustversion", + "secp256k1 0.28.2", "serde", "serde_json", "stratum-core", @@ -3014,7 +2995,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "key-utils", "serde", "serde_json", "sha2 0.10.9", diff --git a/roles/jd-client/Cargo.toml b/roles/jd-client/Cargo.toml index a01e02e6a3..46b41dedf5 100644 --- a/roles/jd-client/Cargo.toml +++ b/roles/jd-client/Cargo.toml @@ -17,7 +17,6 @@ path = "src/lib/mod.rs" [dependencies] stratum-apps = { path = "../stratum-apps", features = ["jd_client"] } -key-utils = { path = "../../utils/key-utils" } async-channel = "1.5.1" serde = { version = "1.0.89", default-features = false, features = ["derive", "alloc"] } tokio = { version = "1.44.1", features = ["full"] } diff --git a/roles/jd-client/src/lib/channel_manager/mod.rs b/roles/jd-client/src/lib/channel_manager/mod.rs index 21f6f5d0eb..096eac4e4b 100644 --- a/roles/jd-client/src/lib/channel_manager/mod.rs +++ b/roles/jd-client/src/lib/channel_manager/mod.rs @@ -8,8 +8,8 @@ use std::{ }; use async_channel::{Receiver, Sender}; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::{ diff --git a/roles/jd-client/src/lib/config.rs b/roles/jd-client/src/lib/config.rs index 5659e96a44..de72efb5be 100644 --- a/roles/jd-client/src/lib/config.rs +++ b/roles/jd-client/src/lib/config.rs @@ -1,4 +1,3 @@ -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use serde::Deserialize; use std::{ net::SocketAddr, @@ -7,6 +6,7 @@ use std::{ }; use stratum_apps::{ config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, stratum_core::bitcoin::{Amount, TxOut}, }; diff --git a/roles/jd-client/src/lib/job_declarator/mod.rs b/roles/jd-client/src/lib/job_declarator/mod.rs index bc45ef71ed..f1ccee52f0 100644 --- a/roles/jd-client/src/lib/job_declarator/mod.rs +++ b/roles/jd-client/src/lib/job_declarator/mod.rs @@ -1,8 +1,8 @@ use std::{net::SocketAddr, sync::Arc}; use async_channel::{unbounded, Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ codec_sv2::HandshakeRole, framing_sv2, handlers_sv2::HandleCommonMessagesFromServerAsync, diff --git a/roles/jd-client/src/lib/mod.rs b/roles/jd-client/src/lib/mod.rs index dfe6e8613c..d8140baaa0 100644 --- a/roles/jd-client/src/lib/mod.rs +++ b/roles/jd-client/src/lib/mod.rs @@ -1,8 +1,6 @@ -use std::{net::SocketAddr, sync::Arc, time::Duration}; - use async_channel::{unbounded, Receiver, Sender}; -use key_utils::Secp256k1PublicKey; -use stratum_apps::stratum_core::bitcoin::consensus::Encodable; +use std::{net::SocketAddr, sync::Arc, time::Duration}; +use stratum_apps::{key_utils::Secp256k1PublicKey, stratum_core::bitcoin::consensus::Encodable}; use tokio::sync::{broadcast, mpsc}; use tracing::{debug, info, warn}; diff --git a/roles/jd-client/src/lib/template_receiver/mod.rs b/roles/jd-client/src/lib/template_receiver/mod.rs index 68e8338708..eb0ed7d9f4 100644 --- a/roles/jd-client/src/lib/template_receiver/mod.rs +++ b/roles/jd-client/src/lib/template_receiver/mod.rs @@ -13,8 +13,8 @@ use std::{net::SocketAddr, sync::Arc}; use async_channel::{unbounded, Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ bitcoin::{ diff --git a/roles/jd-client/src/lib/upstream/mod.rs b/roles/jd-client/src/lib/upstream/mod.rs index 7601c7bbc0..b014a1d309 100644 --- a/roles/jd-client/src/lib/upstream/mod.rs +++ b/roles/jd-client/src/lib/upstream/mod.rs @@ -12,8 +12,8 @@ use std::{net::SocketAddr, sync::Arc}; use async_channel::{unbounded, Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ codec_sv2::HandshakeRole, framing_sv2, handlers_sv2::HandleCommonMessagesFromServerAsync, diff --git a/roles/jd-server/Cargo.toml b/roles/jd-server/Cargo.toml index 2b52d8c28d..102b6bb6f9 100644 --- a/roles/jd-server/Cargo.toml +++ b/roles/jd-server/Cargo.toml @@ -18,8 +18,6 @@ path = "src/lib/mod.rs" [dependencies] stratum-apps = { path = "../stratum-apps", features = ["jd_server"] } -error_handling = { path = "../../utils/error-handling" } -key-utils = { path = "../../utils/key-utils" } async-channel = "1.5.1" rand = "0.8.4" tokio = { version = "1.44.1", features = ["full"] } diff --git a/roles/jd-server/src/lib/config.rs b/roles/jd-server/src/lib/config.rs index e151f7b891..ee01a046ec 100644 --- a/roles/jd-server/src/lib/config.rs +++ b/roles/jd-server/src/lib/config.rs @@ -11,13 +11,15 @@ //! //! Also defines a helper struct [`CoreRpc`] to group RPC parameters. -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use serde::Deserialize; use std::{ path::{Path, PathBuf}, time::Duration, }; -use stratum_apps::config_helpers::CoinbaseRewardScript; +use stratum_apps::{ + config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, +}; #[derive(Debug, serde::Deserialize, Clone)] pub struct JobDeclaratorServerConfig { diff --git a/roles/jd-server/src/lib/job_declarator/mod.rs b/roles/jd-server/src/lib/job_declarator/mod.rs index 308c9cfc16..2e3cf18558 100644 --- a/roles/jd-server/src/lib/job_declarator/mod.rs +++ b/roles/jd-server/src/lib/job_declarator/mod.rs @@ -23,8 +23,6 @@ use super::{ }; use async_channel::{Receiver, Sender}; use core::panic; -use error_handling::handle_result; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; use nohash_hasher::BuildNoHashHasher; use std::{ collections::HashMap, @@ -32,6 +30,8 @@ use std::{ sync::{atomic::AtomicU32, Arc}, }; use stratum_apps::{ + handle_result, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}, network_helpers::noise_connection::Connection, stratum_core::{ binary_sv2::{self, B0255, U256}, diff --git a/roles/jd-server/src/lib/mod.rs b/roles/jd-server/src/lib/mod.rs index ca15ad47d0..3c04cdbf22 100644 --- a/roles/jd-server/src/lib/mod.rs +++ b/roles/jd-server/src/lib/mod.rs @@ -25,15 +25,17 @@ pub mod status; use async_channel::{bounded, unbounded, Receiver, Sender}; use config::JobDeclaratorServerConfig; use error::JdsError; -use error_handling::handle_result; use job_declarator::JobDeclarator; use mempool::error::JdsMempoolError; use std::{ops::Sub, str::FromStr, sync::Arc}; pub use stratum_apps::rpc::Uri; -use stratum_apps::stratum_core::{ - codec_sv2::{StandardEitherFrame, StandardSv2Frame}, - parsers_sv2::AnyMessage as JdsMessages, - roles_logic_sv2::utils::Mutex, +use stratum_apps::{ + handle_result, + stratum_core::{ + codec_sv2::{StandardEitherFrame, StandardSv2Frame}, + parsers_sv2::AnyMessage as JdsMessages, + roles_logic_sv2::utils::Mutex, + }, }; use tokio::{select, task}; use tracing::{error, info, warn}; diff --git a/roles/jd-server/src/lib/status.rs b/roles/jd-server/src/lib/status.rs index c982f9724f..ddf8d613a4 100644 --- a/roles/jd-server/src/lib/status.rs +++ b/roles/jd-server/src/lib/status.rs @@ -8,7 +8,7 @@ //! //! This allows for centralized, consistent error handling across the application. -use stratum_apps::stratum_core::parsers_sv2::Mining; +use stratum_apps::{error_handling, stratum_core::parsers_sv2::Mining}; use super::error::JdsError; diff --git a/roles/pool/Cargo.toml b/roles/pool/Cargo.toml index 22d2bb7342..921436edda 100644 --- a/roles/pool/Cargo.toml +++ b/roles/pool/Cargo.toml @@ -18,8 +18,6 @@ path = "src/lib/mod.rs" [dependencies] stratum-apps = { path = "../stratum-apps", features = ["pool"] } -error_handling = { path = "../../utils/error-handling" } -key-utils = { path = "../../utils/key-utils" } async-channel = "1.5.1" rand = "0.8.4" serde = { version = "1.0.89", features = ["derive", "alloc"], default-features = false } diff --git a/roles/pool/src/lib/channel_manager/mod.rs b/roles/pool/src/lib/channel_manager/mod.rs index 004982e113..e5d2d40c0d 100644 --- a/roles/pool/src/lib/channel_manager/mod.rs +++ b/roles/pool/src/lib/channel_manager/mod.rs @@ -6,9 +6,9 @@ use std::{ use async_channel::{Receiver, Sender}; use core::sync::atomic::Ordering; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::{ diff --git a/roles/pool/src/lib/config.rs b/roles/pool/src/lib/config.rs index 17b06d8c94..51e74317b4 100644 --- a/roles/pool/src/lib/config.rs +++ b/roles/pool/src/lib/config.rs @@ -13,9 +13,9 @@ use std::{ path::{Path, PathBuf}, }; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, stratum_core::bitcoin::{Amount, TxOut}, }; diff --git a/roles/pool/src/lib/template_receiver/mod.rs b/roles/pool/src/lib/template_receiver/mod.rs index 5d17a14da4..31697e7538 100644 --- a/roles/pool/src/lib/template_receiver/mod.rs +++ b/roles/pool/src/lib/template_receiver/mod.rs @@ -1,8 +1,8 @@ use std::{net::SocketAddr, sync::Arc}; mod common_message_handler; use async_channel::{unbounded, Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ bitcoin::{ diff --git a/roles/stratum-apps/Cargo.toml b/roles/stratum-apps/Cargo.toml index 35fbf09a4c..3cfe3fa778 100644 --- a/roles/stratum-apps/Cargo.toml +++ b/roles/stratum-apps/Cargo.toml @@ -15,10 +15,6 @@ keywords = ["stratum", "mining", "bitcoin", "protocol", "sv2"] # Core protocol layer stratum-core = { path = "../../stratum-core", version = "0.1.0" } -# Utilities from utils/ directory -key-utils = { path = "../../utils/key-utils", version = "1.2.0" } -error_handling = { path = "../../utils/error-handling", version = "1.0.0" } - # External dependencies needed by the modules # Network helpers dependencies async-channel = { version = "1.8.0" } @@ -32,7 +28,14 @@ miniscript = { version = "12.3.4", default-features = false, features = ["no-std tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing = { version = "0.1" } -# RPC dependencies +# Key utils dependencies +bs58 = { version = "0.4.0", default-features = false, features = ["check", "alloc"] } +secp256k1 = { version = "0.28.2", default-features = false, features = ["alloc", "rand"] } +rand = { version = "0.8.5", default-features = false } +rustversion = "1.0" +generic-array = "=0.14.7" + +# RPC optional dependencies serde_json = { version = "1.0", default-features = false, features = ["alloc", "raw_value"], optional = true } hex = { version = "0.4.3", optional = true } base64 = { version = "0.21.5", optional = true } @@ -45,12 +48,13 @@ clap = { version = "4.5.39", features = ["derive"] } ext-config = { version = "0.14.0", features = ["toml"], package = "config" } [features] -default = ["network", "config"] +default = ["network", "config", "std"] # Core module features network = ["tokio-util"] config = [] rpc = ["serde_json", "hex", "base64", "hyper", "hyper-util", "http-body-util"] +std = ["bs58/std", "secp256k1/rand-std", "rand/std", "rand/std_rng"] # Protocol features passed through to stratum-core sv1 = ["stratum-core/sv1", "stratum-core/translation", "tokio-util", "serde_json"] diff --git a/utils/error-handling/Cargo.toml b/roles/stratum-apps/src/error_handling/Cargo.toml similarity index 100% rename from utils/error-handling/Cargo.toml rename to roles/stratum-apps/src/error_handling/Cargo.toml diff --git a/utils/error-handling/src/lib.rs b/roles/stratum-apps/src/error_handling/mod.rs similarity index 90% rename from utils/error-handling/src/lib.rs rename to roles/stratum-apps/src/error_handling/mod.rs index 96214d78aa..17e24ce4d8 100644 --- a/utils/error-handling/src/lib.rs +++ b/roles/stratum-apps/src/error_handling/mod.rs @@ -29,8 +29,8 @@ macro_rules! handle_result { // handle error let res = crate::status::handle_error(&$sender, e.into()).await; match res { - error_handling::ErrorBranch::Break => break, - error_handling::ErrorBranch::Continue => continue, + $crate::error_handling::ErrorBranch::Break => break, + $crate::error_handling::ErrorBranch::Continue => continue, } } } diff --git a/utils/key-utils/src/lib.rs b/roles/stratum-apps/src/key_utils/mod.rs similarity index 100% rename from utils/key-utils/src/lib.rs rename to roles/stratum-apps/src/key_utils/mod.rs diff --git a/roles/stratum-apps/src/lib.rs b/roles/stratum-apps/src/lib.rs index 31da50e079..6a9060717c 100644 --- a/roles/stratum-apps/src/lib.rs +++ b/roles/stratum-apps/src/lib.rs @@ -47,3 +47,14 @@ pub mod config_helpers; /// Originally from the `rpc_sv2` crate. #[cfg(feature = "rpc")] pub mod rpc; + +/// Key utilities for cryptographic operations +/// +/// Provides Secp256k1 key management, serialization/deserialization, and signature services. +/// Supports both standard and no_std environments. +pub mod key_utils; + +/// Error handling utilities +/// +/// Provides the `handle_result!` macro and error handling logic for Stratum applications. +pub mod error_handling; diff --git a/roles/test-utils/mining-device/Cargo.toml b/roles/test-utils/mining-device/Cargo.toml index 1c01b1e89d..baa134d812 100644 --- a/roles/test-utils/mining-device/Cargo.toml +++ b/roles/test-utils/mining-device/Cargo.toml @@ -25,7 +25,6 @@ async-channel = "1.5.1" async-recursion = "0.3.2" rand = "0.8.4" futures = "0.3.5" -key-utils = { path = "../../../utils/key-utils" } clap = { version = "^4.5.4", features = ["derive"] } tracing = { version = "0.1" } tracing-subscriber = "0.3" diff --git a/roles/test-utils/mining-device/src/lib/mod.rs b/roles/test-utils/mining-device/src/lib/mod.rs index e407112af5..f6b4573890 100644 --- a/roles/test-utils/mining-device/src/lib/mod.rs +++ b/roles/test-utils/mining-device/src/lib/mod.rs @@ -1,6 +1,5 @@ #![allow(clippy::option_map_unit_fn)] use async_channel::{Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use num_format::{Locale, ToFormattedString}; use primitive_types::U256; use rand::{thread_rng, Rng}; @@ -14,6 +13,7 @@ use std::{ time::{Duration, Instant}, }; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_connection::Connection, stratum_core::{ bitcoin::{blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget}, diff --git a/roles/test-utils/mining-device/src/main.rs b/roles/test-utils/mining-device/src/main.rs index feb677b38f..be70942157 100644 --- a/roles/test-utils/mining-device/src/main.rs +++ b/roles/test-utils/mining-device/src/main.rs @@ -1,6 +1,6 @@ #![allow(special_module_name)] #![allow(clippy::option_map_unit_fn)] -use key_utils::Secp256k1PublicKey; +use stratum_apps::key_utils::Secp256k1PublicKey; use clap::Parser; use tracing::info; diff --git a/roles/translator/Cargo.toml b/roles/translator/Cargo.toml index 03f34a5d84..529f8ceae1 100644 --- a/roles/translator/Cargo.toml +++ b/roles/translator/Cargo.toml @@ -21,7 +21,6 @@ path = "src/main.rs" [dependencies] stratum-apps = { path = "../stratum-apps", features = ["translator"] } -key-utils = { path = "../../utils/key-utils" } async-channel = "1.5.1" serde = { version = "1.0.89", default-features = false, features = ["derive", "alloc"] } serde_json = { version = "1.0.64", default-features = false, features = ["alloc"] } diff --git a/roles/translator/src/lib/config.rs b/roles/translator/src/lib/config.rs index 0d6600330e..8094147f93 100644 --- a/roles/translator/src/lib/config.rs +++ b/roles/translator/src/lib/config.rs @@ -12,8 +12,8 @@ //! - Downstream difficulty adjustment parameters ([`DownstreamDifficultyConfig`]) use std::path::{Path, PathBuf}; -use key_utils::Secp256k1PublicKey; use serde::Deserialize; +use stratum_apps::key_utils::Secp256k1PublicKey; /// Configuration for the Translator. #[derive(Debug, Deserialize, Clone)] diff --git a/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs b/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs index 69f149ffeb..ba3ce943cf 100644 --- a/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs +++ b/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs @@ -838,8 +838,8 @@ mod tests { use super::*; use crate::config::{DownstreamDifficultyConfig, TranslatorConfig, Upstream}; use async_channel::unbounded; - use key_utils::Secp256k1PublicKey; use std::{collections::HashMap, str::FromStr}; + use stratum_apps::key_utils::Secp256k1PublicKey; fn create_test_config() -> TranslatorConfig { let pubkey_str = "9bDuixKmZqAJnrmP746n8zU1wyAQRrus7th9dxnkPg6RzQvCnan"; diff --git a/roles/translator/src/lib/sv2/upstream/upstream.rs b/roles/translator/src/lib/sv2/upstream/upstream.rs index b3a4168f93..8fa2bf0d25 100644 --- a/roles/translator/src/lib/sv2/upstream/upstream.rs +++ b/roles/translator/src/lib/sv2/upstream/upstream.rs @@ -6,9 +6,9 @@ use crate::{ utils::{message_from_frame, ShutdownMessage}, }; use async_channel::{Receiver, Sender}; -use key_utils::Secp256k1PublicKey; use std::{net::SocketAddr, sync::Arc}; use stratum_apps::{ + key_utils::Secp256k1PublicKey, network_helpers::noise_connection::Connection, stratum_core::{ buffer_sv2, diff --git a/scripts/coverage-utils.sh b/scripts/coverage-utils.sh index 6f32742984..6f26878558 100755 --- a/scripts/coverage-utils.sh +++ b/scripts/coverage-utils.sh @@ -12,8 +12,6 @@ tarpaulin crates=( "buffer" - "error-handling" - "key-utils" "bip32-key-derivation" ) diff --git a/test/integration-tests/Cargo.lock b/test/integration-tests/Cargo.lock index 5c7df5db8f..7d8641a019 100644 --- a/test/integration-tests/Cargo.lock +++ b/test/integration-tests/Cargo.lock @@ -787,10 +787,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - [[package]] name = "event-listener" version = "2.5.3" @@ -1254,7 +1250,6 @@ dependencies = [ "flate2", "jd_client_sv2", "jd_server", - "key-utils", "mining_device", "minreq", "once_cell", @@ -1305,7 +1300,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils", "serde", "stratum-apps", "tokio", @@ -1319,10 +1313,8 @@ dependencies = [ "async-channel", "clap", "config", - "error_handling", "hashbrown 0.11.2", "hex", - "key-utils", "nohash-hasher", "rand 0.8.5", "serde", @@ -1362,18 +1354,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "key-utils" -version = "1.2.0" -dependencies = [ - "bs58", - "generic-array", - "rand 0.8.5", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -1447,7 +1427,6 @@ dependencies = [ "async-recursion", "clap", "futures", - "key-utils", "num-format", "primitive-types", "rand 0.8.5", @@ -1757,8 +1736,6 @@ dependencies = [ "async-channel", "clap", "config", - "error_handling", - "key-utils", "rand 0.8.5", "secp256k1 0.28.2", "serde", @@ -2233,16 +2210,19 @@ version = "0.1.0" dependencies = [ "async-channel", "base64 0.21.7", + "bs58", "clap", "config", - "error_handling", "futures", + "generic-array", "hex", "http-body-util", "hyper", "hyper-util", - "key-utils", "miniscript", + "rand 0.8.5", + "rustversion", + "secp256k1 0.28.2", "serde", "serde_json", "stratum-core", @@ -2627,7 +2607,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils", "serde", "serde_json", "stratum-apps", diff --git a/test/integration-tests/Cargo.toml b/test/integration-tests/Cargo.toml index 9c066267b6..42f66452b0 100644 --- a/test/integration-tests/Cargo.toml +++ b/test/integration-tests/Cargo.toml @@ -12,7 +12,6 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"] [dependencies] stratum-apps = { path = "../../roles/stratum-apps", features = ["network", "config"] } -key-utils = { path = "../../utils/key-utils" } jd_client_sv2 = { path = "../../roles/jd-client" } jd_server = { path = "../../roles/jd-server" } mining_device = { path = "../../roles/test-utils/mining-device" } diff --git a/test/integration-tests/lib/mod.rs b/test/integration-tests/lib/mod.rs index 048e15b246..a93b836a47 100644 --- a/test/integration-tests/lib/mod.rs +++ b/test/integration-tests/lib/mod.rs @@ -3,7 +3,6 @@ use corepc_node::{ConnectParams, CookieValues}; use interceptor::InterceptAction; use jd_client_sv2::JobDeclaratorClient; use jd_server::JobDeclaratorServer; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use once_cell::sync::OnceCell; use pool_sv2::PoolSv2; use std::{ @@ -11,7 +10,10 @@ use std::{ net::{Ipv4Addr, SocketAddr}, time::Duration, }; -use stratum_apps::config_helpers::CoinbaseRewardScript; +use stratum_apps::{ + config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, +}; use tracing::Level; use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; use translator_sv2::TranslatorSv2; diff --git a/test/integration-tests/lib/utils.rs b/test/integration-tests/lib/utils.rs index bf8929ca81..0c7c8575b8 100644 --- a/test/integration-tests/lib/utils.rs +++ b/test/integration-tests/lib/utils.rs @@ -5,7 +5,6 @@ use crate::{ types::{MessageFrame, MsgType}, }; use async_channel::{Receiver, Sender}; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use once_cell::sync::Lazy; use std::{ collections::HashSet, @@ -14,6 +13,7 @@ use std::{ sync::Mutex, }; use stratum_apps::{ + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_connection::Connection, stratum_core::{ codec_sv2::{HandshakeRole, StandardEitherFrame}, diff --git a/utils/Cargo.lock b/utils/Cargo.lock index 3f57d35972..4c12cd360d 100644 --- a/utils/Cargo.lock +++ b/utils/Cargo.lock @@ -196,24 +196,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bs58" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" -dependencies = [ - "sha2", -] - [[package]] name = "buffer_sv2" version = "2.0.0" @@ -488,15 +470,6 @@ dependencies = [ "binary_codec_sv2", ] -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - [[package]] name = "either" version = "1.15.0" @@ -509,10 +482,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" -[[package]] -name = "error_handling" -version = "1.0.0" - [[package]] name = "find-msvc-tools" version = "0.1.4" @@ -734,19 +703,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "key-utils" -version = "1.2.0" -dependencies = [ - "bs58", - "generic-array", - "rand", - "rustversion", - "secp256k1 0.28.2", - "serde", - "toml", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -1146,7 +1102,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", - "serde_derive", ] [[package]] @@ -1192,19 +1147,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer", - "cfg-if", - "cpufeatures", - "digest", - "opaque-debug", -] - [[package]] name = "shlex" version = "1.3.0" diff --git a/utils/Cargo.toml b/utils/Cargo.toml index c199c38f4f..e83a4f5844 100644 --- a/utils/Cargo.toml +++ b/utils/Cargo.toml @@ -3,8 +3,6 @@ resolver="2" members = [ "buffer", - "error-handling", - "key-utils", "bip32-key-derivation", ] diff --git a/utils/key-utils/Cargo.toml b/utils/key-utils/Cargo.toml deleted file mode 100644 index d468e5a87b..0000000000 --- a/utils/key-utils/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "key-utils" -version = "1.2.0" -authors = ["The Stratum V2 Developers"] -edition = "2021" -description = "Key utils" -documentation = "https://docs.rs/key-utils" -readme = "README.md" -homepage = "https://stratumprotocol.org" -repository = "https://github.com/stratum-mining/stratum" -license = "MIT OR Apache-2.0" -keywords = ["stratum", "mining", "bitcoin", "protocol"] - - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -name = "key_utils" -path = "src/lib.rs" - -[[bin]] -name = "key-utils-bin" -path = "src/main.rs" - -[dependencies] -bs58 = { version ="0.4.0", default-features = false, features = ["check", "alloc"] } -secp256k1 = { version = "0.28.2", default-features = false, features =["alloc","rand"] } -serde = { version = "1.0.89", features = ["derive","alloc"], default-features = false } -rand = {version = "0.8.5", default-features = false } -rustversion = "1.0" -generic-array = "=0.14.7" - -[dev-dependencies] -toml = { version = "0.5.6", git = "https://github.com/diondokter/toml-rs", default-features = false, rev = "c4161aa" } - -[features] -default = ["std"] -std = ["bs58/std","secp256k1/rand-std", "rand/std", "rand/std_rng"] diff --git a/utils/key-utils/README.md b/utils/key-utils/README.md deleted file mode 100644 index 8202396ce9..0000000000 --- a/utils/key-utils/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Key utils - -## Binary -It can be used as binary to a random pair of base58 encoded secp256k1 keys: `cargo run` - -## Library -It can be imported by other applications that need to serialize and deserialize secp256k1 keys. - diff --git a/utils/key-utils/src/main.rs b/utils/key-utils/src/main.rs deleted file mode 100644 index 35a12ccce9..0000000000 --- a/utils/key-utils/src/main.rs +++ /dev/null @@ -1,31 +0,0 @@ -#[cfg(feature = "std")] -use ::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; -#[cfg(feature = "std")] -use secp256k1::{rand, Keypair, Secp256k1}; - -#[cfg(feature = "std")] -fn generate_key() -> (Secp256k1SecretKey, Secp256k1PublicKey) { - let secp = Secp256k1::new(); - let (secret_key, _) = secp.generate_keypair(&mut rand::thread_rng()); - let kp = Keypair::from_secret_key(&secp, &secret_key); - if kp.x_only_public_key().1 == secp256k1::Parity::Even { - ( - Secp256k1SecretKey(kp.secret_key()), - Secp256k1PublicKey(kp.x_only_public_key().0), - ) - } else { - generate_key() - } -} - -#[cfg(feature = "std")] -fn main() { - let (secret, public) = generate_key(); - let secret: String = secret.into(); - let public: String = public.into(); - println!("Secret Key: {secret}"); - println!("Public Key: {public}"); -} - -#[cfg(not(feature = "std"))] -fn main() {} From efc78bf214931e4afa47ebea1f85b0367ed69c60 Mon Sep 17 00:00:00 2001 From: GitGab19 Date: Thu, 16 Oct 2025 12:06:55 +0200 Subject: [PATCH 2/5] remove `roles_logic_sv2` from cargo semver-checks --- .github/workflows/semver-check.yaml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/semver-check.yaml b/.github/workflows/semver-check.yaml index 9bccee1355..d610f24665 100644 --- a/.github/workflows/semver-check.yaml +++ b/.github/workflows/semver-check.yaml @@ -81,10 +81,6 @@ jobs: working-directory: protocols/v2/subprotocols/template-distribution run: cargo semver-checks - - name: Run semver checks for protocols/v2/roles-logic-sv2 - working-directory: protocols/v2/roles-logic-sv2 - run: cargo semver-checks --default-features - - name: Run semver checks for protocols/v2/channels-sv2 working-directory: protocols/v2/channels-sv2 run: cargo semver-checks From 344cb12e5edb2a354944ee55797c8d90613261b9 Mon Sep 17 00:00:00 2001 From: GitGab19 Date: Wed, 15 Oct 2025 19:36:21 +0200 Subject: [PATCH 3/5] drop `roles_logic_sv2` and adapt JDS + mining_device to use published crates instead of stratum-apps --- .github/workflows/docs.yaml | 6 - protocols/v2/roles-logic-sv2/Cargo.toml | 43 -- protocols/v2/roles-logic-sv2/README.md | 31 -- .../v2/roles-logic-sv2/reg-test-block.toml | 14 - protocols/v2/roles-logic-sv2/src/errors.rs | 274 ---------- .../v2/roles-logic-sv2/src/handlers/common.rs | 163 ------ .../src/handlers/job_declaration.rs | 211 -------- .../v2/roles-logic-sv2/src/handlers/mining.rs | 475 ------------------ .../v2/roles-logic-sv2/src/handlers/mod.rs | 85 ---- .../src/handlers/template_distribution.rs | 203 -------- protocols/v2/roles-logic-sv2/src/lib.rs | 23 - protocols/v2/roles-logic-sv2/src/utils.rs | 115 ----- roles/Cargo.lock | 423 +++++++++++++--- roles/jd-server/Cargo.toml | 17 +- roles/jd-server/src/lib/config.rs | 10 +- roles/jd-server/src/lib/error.rs | 9 +- .../src/lib/job_declarator/message_handler.rs | 39 +- roles/jd-server/src/lib/job_declarator/mod.rs | 48 +- roles/jd-server/src/lib/mempool/error.rs | 2 +- roles/jd-server/src/lib/mempool/mod.rs | 14 +- roles/jd-server/src/lib/mod.rs | 13 +- roles/jd-server/src/lib/status.rs | 24 +- roles/jd-server/src/main.rs | 2 +- roles/test-utils/mining-device/Cargo.toml | 18 +- .../mining-device/benches/hasher_bench.rs | 6 +- .../mining-device/benches/microbatch_bench.rs | 6 +- .../mining-device/benches/scaling_bench.rs | 6 +- roles/test-utils/mining-device/src/lib/mod.rs | 71 ++- .../tests/fast_hasher_equivalence.rs | 6 +- stratum-core/Cargo.toml | 4 +- stratum-core/src/lib.rs | 2 +- test/integration-tests/Cargo.lock | 431 +++++++++++++--- utils/Cargo.lock | 42 -- 33 files changed, 877 insertions(+), 1959 deletions(-) delete mode 100644 protocols/v2/roles-logic-sv2/Cargo.toml delete mode 100644 protocols/v2/roles-logic-sv2/README.md delete mode 100644 protocols/v2/roles-logic-sv2/reg-test-block.toml delete mode 100644 protocols/v2/roles-logic-sv2/src/errors.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/handlers/common.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/handlers/mining.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/handlers/mod.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/lib.rs delete mode 100644 protocols/v2/roles-logic-sv2/src/utils.rs diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 52b97603f5..289d8ebadb 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -94,12 +94,6 @@ jobs: cd protocols/v2/subprotocols/template-distribution cargo doc - - name: Rust Docs crate roles_logic_sv2 - - run: | - cd protocols/v2/roles-logic-sv2 - cargo doc - - name: Rust Docs crate sv1_api run: | cd protocols/v1 diff --git a/protocols/v2/roles-logic-sv2/Cargo.toml b/protocols/v2/roles-logic-sv2/Cargo.toml deleted file mode 100644 index 96b96ab2bc..0000000000 --- a/protocols/v2/roles-logic-sv2/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -[package] -name = "roles_logic_sv2" -version = "5.0.0" -authors = ["The Stratum V2 Developers"] -edition = "2021" -description = "Common handlers for use within SV2 roles" -documentation = "https://docs.rs/roles_logic_sv2" -license = "MIT OR Apache-2.0" -repository = "https://github.com/stratum-mining/stratum" -homepage = "https://stratumprotocol.org" -keywords = ["stratum", "mining", "bitcoin", "protocol"] - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -bitcoin = { version = "0.32.5" } -binary_sv2 = { path = "../binary-sv2", version = "^4.0.0" } -channels_sv2 = { path = "../channels-sv2", version = "^2.0.0" } -parsers_sv2 = { path = "../parsers-sv2", version = "^0.1.0" } -handlers_sv2 = { path = "../handlers-sv2", version = "^0.2.0" } -common_messages_sv2 = { path = "../../../protocols/v2/subprotocols/common-messages", version = "^6.0.0" } -mining_sv2 = { path = "../../../protocols/v2/subprotocols/mining", version = "^5.0.0" } -template_distribution_sv2 = { path = "../../../protocols/v2/subprotocols/template-distribution", version = "^4.0.0" } -job_declaration_sv2 = { path = "../../../protocols/v2/subprotocols/job-declaration", version = "^5.0.0" } -tracing = { version = "0.1"} -chacha20poly1305 = { version = "0.10.1"} -nohash-hasher = "0.2.0" -primitive-types = "0.13.1" -hex = {package = "hex-conservative", version = "0.3.0"} -codec_sv2 = { path = "../../../protocols/v2/codec-sv2", version = "^4.0.0", features = ["noise_sv2", "with_buffer_pool"] } - -[dev-dependencies] -quickcheck = "1.0.3" -quickcheck_macros = "1" -rand = "0.8.5" -toml = {git = "https://github.com/diondokter/toml-rs", default-features = false, rev="c4161aa"} -serde = { version = "1.0.89", features = ["derive", "alloc"], default-features = false} -tracing-subscriber = "0.3" - -[features] -prop_test = ["template_distribution_sv2/prop_test"] -# Code coverage tools may conflict with the nopanic logic, so we can disable it when needed -disable_nopanic = [] diff --git a/protocols/v2/roles-logic-sv2/README.md b/protocols/v2/roles-logic-sv2/README.md deleted file mode 100644 index 1aed76225c..0000000000 --- a/protocols/v2/roles-logic-sv2/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# `roles_logic_sv2` - -[![crates.io](https://img.shields.io/crates/v/roles_logic_sv2.svg)](https://crates.io/crates/roles_logic_sv2) -[![docs.rs](https://docs.rs/roles_logic_sv2/badge.svg)](https://docs.rs/roles_logic_sv2) -[![rustc+](https://img.shields.io/badge/rustc-1.75.0%2B-lightgrey.svg)](https://blog.rust-lang.org/2023/12/28/Rust-1.75.0.html) -[![license](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](https://github.com/stratum-mining/stratum/blob/main/LICENSE.md) -[![codecov](https://codecov.io/gh/stratum-mining/stratum/branch/main/graph/badge.svg?flag=roles_logic_sv2-coverage)](https://codecov.io/gh/stratum-mining/stratum) - -`roles_logic_sv2` provides the core logic and utilities for implementing roles in the Stratum V2 (Sv2) protocol, such as miners, pools, and proxies. It abstracts message handling, channel management, job creation, and routing logic, enabling efficient and secure communication across upstream and downstream connections. - -## Main Components - -- **Channel Logic**: Manages the lifecycle and settings of communication channels (standard, extended, and group ones) between roles. -- **Handlers**: Provides traits for handling logic of Sv2 protocol messages. -- **Job Management**: Facilitates the creation, validation, and dispatching of mining jobs. -- **Parsers**: Handles serialization and deserialization of Sv2 messages via [`binary_sv2`](https://docs.rs/binary_sv2/latest/binary_sv2/index.html). -- **Routing Logic**: Implements message routing and downstream/upstream selector utilities. Useful for advanced proxy implementations with multiplexing of Standard Channels across different upstreams. -- **Utilities**: Provides helpers for safe mutex locking, mining-specific calculations, and more. - -## Usage - -To include this crate in your project, run: - -```bash -cargo add roles_logic_sv2 -``` - -This crate can be built with the following feature flags: - -- `prop_test`: Enables property-based testing features for template distribution logic, leveraging dependencies' testing capabilities such as `template_distribution_sv2` crate. -- `disable_nopanic`: Disables the nopanic logic in scenarios where code coverage tools might conflict with it. \ No newline at end of file diff --git a/protocols/v2/roles-logic-sv2/reg-test-block.toml b/protocols/v2/roles-logic-sv2/reg-test-block.toml deleted file mode 100644 index 016304e8e9..0000000000 --- a/protocols/v2/roles-logic-sv2/reg-test-block.toml +++ /dev/null @@ -1,14 +0,0 @@ -# Block with 1 transaction (not including the cb tx) generated using regtest -block_hash = "59202ef47d684ab51866e91d5f40e61a94787d02d899fc3da28e4f4bcb8fd0a4" - -version = 0x20000000 # LE -prev_hash = "74f34a78cf87740b67fa545734ce7ea86e917e53001c3bd6eaf5d32f5d89264d" # BE -merkle_root = "3a158fb4278f27d01cafcac465ba1c5b8f3461687681465f6734649f2cb8d5a7" #BE -nbits = 0x207fffff # BE -time = 0x6238b86a # BE -nonce = 0x00000001 # BE - -coinbase_tx_prefix = "02000000010000000000000000000000000000000000000000000000000000000000000000ffffffff040172" -coinbase_script = "0101" -coinbase_tx_suffix = "ffffffff02d0751b2a010000001600146e556b6f3ad312726bc501da9656ac1329a84d040000000000000000266a24aa21a9edd8b6a6c9c32ffe19d40f1109b33186c59d580c7e7d591194df4e57b05ef9824100000000" -path = ["55f88d00edeeca6cdb853624a34500e076394abd35fc39bf9a3a9865f0540731"] \ No newline at end of file diff --git a/protocols/v2/roles-logic-sv2/src/errors.rs b/protocols/v2/roles-logic-sv2/src/errors.rs deleted file mode 100644 index d58da2dc3c..0000000000 --- a/protocols/v2/roles-logic-sv2/src/errors.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! # Error Handling -//! -//! This module defines error types and utilities for handling errors in the `roles_logic_sv2` -//! module. It includes the [`Error`] enum for representing various errors. - -use binary_sv2::Error as BinarySv2Error; -use bitcoin::hashes::FromSliceError; -use channels_sv2::{ - server::error::{ExtendedChannelError, GroupChannelError, StandardChannelError}, - target::InputError, - vardiff::error::VardiffError, -}; -use mining_sv2::ExtendedExtranonceError; -use parsers_sv2::AnyMessage as AllMessages; -use std::{ - fmt::{self, Display, Formatter}, - sync::{MutexGuard, PoisonError}, -}; - -/// Error enum -#[derive(Debug)] -pub enum Error { - /// Payload size is too big to fit into a frame - BadPayloadSize, - /// Expected Length of 32, but received different length - ExpectedLen32(usize), - /// Error serializing/deserializing binary format - BinarySv2Error(BinarySv2Error), - /// Downstream is not connected anymore - DownstreamDown, - /// A channel was attempted to be added to an Upstream, but no groups are specified - NoGroupsFound, - /// Unexpected message received. - UnexpectedMessage(u8), - /// Extended channels do not have group IDs - NoGroupIdOnExtendedChannel, - /// No pairable upstream. Parameters are: (`min_v`, `max_v`, all flags supported) - NoPairableUpstream((u16, u16, u32)), - /// Error if the hashmap `future_jobs` field in the `GroupChannelJobDispatcher` is empty. - NoFutureJobs, - /// No Downstream's connected - NoDownstreamsConnected, - /// PrevHash requires non-existent Job Id - PrevHashRequireNonExistentJobId(u32), - /// Request Id not mapped - RequestIdNotMapped(u32), - /// There are no upstream connected - NoUpstreamsConnected, - /// Protocol has not been implemented, but should be - UnimplementedProtocol, - /// Unexpected `PoolMessage` type - UnexpectedPoolMessage, - /// Upstream is answering with a wrong request ID {} or - /// `DownstreamMiningSelector::on_open_standard_channel_request` has not been called - /// before relaying open channel request to upstream - UnknownRequestId(u32), - /// No more extranonces - NoMoreExtranonces, - /// A non future job always expect a previous new prev hash - JobIsNotFutureButPrevHashNotPresent, - /// If a channel is neither extended or part of a pool, - /// the only thing to do when a OpenStandardChannel is received - /// is to relay it upstream with and updated request id - ChannelIsNeitherExtendedNeitherInAPool, - /// No more available extranonces for downstream" - ExtranonceSpaceEnded, - /// Impossible to calculate merkle root - ImpossibleToCalculateMerkleRoot, - /// Group Id not found - GroupIdNotFound, - /// A share has been received but no job for it exist - ShareDoNotMatchAnyJob, - /// A share has been received but no channel for it exist - ShareDoNotMatchAnyChannel, - /// Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase - InvalidCoinbase, - /// Value remaining in coinbase output was not correctly updated (it's equal to 0) - ValueRemainingNotUpdated, - /// Block header version cannot be bigger than `i32::MAX` - VersionTooBig, - /// Tx version cannot be bigger than `i32::MAX` - TxVersionTooBig, - /// Tx version cannot be lower than 1 - TxVersionTooLow, - /// Impossible to decode tx - TxDecodingError(String), - /// No downstream has been registered for this channel id - NotFoundChannelId, - /// Impossible to create a standard job for channel - /// because no valid job has been received from upstream yet - NoValidJob, - /// Impossible to create an extended job for channel - /// because no valid job has been received from upstream yet - NoValidTranslatorJob, - /// Impossible to retrieve a template for the required job id - NoTemplateForId, - /// Impossible to retrieve a template for the required template id - NoValidTemplate(String), - /// Invalid extranonce size. Params: (required min, requested) - InvalidExtranonceSize(u16, u16), - /// Failed to create ExtendedExtranonce. Param: (error message) - ExtendedExtranonceCreationFailed(String), - /// Poison Lock - PoisonLock(String), - /// Channel Factory did not update job. Params: (downstream_job_id, upstream_job_id) - JobNotUpdated(u32, u32), - /// Impossible to get Target - TargetError(InputError), - /// Impossible to get Hashrate - HashrateError(InputError), - /// Message is well formatted but can not be handled - LogicErrorMessage(std::boxed::Box>), - /// JD server cannot propagate the block due to missing transactions - JDSMissingTransactions, - IoError(std::io::Error), - FromSliceError(FromSliceError), - /// Invalid user identity - InvalidUserIdentity(String), - ExtranoncePrefixFactoryError(ExtendedExtranonceError), - FailedToCreateStandardChannel(StandardChannelError), - Vardiff(VardiffError), - FailedToCreateExtendedChannel(ExtendedChannelError), - FailedToUpdateStandardChannel(StandardChannelError), - FailedToUpdateExtendedChannel(ExtendedChannelError), - FailedToProcessNewTemplateGroupChannel(GroupChannelError), - FailedToProcessSetNewPrevHashGroupChannel(GroupChannelError), - FailedToProcessNewTemplateExtendedChannel(ExtendedChannelError), - FailedToProcessNewTemplateStandardChannel(StandardChannelError), - FailedToProcessSetNewPrevHashExtendedChannel(ExtendedChannelError), - FailedToProcessSetNewPrevHashStandardChannel(StandardChannelError), - FailedToProcessGroupChannelJob(StandardChannelError), - NoActiveJob, - FailedToSendSolution, - FailedToSetCustomMiningJob(ExtendedChannelError), - FailedToDeserializeCoinbaseOutputs, - /// Error from parsers_sv2 - ParserError(parsers_sv2::ParserError), -} - -impl From for Error { - fn from(v: BinarySv2Error) -> Error { - Error::BinarySv2Error(v) - } -} - -impl From for Error { - fn from(v: std::io::Error) -> Error { - Error::IoError(v) - } -} - -impl From for Error { - fn from(v: FromSliceError) -> Error { - Error::FromSliceError(v) - } -} - -impl From for Error { - fn from(value: VardiffError) -> Self { - Error::Vardiff(value) - } -} - -impl From for Error { - fn from(v: parsers_sv2::ParserError) -> Error { - Error::ParserError(v) - } -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - use Error::*; - match self { - BadPayloadSize => write!(f, "Payload is too big to fit into the frame"), - BinarySv2Error(v) => write!( - f, - "BinarySv2Error: error in serializing/deserializing binary format {v:?}" - ), - DownstreamDown => { - write!( - f, - "Downstream is not connected anymore" - ) - } - ExpectedLen32(l) => write!(f, "Expected length of 32, but received length of {l}"), - NoGroupsFound => write!( - f, - "A channel was attempted to be added to an Upstream, but no groups are specified" - ), - UnexpectedMessage(type_) => write!(f, "Error: Unexpected message received. Recv m type: {type_:x}"), - NoGroupIdOnExtendedChannel => write!(f, "Extended channels do not have group IDs"), - NoPairableUpstream(a) => { - write!(f, "No pairable upstream node: {a:?}") - } - NoFutureJobs => write!(f, "GroupChannelJobDispatcher does not have any future jobs"), - NoDownstreamsConnected => write!(f, "NoDownstreamsConnected"), - PrevHashRequireNonExistentJobId(id) => { - write!(f, "PrevHashRequireNonExistentJobId {id}") - } - RequestIdNotMapped(id) => write!(f, "RequestIdNotMapped {id}"), - NoUpstreamsConnected => write!(f, "There are no upstream connected"), - UnexpectedPoolMessage => write!(f, "Unexpected `PoolMessage` type"), - UnimplementedProtocol => write!( - f, - "TODO: `Protocol` has not been implemented, but should be" - ), - UnknownRequestId(id) => write!( - f, - "Upstream is answering with a wrong request ID {id} or - DownstreamMiningSelector::on_open_standard_channel_request has not been called - before relaying open channel request to upstream" - ), - InvalidExtranonceSize(required_min, requested) => { - write!( - f, - "Invalid extranonce size: required min {required_min}, requested {requested}" - ) - }, - NoMoreExtranonces => write!(f, "No more extranonces"), - JobIsNotFutureButPrevHashNotPresent => write!(f, "A non future job always expect a previous new prev hash"), - ChannelIsNeitherExtendedNeitherInAPool => write!(f, "If a channel is neither extended neither is part of a pool the only thing to do when a OpenStandardChannel is received is to relay it upstream with and updated request id"), - ExtranonceSpaceEnded => write!(f, "No more available extranonces for downstream"), - ImpossibleToCalculateMerkleRoot => write!(f, "Impossible to calculate merkle root"), - GroupIdNotFound => write!(f, "Group id not found"), - ShareDoNotMatchAnyJob => write!(f, "A share has been received but no job for it exist"), - ShareDoNotMatchAnyChannel => write!(f, "A share has been received but no channel for it exist"), - InvalidCoinbase => write!(f, "Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase"), - ValueRemainingNotUpdated => write!(f, "Value remaining in coinbase output was not correctly updated (it's equal to 0)"), - VersionTooBig => write!(f, "We are trying to construct a block header with version bigger than i32::MAX"), - TxVersionTooBig => write!(f, "Tx version can not be greater than i32::MAX"), - TxVersionTooLow => write!(f, "Tx version can not be lower than 1"), - TxDecodingError(e) => write!(f, "Impossible to decode tx: {e:?}"), - NotFoundChannelId => write!(f, "No downstream has been registered for this channel id"), - NoValidJob => write!(f, "Impossible to create a standard job for channelA cause no valid job has been received from upstream yet"), - NoValidTranslatorJob => write!(f, "Impossible to create a extended job for channel cause no valid job has been received from upstream yet"), - NoTemplateForId => write!(f, "Impossible to retrieve a template for the required job id"), - NoValidTemplate(e) => write!(f, "Impossible to retrieve a template for the required template id: {e}"), - PoisonLock(e) => write!(f, "Poison lock: {e}"), - JobNotUpdated(ds_job_id, us_job_id) => write!(f, "Channel Factory did not update job: Downstream job id = {ds_job_id}, Upstream job id = {us_job_id}"), - TargetError(e) => write!(f, "Impossible to get Target: {e:?}"), - HashrateError(e) => write!(f, "Impossible to get Hashrate: {e:?}"), - LogicErrorMessage(e) => write!(f, "Message is well formatted but can not be handled: {e:?}"), - JDSMissingTransactions => write!(f, "JD server cannot propagate the block: missing transactions"), - IoError(e) => write!(f, "IO error: {e:?}"), - ExtendedExtranonceCreationFailed(e) => write!(f, "Failed to create ExtendedExtranonce: {e}"), - FromSliceError(e) => write!(f, "Failed to hash from slice: {e}"), - InvalidUserIdentity(e) => write!(f, "Invalid user identity: {e}"), - ExtranoncePrefixFactoryError(e) => write!(f, "Failed to create ExtranoncePrefixFactory: {e:?}"), - Vardiff(e) => write!(f, "Failed to adjust diff in vardiff module: {e:?}"), - FailedToCreateStandardChannel(e) => write!(f, "Failed to create StandardChannel: {e:?}"), - FailedToCreateExtendedChannel(e) => write!(f, "Failed to create ExtendedChannel: {e:?}"), - FailedToProcessNewTemplateGroupChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), - FailedToProcessSetNewPrevHashGroupChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), - NoActiveJob => write!(f, "No active job"), - FailedToUpdateStandardChannel(e) => write!(f, "Failed to update StandardChannel: {e:?}"), - FailedToUpdateExtendedChannel(e) => write!(f, "Failed to update ExtendedChannel: {e:?}"), - FailedToSendSolution => write!(f, "Failed to send solution"), - FailedToSetCustomMiningJob(e) => write!(f, "Failed to set custom mining job: {e:?}"), - FailedToProcessNewTemplateExtendedChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), - FailedToProcessNewTemplateStandardChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), - FailedToProcessSetNewPrevHashExtendedChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), - FailedToProcessSetNewPrevHashStandardChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), - FailedToDeserializeCoinbaseOutputs => write!(f, "Failed to deserialize coinbase outputs"), - FailedToProcessGroupChannelJob(e) => write!(f, "Failed to process group channel job: {e:?}"), - ParserError(v) => write!(f, "Parser error: {v}"), - } - } -} - -impl From>> for Error { - fn from(value: PoisonError>) -> Self { - Error::PoisonLock(value.to_string()) - } -} diff --git a/protocols/v2/roles-logic-sv2/src/handlers/common.rs b/protocols/v2/roles-logic-sv2/src/handlers/common.rs deleted file mode 100644 index f1496853f2..0000000000 --- a/protocols/v2/roles-logic-sv2/src/handlers/common.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! # Common Handlers -//! -//! This module defines traits and implementations for handling common Stratum V2 messages exchanged -//! between upstream and downstream nodes. -//! -//! ## Message Handling -//! -//! Handlers in this module are responsible for: -//! - Parsing and deserializing common messages. -//! - Dispatching deserialized messages to appropriate handler functions based on message type, such -//! as `SetupConnection` or `ChannelEndpointChanged`. -//! - Ensuring robust error handling for unexpected or malformed messages. -//! -//! ## Return Type -//! -//! Functions return `Result`, where `SendTo` specifies the next action for the -//! message: whether to forward it, respond to it, or ignore it. -//! -//! ## Structure -//! -//! This module includes: -//! - Traits for upstream and downstream message parsing and handling. -//! - Functions to process common message types while maintaining clear separation of concerns. -//! - Error handling mechanisms to address edge cases and ensure reliable communication within -//! Stratum V2 networks. - -use super::SendTo_; -use crate::{errors::Error, utils::Mutex}; -use parsers_sv2::CommonMessages; - -use common_messages_sv2::{ - ChannelEndpointChanged, Reconnect, SetupConnection, SetupConnectionError, - SetupConnectionSuccess, *, -}; -use core::convert::TryInto; -use std::sync::Arc; - -/// see [`SendTo_`] -pub type SendTo = SendTo_, ()>; - -/// A trait that is implemented by the downstream node, and is used to handle -/// common messages sent by the upstream to the downstream -pub trait ParseCommonMessagesFromUpstream -where - Self: Sized, -{ - /// Takes a message type and a payload, and if the message type is a - /// [`crate::parsers::CommonMessages`], it calls the appropriate handler function - fn handle_message_common( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_common_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// Takes a message and it calls the appropriate handler function - fn handle_message_common_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - match message { - Ok(CommonMessages::SetupConnectionSuccess(m)) => { - self_.safe_lock(|x| x.handle_setup_connection_success(m))? - } - Ok(CommonMessages::SetupConnectionError(m)) => { - self_.safe_lock(|x| x.handle_setup_connection_error(m))? - } - Ok(CommonMessages::ChannelEndpointChanged(m)) => { - self_.safe_lock(|x| x.handle_channel_endpoint_changed(m))? - } - Ok(CommonMessages::Reconnect(m)) => self_.safe_lock(|x| x.handle_reconnect(m))?, - Ok(CommonMessages::SetupConnection(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_SETUP_CONNECTION)) - } - Err(e) => Err(e), - } - } - - /// Handles a `SetupConnectionSuccess` message. - /// - /// This method processes a `SetupConnectionSuccess` message and handles it - /// by delegating to the appropriate handler. - fn handle_setup_connection_success( - &mut self, - m: SetupConnectionSuccess, - ) -> Result; - - /// Handles a `SetupConnectionError` message. - /// - /// This method processes a `SetupConnectionError` message and handles it - /// by delegating to the appropriate handler. - fn handle_setup_connection_error(&mut self, m: SetupConnectionError) -> Result; - - /// Handles a `ChannelEndpointChanged` message. - /// - /// This method processes a `ChannelEndpointChanged` message and handles it - /// by delegating to the appropriate handler. - fn handle_channel_endpoint_changed( - &mut self, - m: ChannelEndpointChanged, - ) -> Result; - - /// Handles a `Reconnect` message. - fn handle_reconnect(&mut self, m: Reconnect) -> Result; -} - -/// A trait that is implemented by the upstream node, and is used to handle -/// common messages sent by the downstream to the upstream -pub trait ParseCommonMessagesFromDownstream -where - Self: Sized, -{ - /// It takes a message type and a payload, and if the message is a serialized setup connection - /// message, it calls the `on_setup_connection` function on the routing logic, and then calls - /// the `handle_setup_connection` function on the router - fn handle_message_common( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_common_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// It takes a message do setup connection message, it calls - /// the `on_setup_connection` function on the routing logic, and then calls - /// the `handle_setup_connection` function on the router - fn handle_message_common_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - match message { - Ok(CommonMessages::SetupConnection(m)) => { - self_.safe_lock(|x| x.handle_setup_connection(m))? - } - Ok(CommonMessages::SetupConnectionSuccess(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SETUP_CONNECTION_SUCCESS, - )), - Ok(CommonMessages::SetupConnectionError(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SETUP_CONNECTION_ERROR, - )), - Ok(CommonMessages::ChannelEndpointChanged(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_CHANNEL_ENDPOINT_CHANGED, - )), - Ok(CommonMessages::Reconnect(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_RECONNECT)) - } - Err(e) => Err(e), - } - } - - /// Handles a `SetupConnection` message. - /// - /// This method processes a `SetupConnection` message and handles it - /// by delegating to the appropriate handler in the routing logic. - fn handle_setup_connection(&mut self, m: SetupConnection) -> Result; -} diff --git a/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs b/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs deleted file mode 100644 index f6830158ca..0000000000 --- a/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs +++ /dev/null @@ -1,211 +0,0 @@ -//! # Job Declaration Handlers -//! -//! This module defines traits and functions for handling job declaration messages within the -//! Stratum V2 protocol. The job declaration process is integral to managing mining tasks and -//! transactions between server and client components. -//! -//! ## Message Handling -//! -//! The handlers are responsible for the following tasks: -//! - Parsing and deserializing job declaration messages into appropriate types. -//! - Dispatching the deserialized messages to specific handler functions based on their type, such -//! as handling job token allocation, job declaration success or error responses, and transaction -//! data management. -//! -//! ## Return Type -//! -//! The functions return a `Result`. The `SendTo` type determines the next action for -//! the message: whether the message should be relayed, responded to, or ignored. If an error occurs -//! during processing, the `Error` type is returned. -//! -//! ## Structure -//! -//! This module contains: -//! - Traits for processing job declaration messages, covering both server-side and client-side -//! handling. -//! - Functions designed to parse, deserialize, and process messages related to job declarations, -//! with robust error handling. -//! - Error handling mechanisms to address unexpected messages and ensure safe processing, -//! particularly in the context of shared state. - -use crate::utils::Mutex; -use parsers_sv2::JobDeclaration; -use std::sync::Arc; - -/// see [`SendTo_`] -pub type SendTo = SendTo_, ()>; -use super::SendTo_; -use crate::errors::Error; -use core::convert::TryInto; -use job_declaration_sv2::{ - MESSAGE_TYPE_ALLOCATE_MINING_JOB_TOKEN, MESSAGE_TYPE_ALLOCATE_MINING_JOB_TOKEN_SUCCESS, - MESSAGE_TYPE_DECLARE_MINING_JOB, MESSAGE_TYPE_DECLARE_MINING_JOB_ERROR, - MESSAGE_TYPE_DECLARE_MINING_JOB_SUCCESS, MESSAGE_TYPE_PROVIDE_MISSING_TRANSACTIONS, - MESSAGE_TYPE_PROVIDE_MISSING_TRANSACTIONS_SUCCESS, MESSAGE_TYPE_PUSH_SOLUTION, *, -}; - -/// A trait for parsing and handling SV2 job declaration messages sent by a server. -/// -/// This trait is designed to be implemented by downstream components that need to handle -/// various job declaration messages from an upstream SV2 server, such as job tokens allocation, -/// declaration success, and error messages. -pub trait ParseJobDeclarationMessagesFromUpstream -where - Self: Sized, -{ - /// Routes an incoming job declaration message to the appropriate handler function. - fn handle_message_job_declaration( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_job_declaration_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// Routes a deserialized job declaration message to the appropriate handler function. - fn handle_message_job_declaration_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - match message { - Ok(JobDeclaration::AllocateMiningJobTokenSuccess(message)) => { - self_.safe_lock(|x| x.handle_allocate_mining_job_token_success(message))? - } - Ok(JobDeclaration::DeclareMiningJobSuccess(message)) => { - self_.safe_lock(|x| x.handle_declare_mining_job_success(message))? - } - Ok(JobDeclaration::DeclareMiningJobError(message)) => { - self_.safe_lock(|x| x.handle_declare_mining_job_error(message))? - } - Ok(JobDeclaration::ProvideMissingTransactions(message)) => { - self_.safe_lock(|x| x.handle_provide_missing_transactions(message))? - } - Ok(JobDeclaration::AllocateMiningJobToken(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_ALLOCATE_MINING_JOB_TOKEN, - )), - Ok(JobDeclaration::DeclareMiningJob(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_DECLARE_MINING_JOB)) - } - Ok(JobDeclaration::ProvideMissingTransactionsSuccess(_)) => Err( - Error::UnexpectedMessage(MESSAGE_TYPE_PROVIDE_MISSING_TRANSACTIONS_SUCCESS), - ), - Ok(JobDeclaration::PushSolution(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_PUSH_SOLUTION)) - } - Err(e) => Err(e), - } - } - - /// Handles an `AllocateMiningJobTokenSuccess` message. - /// - /// This method processes a message indicating a successful job token allocation. - fn handle_allocate_mining_job_token_success( - &mut self, - message: AllocateMiningJobTokenSuccess, - ) -> Result; - - /// Handles a `DeclareMiningJobSuccess` message. - /// - /// This method processes a message indicating a successful mining job declaration. - fn handle_declare_mining_job_success( - &mut self, - message: DeclareMiningJobSuccess, - ) -> Result; - - /// Handles a `DeclareMiningJobError` message. - /// - /// This method processes a message indicating an error in the mining job declaration process. - fn handle_declare_mining_job_error( - &mut self, - message: DeclareMiningJobError, - ) -> Result; - - /// Handles a `ProvideMissingTransactions` message. - /// - /// This method processes a message that supplies missing transaction data. - fn handle_provide_missing_transactions( - &mut self, - message: ProvideMissingTransactions, - ) -> Result; -} - -/// A trait responsible for handling job declaration messages sent by clients to upstream nodes. -/// The methods process messages like job declarations, solutions, and transaction success -/// indicators, ensuring proper routing and handling. -pub trait ParseJobDeclarationMessagesFromDownstream -where - Self: Sized, -{ - /// Routes an incoming job declaration message to the appropriate handler function. - fn handle_message_job_declaration( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_job_declaration_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// Routes a deserialized job declaration message to the appropriate handler function. - fn handle_message_job_declaration_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - match message { - Ok(JobDeclaration::AllocateMiningJobToken(message)) => { - self_.safe_lock(|x| x.handle_allocate_mining_job_token(message))? - } - Ok(JobDeclaration::DeclareMiningJob(message)) => { - self_.safe_lock(|x| x.handle_declare_mining_job(message))? - } - Ok(JobDeclaration::ProvideMissingTransactionsSuccess(message)) => { - self_.safe_lock(|x| x.handle_provide_missing_transactions_success(message))? - } - Ok(JobDeclaration::PushSolution(message)) => { - self_.safe_lock(|x| x.handle_push_solution(message))? - } - Ok(JobDeclaration::AllocateMiningJobTokenSuccess(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_ALLOCATE_MINING_JOB_TOKEN_SUCCESS, - )), - Ok(JobDeclaration::DeclareMiningJobSuccess(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_DECLARE_MINING_JOB_SUCCESS, - )), - Ok(JobDeclaration::DeclareMiningJobError(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_DECLARE_MINING_JOB_ERROR, - )), - Ok(JobDeclaration::ProvideMissingTransactions(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_PROVIDE_MISSING_TRANSACTIONS, - )), - Err(e) => Err(e), - } - } - - /// Handles an `AllocateMiningJobToken` message. - fn handle_allocate_mining_job_token( - &mut self, - message: AllocateMiningJobToken, - ) -> Result; - - /// Handles a `DeclareMiningJob` message. - /// - /// This method processes a message that declares a new mining job. - fn handle_declare_mining_job(&mut self, message: DeclareMiningJob) -> Result; - - /// Handles a `ProvideMissingTransactionsSuccess` message. - /// - /// This method processes a message that confirms the receipt of missing transactions. - fn handle_provide_missing_transactions_success( - &mut self, - message: ProvideMissingTransactionsSuccess, - ) -> Result; - - /// Handles a `PushSolution` message. - /// - /// This method is used to process a valid block found by the miner. - fn handle_push_solution(&mut self, message: PushSolution) -> Result; -} diff --git a/protocols/v2/roles-logic-sv2/src/handlers/mining.rs b/protocols/v2/roles-logic-sv2/src/handlers/mining.rs deleted file mode 100644 index 0ea9a6d49e..0000000000 --- a/protocols/v2/roles-logic-sv2/src/handlers/mining.rs +++ /dev/null @@ -1,475 +0,0 @@ -//! # Mining Handlers -//! -//! This module defines traits and functions for handling mining-related messages within the Stratum -//! V2 protocol. -//! -//! ## Message Handling -//! -//! Handlers in this module are responsible for: -//! - Parsing and deserializing mining-related messages into the appropriate types. -//! - Dispatching the deserialized messages to specific handler functions based on message type, -//! such as handling new mining jobs, share submissions, and extranonce updates. -//! - Ensuring the integrity and validity of received messages, while interacting with downstream -//! mining systems to ensure proper communication and task execution. -//! -//! ## Return Type -//! -//! Functions return `Result, Error>`, where `SendTo` specifies the next action -//! for the message: whether it should be sent to the downstream node, an error response should be -//! generated, or the message should be ignored. -//! -//! ## Structure -//! -//! This module includes: -//! - Traits for processing mining-related messages for both upstream and downstream communication. -//! - Functions to parse, deserialize, and process messages related to mining, ensuring robust error -//! handling for unexpected conditions. -//! - Support for managing mining channels, extranonce prefixes, and share submissions, while -//! handling edge cases and ensuring the correctness of the mining process. - -use crate::errors::Error; -use binary_sv2; -use core::convert::TryInto; -use mining_sv2::{ - CloseChannel, NewExtendedMiningJob, NewMiningJob, OpenExtendedMiningChannel, - OpenExtendedMiningChannelSuccess, OpenMiningChannelError, OpenStandardMiningChannel, - OpenStandardMiningChannelSuccess, SetCustomMiningJob, SetCustomMiningJobError, - SetCustomMiningJobSuccess, SetExtranoncePrefix, SetGroupChannel, SetNewPrevHash, SetTarget, - SubmitSharesError, SubmitSharesExtended, SubmitSharesStandard, SubmitSharesSuccess, - UpdateChannel, UpdateChannelError, -}; -use parsers_sv2::Mining; - -use super::SendTo_; - -use crate::utils::Mutex; -use mining_sv2::*; -use std::{fmt::Debug as D, sync::Arc}; - -/// see [`SendTo_`] -pub type SendTo = SendTo_, Remote>; - -/// Represents supported channel types in a mining connection. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum SupportedChannelTypes { - Standard, - Extended, - Group, - /// Represents a connection that supports both group and extended channels. - GroupAndExtended, -} - -/// Trait for parsing downstream mining messages in a Stratum V2 connection. -/// -/// This trait defines methods for parsing and routing downstream messages -/// related to mining operations. -pub trait ParseMiningMessagesFromDownstream -where - Self: Sized + D, -{ - /// Returns the type of channel supported by the downstream connection. - fn get_channel_type(&self) -> SupportedChannelTypes; - - /// Handles a mining message from the downstream, given its type and payload. - fn handle_message_mining( - self_mutex: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result, Error> - where - Self: Sized, - { - match Self::handle_message_mining_deserialized( - self_mutex, - (message_type, payload).try_into().map_err(Into::into), - ) { - Err(Error::UnexpectedMessage(0)) => Err(Error::UnexpectedMessage(message_type)), - result => result, - } - } - - /// Deserializes and processes a mining message from the downstream. - fn handle_message_mining_deserialized( - self_mutex: Arc>, - message: Result, Error>, - ) -> Result, Error> - where - Self: Sized, - { - let (channel_type, is_work_selection_enabled) = self_mutex - .safe_lock(|self_| (self_.get_channel_type(), self_.is_work_selection_enabled()))?; - match message { - Ok(Mining::OpenStandardMiningChannel(m)) => { - // check user auth - if !Self::is_downstream_authorized(self_mutex.clone(), &m.user_identity)? { - return Ok(SendTo::Respond(Mining::OpenMiningChannelError( - OpenMiningChannelError::new_unknown_user(m.get_request_id_as_u32()), - ))); - } - match channel_type { - SupportedChannelTypes::Standard => self_mutex - .safe_lock(|self_| self_.handle_open_standard_mining_channel(m))?, - SupportedChannelTypes::Extended => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_STANDARD_MINING_CHANNEL, - )), - SupportedChannelTypes::Group => self_mutex - .safe_lock(|self_| self_.handle_open_standard_mining_channel(m))?, - SupportedChannelTypes::GroupAndExtended => self_mutex - .safe_lock(|self_| self_.handle_open_standard_mining_channel(m))?, - } - } - Ok(Mining::OpenExtendedMiningChannel(m)) => { - // check user auth - if !Self::is_downstream_authorized(self_mutex.clone(), &m.user_identity)? { - return Ok(SendTo::Respond(Mining::OpenMiningChannelError( - OpenMiningChannelError::new_unknown_user(m.get_request_id_as_u32()), - ))); - }; - match channel_type { - SupportedChannelTypes::Standard => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_EXTENDED_MINING_CHANNEL, - )), - SupportedChannelTypes::Extended => self_mutex - .safe_lock(|self_| self_.handle_open_extended_mining_channel(m))?, - SupportedChannelTypes::Group => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_EXTENDED_MINING_CHANNEL, - )), - SupportedChannelTypes::GroupAndExtended => self_mutex - .safe_lock(|self_| self_.handle_open_extended_mining_channel(m))?, - } - } - Ok(Mining::UpdateChannel(m)) => { - self_mutex.safe_lock(|self_| self_.handle_update_channel(m))? - } - Ok(Mining::SubmitSharesStandard(m)) => match channel_type { - SupportedChannelTypes::Standard => { - self_mutex.safe_lock(|self_| self_.handle_submit_shares_standard(m))? - } - SupportedChannelTypes::Extended => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SUBMIT_SHARES_STANDARD, - )), - SupportedChannelTypes::Group => { - self_mutex.safe_lock(|self_| self_.handle_submit_shares_standard(m))? - } - SupportedChannelTypes::GroupAndExtended => { - self_mutex.safe_lock(|self_| self_.handle_submit_shares_standard(m))? - } - }, - Ok(Mining::SubmitSharesExtended(m)) => match channel_type { - SupportedChannelTypes::Standard => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SUBMIT_SHARES_EXTENDED, - )), - SupportedChannelTypes::Extended => { - self_mutex.safe_lock(|self_| self_.handle_submit_shares_extended(m))? - } - SupportedChannelTypes::Group => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SUBMIT_SHARES_EXTENDED, - )), - SupportedChannelTypes::GroupAndExtended => { - self_mutex.safe_lock(|self_| self_.handle_submit_shares_extended(m))? - } - }, - Ok(Mining::SetCustomMiningJob(m)) => match (channel_type, is_work_selection_enabled) { - (SupportedChannelTypes::Extended, true) => { - self_mutex.safe_lock(|self_| self_.handle_set_custom_mining_job(m))? - } - (SupportedChannelTypes::GroupAndExtended, true) => { - self_mutex.safe_lock(|self_| self_.handle_set_custom_mining_job(m))? - } - _ => Err(Error::UnexpectedMessage(MESSAGE_TYPE_SET_CUSTOM_MINING_JOB)), - }, - Ok(Mining::CloseChannel(m)) => self_mutex.safe_lock(|x| x.handle_close_channel(m))?, - Ok(_) => Err(Error::UnexpectedMessage(0)), - Err(e) => Err(e), - } - } - - /// Checks if work selection is enabled for the downstream connection. - fn is_work_selection_enabled(&self) -> bool; - - /// Checks if the downstream user is authorized. - fn is_downstream_authorized( - _self_mutex: Arc>, - _user_identity: &binary_sv2::Str0255, - ) -> Result; - - /// Handles an `OpenStandardMiningChannel` message. - fn handle_open_standard_mining_channel( - &mut self, - m: OpenStandardMiningChannel, - ) -> Result, Error>; - - /// Handles an `OpenExtendedMiningChannel` message. - fn handle_open_extended_mining_channel( - &mut self, - m: OpenExtendedMiningChannel, - ) -> Result, Error>; - - /// Handles an `UpdateChannel` message. - /// - /// This method processes an `UpdateChannel` message and updates the channel settings. - fn handle_update_channel(&mut self, m: UpdateChannel) -> Result, Error>; - - /// Handles a `SubmitSharesStandard` message. - /// - /// This method processes a `SubmitSharesStandard` message and validates the submitted shares. - fn handle_submit_shares_standard( - &mut self, - m: SubmitSharesStandard, - ) -> Result, Error>; - - /// Handles a `SubmitSharesExtended` message. - /// - /// This method processes a `SubmitSharesExtended` message and validates the submitted shares. - fn handle_submit_shares_extended( - &mut self, - m: SubmitSharesExtended, - ) -> Result, Error>; - - /// Handles a `SetCustomMiningJob` message. - /// - /// This method processes a `SetCustomMiningJob` message and applies the custom mining job - /// settings. - fn handle_set_custom_mining_job(&mut self, m: SetCustomMiningJob) -> Result, Error>; - - /// Handles a request to close a mining channel. - fn handle_close_channel(&mut self, m: CloseChannel) -> Result, Error>; -} - -/// A trait defining the parser for upstream mining messages used by a downstream. -/// -/// This trait provides the functionality to handle and route various types of mining messages -/// from the upstream based on the message type and payload. -pub trait ParseMiningMessagesFromUpstream -where - Self: Sized + D, -{ - /// Retrieves the type of the channel supported by this upstream parser. - fn get_channel_type(&self) -> SupportedChannelTypes; - - /// Parses and routes SV2 mining messages from the upstream based on the message type and - /// payload. The implementor of DownstreamMining needs to pass a RequestIdMapper if changing - /// the request ID. Proxies typically need this to ensure the request ID is unique across - /// the connection. - fn handle_message_mining( - self_mutex: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result, Error> { - match Self::handle_message_mining_deserialized( - self_mutex, - (message_type, payload).try_into().map_err(Into::into), - ) { - Err(Error::UnexpectedMessage(0)) => Err(Error::UnexpectedMessage(message_type)), - result => result, - } - } - - /// Handles the deserialized mining message from the upstream, processing it according to the - /// routing logic. - fn handle_message_mining_deserialized( - self_mutex: Arc>, - message: Result, - ) -> Result, Error> { - let (channel_type, is_work_selection_enabled) = - self_mutex.safe_lock(|s| (s.get_channel_type(), s.is_work_selection_enabled()))?; - - match message { - Ok(Mining::OpenStandardMiningChannelSuccess(m)) => { - match channel_type { - SupportedChannelTypes::Standard => self_mutex - .safe_lock(|s| s.handle_open_standard_mining_channel_success(m))?, - SupportedChannelTypes::Extended => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_STANDARD_MINING_CHANNEL_SUCCESS, - )), - SupportedChannelTypes::Group => self_mutex - .safe_lock(|s| s.handle_open_standard_mining_channel_success(m))?, - SupportedChannelTypes::GroupAndExtended => self_mutex - .safe_lock(|s| s.handle_open_standard_mining_channel_success(m))?, - } - } - Ok(Mining::OpenExtendedMiningChannelSuccess(m)) => { - match channel_type { - SupportedChannelTypes::Standard => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_EXTENDED_MINING_CHANNEL_SUCCESS, - )), - SupportedChannelTypes::Extended => self_mutex - .safe_lock(|s| s.handle_open_extended_mining_channel_success(m))?, - SupportedChannelTypes::Group => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_OPEN_EXTENDED_MINING_CHANNEL_SUCCESS, - )), - SupportedChannelTypes::GroupAndExtended => self_mutex - .safe_lock(|s| s.handle_open_extended_mining_channel_success(m))?, - } - } - Ok(Mining::OpenMiningChannelError(m)) => { - self_mutex.safe_lock(|x| x.handle_open_mining_channel_error(m))? - } - Ok(Mining::UpdateChannelError(m)) => { - self_mutex.safe_lock(|x| x.handle_update_channel_error(m))? - } - Ok(Mining::CloseChannel(m)) => self_mutex.safe_lock(|x| x.handle_close_channel(m))?, - - Ok(Mining::SetExtranoncePrefix(m)) => { - self_mutex.safe_lock(|x| x.handle_set_extranonce_prefix(m))? - } - Ok(Mining::SubmitSharesSuccess(m)) => { - self_mutex.safe_lock(|x| x.handle_submit_shares_success(m))? - } - Ok(Mining::SubmitSharesError(m)) => { - self_mutex.safe_lock(|x| x.handle_submit_shares_error(m))? - } - Ok(Mining::NewMiningJob(m)) => match channel_type { - SupportedChannelTypes::Standard => { - self_mutex.safe_lock(|x| x.handle_new_mining_job(m))? - } - SupportedChannelTypes::Extended => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_NEW_MINING_JOB)) - } - SupportedChannelTypes::Group => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_NEW_MINING_JOB)) - } - SupportedChannelTypes::GroupAndExtended => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_NEW_MINING_JOB)) - } - }, - Ok(Mining::NewExtendedMiningJob(m)) => match channel_type { - SupportedChannelTypes::Standard => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_NEW_EXTENDED_MINING_JOB, - )), - SupportedChannelTypes::Extended => { - self_mutex.safe_lock(|x| x.handle_new_extended_mining_job(m))? - } - SupportedChannelTypes::Group => { - self_mutex.safe_lock(|x| x.handle_new_extended_mining_job(m))? - } - SupportedChannelTypes::GroupAndExtended => { - self_mutex.safe_lock(|x| x.handle_new_extended_mining_job(m))? - } - }, - Ok(Mining::SetNewPrevHash(m)) => { - self_mutex.safe_lock(|x| x.handle_set_new_prev_hash(m))? - } - Ok(Mining::SetCustomMiningJobSuccess(m)) => { - match (channel_type, is_work_selection_enabled) { - (SupportedChannelTypes::Extended, true) => { - self_mutex.safe_lock(|x| x.handle_set_custom_mining_job_success(m))? - } - (SupportedChannelTypes::GroupAndExtended, true) => { - self_mutex.safe_lock(|x| x.handle_set_custom_mining_job_success(m))? - } - _ => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SET_CUSTOM_MINING_JOB_SUCCESS, - )), - } - } - - Ok(Mining::SetCustomMiningJobError(m)) => { - match (channel_type, is_work_selection_enabled) { - (SupportedChannelTypes::Extended, true) => { - self_mutex.safe_lock(|x| x.handle_set_custom_mining_job_error(m))? - } - (SupportedChannelTypes::Group, true) => { - self_mutex.safe_lock(|x| x.handle_set_custom_mining_job_error(m))? - } - (SupportedChannelTypes::GroupAndExtended, true) => { - self_mutex.safe_lock(|x| x.handle_set_custom_mining_job_error(m))? - } - _ => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_SET_CUSTOM_MINING_JOB_ERROR, - )), - } - } - Ok(Mining::SetTarget(m)) => self_mutex.safe_lock(|x| x.handle_set_target(m))?, - Ok(Mining::SetGroupChannel(m)) => match channel_type { - SupportedChannelTypes::Standard => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_SET_GROUP_CHANNEL)) - } - SupportedChannelTypes::Extended => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_SET_GROUP_CHANNEL)) - } - SupportedChannelTypes::Group => { - self_mutex.safe_lock(|x| x.handle_set_group_channel(m))? - } - SupportedChannelTypes::GroupAndExtended => { - self_mutex.safe_lock(|x| x.handle_set_group_channel(m))? - } - }, - Ok(_) => Err(Error::UnexpectedMessage(0)), - Err(e) => Err(e), - } - } - - /// Determines whether work selection is enabled for this upstream. - fn is_work_selection_enabled(&self) -> bool; - - /// Handles a successful response for opening a standard mining channel. - fn handle_open_standard_mining_channel_success( - &mut self, - m: OpenStandardMiningChannelSuccess, - ) -> Result, Error>; - - /// Handles a successful response for opening an extended mining channel. - fn handle_open_extended_mining_channel_success( - &mut self, - m: OpenExtendedMiningChannelSuccess, - ) -> Result, Error>; - - /// Handles an error when opening a mining channel. - fn handle_open_mining_channel_error( - &mut self, - m: OpenMiningChannelError, - ) -> Result, Error>; - - /// Handles an error when updating a mining channel. - fn handle_update_channel_error(&mut self, m: UpdateChannelError) - -> Result, Error>; - - /// Handles a request to close a mining channel. - fn handle_close_channel(&mut self, m: CloseChannel) -> Result, Error>; - - /// Handles a request to set the extranonce prefix for mining. - fn handle_set_extranonce_prefix( - &mut self, - m: SetExtranoncePrefix, - ) -> Result, Error>; - - /// Handles a successful submission of shares. - fn handle_submit_shares_success( - &mut self, - m: SubmitSharesSuccess, - ) -> Result, Error>; - - /// Handles an error when submitting shares. - fn handle_submit_shares_error(&mut self, m: SubmitSharesError) -> Result, Error>; - - /// Handles a new mining job. - fn handle_new_mining_job(&mut self, m: NewMiningJob) -> Result, Error>; - - /// Handles a new extended mining job. - fn handle_new_extended_mining_job( - &mut self, - m: NewExtendedMiningJob, - ) -> Result, Error>; - - /// Handles a request to set the new previous hash. - fn handle_set_new_prev_hash(&mut self, m: SetNewPrevHash) -> Result, Error>; - - /// Handles a successful response for setting a custom mining job. - fn handle_set_custom_mining_job_success( - &mut self, - m: SetCustomMiningJobSuccess, - ) -> Result, Error>; - - /// Handles an error when setting a custom mining job. - fn handle_set_custom_mining_job_error( - &mut self, - m: SetCustomMiningJobError, - ) -> Result, Error>; - - /// Handles a request to set the target for mining. - fn handle_set_target(&mut self, m: SetTarget) -> Result, Error>; - - /// Handles a request to set the group channel for mining. - fn handle_set_group_channel(&mut self, _m: SetGroupChannel) -> Result, Error>; -} diff --git a/protocols/v2/roles-logic-sv2/src/handlers/mod.rs b/protocols/v2/roles-logic-sv2/src/handlers/mod.rs deleted file mode 100644 index 96cd504131..0000000000 --- a/protocols/v2/roles-logic-sv2/src/handlers/mod.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! # Handlers -//! -//! This module centralizes the logic for processing and routing Stratum V2 protocol messages, -//! defining traits and utilities to handle messages for both Downstream and Upstream roles. -//! -//! ## Purpose -//! -//! - Standardize the handling of protocol-specific messages. -//! - Enable efficient routing, transformation, and relaying of messages between nodes. -//! - Support modularity and scalability across Stratum V2 subprotocols. -//! -//! ## Structure -//! -//! The module is organized by subprotocol and role, with handler traits for: -//! - `ParseDownstream[Protocol]`: Handles messages from Downstream nodes. -//! - `ParseUpstream[Protocol]`: Handles messages from Upstream nodes. -//! -//! Supported subprotocols include: -//! - `common`: Shared messages across all Sv2 roles. -//! - `job_declaration`: Manages custom mining job declarations, transactions, and solutions. -//! - `mining`: Manages standard mining communication (e.g., job dispatch, shares submission). -//! - `template_distribution`: Handles block templates updates and transaction data. -//! - `Common Messages`: Shared across all Sv2 roles. -//! -//! ## Return Values -//! -//! Handlers return `Result`, where: -//! - `SendTo_` specifies the action (relay, respond, or no action). -//! - `Error` indicates processing issues. -pub mod common; -pub mod job_declaration; -pub mod mining; -pub mod template_distribution; -use crate::utils::Mutex; -use std::sync::Arc; - -#[derive(Debug)] -/// Represents a serializable entity used for communication between Remotes. -/// The `SendTo_` enum adds context to the message, specifying the intended action. -pub enum SendTo_ { - /// Relay a new message to a specific remote. - RelayNewMessageToRemote(Arc>, Message), - /// Relay the same received message to a specific remote to avoid extra allocations. - RelaySameMessageToRemote(Arc>), - /// Relay a new message without specifying a specific remote. - /// - /// This is common in proxies that translate between SV1 and SV2 protocols, where messages are - /// often broadcasted via extended channels. - RelayNewMessage(Message), - /// Directly respond to a received message. - Respond(Message), - /// Relay multiple messages to various destinations. - Multiple(Vec>), - /// Indicates that no immediate action is required for the message. - /// - /// This variant allows for cases where the message is still needed for later processing - /// (e.g., transformations or when two roles are implemented in the same software). - None(Option), -} - -impl SendTo_ { - /// Extracts the message, if available. - pub fn into_message(self) -> Option { - match self { - Self::RelayNewMessageToRemote(_, m) => Some(m), - Self::RelaySameMessageToRemote(_) => None, - Self::RelayNewMessage(m) => Some(m), - Self::Respond(m) => Some(m), - Self::Multiple(_) => None, - Self::None(m) => m, - } - } - - /// Extracts the remote, if available. - pub fn into_remote(self) -> Option>> { - match self { - Self::RelayNewMessageToRemote(r, _) => Some(r), - Self::RelaySameMessageToRemote(r) => Some(r), - Self::RelayNewMessage(_) => None, - Self::Respond(_) => None, - Self::Multiple(_) => None, - Self::None(_) => None, - } - } -} diff --git a/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs b/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs deleted file mode 100644 index 9054a23874..0000000000 --- a/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! # Template Distribution Handlers -//! -//! This module defines traits and functions for handling template distribution messages within the -//! Stratum V2 protocol. -//! -//! ## Message Handling -//! -//! Handlers are responsible for: -//! - Parsing and deserializing template distribution messages into appropriate types. -//! - Dispatching the deserialized messages to specific handler functions based on message type, -//! such as handling new templates, transaction data requests, and coinbase output data. -//! -//! ## Return Type -//! -//! Functions return `Result`, where `SendTo` determines the next action for the -//! message: whether it should be relayed, responded to, or ignored. -//! -//! ## Structure -//! -//! This module includes: -//! - Traits for processing template distribution messages, including server-side and client-side -//! handling. -//! - Functions to parse, deserialize, and process messages related to template distribution, -//! ensuring robust error handling. -//! - Error handling mechanisms to address unexpected messages and ensure safe processing, -//! especially in the context of shared state. - -use super::SendTo_; -use crate::{errors::Error, utils::Mutex}; -use parsers_sv2::TemplateDistribution; -use template_distribution_sv2::{ - CoinbaseOutputConstraints, NewTemplate, RequestTransactionData, RequestTransactionDataError, - RequestTransactionDataSuccess, SetNewPrevHash, SubmitSolution, -}; - -/// see [`SendTo_`] -pub type SendTo = SendTo_, ()>; -use core::convert::TryInto; -use std::sync::Arc; -use template_distribution_sv2::*; - -/// Trait for handling template distribution messages received from server (Template Provider). -/// Includes functions to handle messages such as new templates, previous hash updates, and -/// transaction data requests. -pub trait ParseTemplateDistributionMessagesFromServer -where - Self: Sized, -{ - /// Handles incoming template distribution messages. - /// - /// This function is responsible for parsing and dispatching the appropriate handler based on - /// the message type. It first deserializes the payload and then routes it to the - /// corresponding handler function. - fn handle_message_template_distribution( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_template_distribution_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// Handles deserialized template distribution messages. - /// - /// This function takes the deserialized message and processes it according to the specific - /// message type, invoking the appropriate handler function. - fn handle_message_template_distribution_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - // Is ok to unwrap a safe_lock result - match message { - Ok(TemplateDistribution::NewTemplate(m)) => { - self_.safe_lock(|x| x.handle_new_template(m))? - } - Ok(TemplateDistribution::SetNewPrevHash(m)) => { - self_.safe_lock(|x| x.handle_set_new_prev_hash(m))? - } - Ok(TemplateDistribution::RequestTransactionDataSuccess(m)) => { - self_.safe_lock(|x| x.handle_request_tx_data_success(m))? - } - Ok(TemplateDistribution::RequestTransactionDataError(m)) => { - self_.safe_lock(|x| x.handle_request_tx_data_error(m))? - } - Ok(TemplateDistribution::CoinbaseOutputConstraints(_)) => Err( - Error::UnexpectedMessage(MESSAGE_TYPE_COINBASE_OUTPUT_CONSTRAINTS), - ), - Ok(TemplateDistribution::RequestTransactionData(_)) => Err(Error::UnexpectedMessage( - MESSAGE_TYPE_REQUEST_TRANSACTION_DATA, - )), - Ok(TemplateDistribution::SubmitSolution(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_SUBMIT_SOLUTION)) - } - Err(e) => Err(e), - } - } - - /// Handles a `NewTemplate` message. - /// - /// This method processes the `NewTemplate` message, which contains information about a newly - /// generated template. - fn handle_new_template(&mut self, m: NewTemplate) -> Result; - - /// Handles a `SetNewPrevHash` message. - /// - /// This method processes the `SetNewPrevHash` message, which updates the previous hash for a - /// template. - fn handle_set_new_prev_hash(&mut self, m: SetNewPrevHash) -> Result; - - /// Handles a `RequestTransactionDataSuccess` message. - /// - /// This method processes the success response for a requested transaction data message. - fn handle_request_tx_data_success( - &mut self, - m: RequestTransactionDataSuccess, - ) -> Result; - - /// Handles a `RequestTransactionDataError` message. - /// - /// This method processes an error response for a requested transaction data message. - fn handle_request_tx_data_error( - &mut self, - m: RequestTransactionDataError, - ) -> Result; -} - -/// Trait for handling template distribution messages received from downstream nodes (client side). -/// Includes functions to handle messages such as coinbase output data size, transaction data -/// requests, and solution submissions. -pub trait ParseTemplateDistributionMessagesFromClient -where - Self: Sized, -{ - /// Handles incoming template distribution messages. - /// - /// This function is responsible for parsing and dispatching the appropriate handler based on - /// the message type. It first deserializes the payload and then routes it to the - /// corresponding handler function. - fn handle_message_template_distribution( - self_: Arc>, - message_type: u8, - payload: &mut [u8], - ) -> Result { - Self::handle_message_template_distribution_deserialized( - self_, - (message_type, payload).try_into().map_err(Into::into), - ) - } - - /// Handles deserialized template distribution messages. - /// - /// This function takes the deserialized message and processes it according to the specific - /// message type, invoking the appropriate handler function. - fn handle_message_template_distribution_deserialized( - self_: Arc>, - message: Result, Error>, - ) -> Result { - match message { - Ok(TemplateDistribution::CoinbaseOutputConstraints(m)) => { - self_.safe_lock(|x| x.handle_coinbase_out_data_size(m))? - } - Ok(TemplateDistribution::RequestTransactionData(m)) => { - self_.safe_lock(|x| x.handle_request_tx_data(m))? - } - Ok(TemplateDistribution::SubmitSolution(m)) => { - self_.safe_lock(|x| x.handle_request_submit_solution(m))? - } - Ok(TemplateDistribution::NewTemplate(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_NEW_TEMPLATE)) - } - Ok(TemplateDistribution::SetNewPrevHash(_)) => { - Err(Error::UnexpectedMessage(MESSAGE_TYPE_SET_NEW_PREV_HASH)) - } - Ok(TemplateDistribution::RequestTransactionDataSuccess(_)) => Err( - Error::UnexpectedMessage(MESSAGE_TYPE_REQUEST_TRANSACTION_DATA_SUCCESS), - ), - Ok(TemplateDistribution::RequestTransactionDataError(_)) => Err( - Error::UnexpectedMessage(MESSAGE_TYPE_REQUEST_TRANSACTION_DATA_ERROR), - ), - Err(e) => Err(e), - } - } - - /// Handles a `CoinbaseOutputConstraints` message. - /// - /// This method processes a message that includes the coinbase output data size. - fn handle_coinbase_out_data_size( - &mut self, - m: CoinbaseOutputConstraints, - ) -> Result; - - /// Handles a `RequestTransactionData` message. - /// - /// This method processes a message requesting transaction data. - fn handle_request_tx_data(&mut self, m: RequestTransactionData) -> Result; - - /// Handles a `SubmitSolution` message. - /// - /// This method processes a solution submission message. - fn handle_request_submit_solution(&mut self, m: SubmitSolution) -> Result; -} diff --git a/protocols/v2/roles-logic-sv2/src/lib.rs b/protocols/v2/roles-logic-sv2/src/lib.rs deleted file mode 100644 index 099fcaca97..0000000000 --- a/protocols/v2/roles-logic-sv2/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! # Stratum V2 Roles-Logic Library -//! -//! roles_logic_sv2 provides the core logic and utilities for implementing roles in the Stratum V2 -//! (Sv2) protocol, such as miners, pools, and proxies. It abstracts message handling, channel -//! management, job creation, and routing logic, enabling efficient and secure communication across -//! upstream and downstream connections. -//! -//! ## Usage -//! -//! To include this crate in your project, run: -//! ```bash -//! $ cargo add roles_logic_sv2 -//! ``` -//! -//! ## Build Options -//! -//! This crate can be built with the following features: -//! -//! - `prop_test`: Enables support for property testing in [`template_distribution_sv2`] crate. -pub mod errors; -pub mod handlers; -pub mod utils; -pub use errors::Error; diff --git a/protocols/v2/roles-logic-sv2/src/utils.rs b/protocols/v2/roles-logic-sv2/src/utils.rs deleted file mode 100644 index 8b23742da9..0000000000 --- a/protocols/v2/roles-logic-sv2/src/utils.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! # Collection of Helper Primitives -//! -//! Provides a collection of utilities and helper structures used throughout the Stratum V2 -//! protocol implementation. These utilities simplify common tasks, such as ID generation and -//! management, mutex management, difficulty target calculations, merkle root calculations, and -//! more. - -use std::sync::{Mutex as Mutex_, MutexGuard, PoisonError}; - -/// Custom synchronization primitive for managing shared mutable state. -/// -/// This custom mutex implementation builds on [`std::sync::Mutex`] to enhance usability and safety -/// in concurrent environments. It provides ergonomic methods to safely access and modify inner -/// values while reducing the risk of deadlocks and panics. It is used throughout SRI applications -/// to managed shared state across multiple threads, such as tracking active mining sessions, -/// routing jobs, and managing connections safely and efficiently. -/// -/// ## Advantages -/// - **Closure-Based Locking:** The `safe_lock` method encapsulates the locking process, ensuring -/// the lock is automatically released after the closure completes. -/// - **Error Handling:** `safe_lock` enforces explicit handling of potential [`PoisonError`] -/// conditions, reducing the risk of panics caused by poisoned locks. -/// - **Panic-Safe Option:** The `super_safe_lock` method provides an alternative that unwraps the -/// result of `safe_lock`, with optional runtime safeguards against panics. -/// - **Extensibility:** Includes feature-gated functionality to customize behavior, such as -/// stricter runtime checks using external tools like -/// [`no-panic`](https://github.com/dtolnay/no-panic). -#[derive(Debug)] -pub struct Mutex(Mutex_); - -impl Mutex { - /// Mutex safe lock. - /// - /// Safely locks the `Mutex` and executes a closer (`thunk`) with a mutable reference to the - /// inner value. This ensures that the lock is automatically released after the closure - /// completes, preventing deadlocks. It explicitly returns a [`PoisonError`] containing a - /// [`MutexGuard`] to the inner value in cases where the lock is poisoned. - /// - /// To prevent poison lock errors, unwraps should never be used within the closure. The result - /// should always be returned and handled outside of the sage lock. - pub fn safe_lock(&self, thunk: F) -> Result>> - where - F: FnOnce(&mut T) -> Ret, - { - let mut lock = self.0.lock()?; - let return_value = thunk(&mut *lock); - drop(lock); - Ok(return_value) - } - - /// Mutex super safe lock. - /// - /// Locks the `Mutex` and executes a closure (`thunk`) with a mutable reference to the inner - /// value, panicking if the lock is poisoned. - /// - /// This is a convenience wrapper around `safe_lock` for cases where explicit error handling is - /// unnecessary or undesirable. Use with caution in production code. - pub fn super_safe_lock(&self, thunk: F) -> Ret - where - F: FnOnce(&mut T) -> Ret, - { - //#[cfg(feature = "disable_nopanic")] - { - self.safe_lock(thunk).unwrap() - } - //#[cfg(not(feature = "disable_nopanic"))] - //{ - // // based on https://github.com/dtolnay/no-panic - // struct __NoPanic; - // extern "C" { - // #[link_name = "super_safe_lock called on a function that may panic"] - // fn trigger() -> !; - // } - // impl core::ops::Drop for __NoPanic { - // fn drop(&mut self) { - // unsafe { - // trigger(); - // } - // } - // } - // let mut lock = self.0.lock().expect("threads to never panic"); - // let __guard = __NoPanic; - // let return_value = thunk(&mut *lock); - // core::mem::forget(__guard); - // drop(lock); - // return_value - //} - } - - /// Creates a new [`Mutex`] instance, storing the initial value inside. - pub fn new(v: T) -> Self { - Mutex(Mutex_::new(v)) - } - - /// Removes lock for direct access. - /// - /// Acquires a lock on the [`Mutex`] and returns a [`MutexGuard`] for direct access to the - /// inner value. Allows for manual lock handling and is useful in scenarios where closures are - /// not convenient. - pub fn to_remove(&self) -> Result, PoisonError>> { - self.0.lock() - } -} - -#[cfg(test)] -mod tests { - - #[test] - fn test_super_safe_lock() { - let m = super::Mutex::new(1u32); - m.safe_lock(|i| *i += 1).unwrap(); - // m.super_safe_lock(|i| *i = (*i).checked_add(1).unwrap()); // will not compile - m.super_safe_lock(|i| *i = (*i).checked_add(1).unwrap_or_default()); // compiles - } -} diff --git a/roles/Cargo.lock b/roles/Cargo.lock index 701b538161..f2279dd026 100644 --- a/roles/Cargo.lock +++ b/roles/Cargo.lock @@ -435,19 +435,44 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d965446196e3b7decd44aa7ee49e31d630118f90ef12f97900f262eb915c951d" +[[package]] +name = "binary_codec_sv2" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ad24342e0abdcc463ad6ad4ac7b0ec606122c11eddf92de186a657df0114eb7" + [[package]] name = "binary_codec_sv2" version = "3.0.0" dependencies = [ - "buffer_sv2", + "buffer_sv2 2.0.0", +] + +[[package]] +name = "binary_codec_sv2" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16415a0a9ccee2f71820da352c1f2a7f16d9f8e3ae6fb5e97834c6d732e98cd" +dependencies = [ + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "binary_sv2" version = "4.0.0" dependencies = [ - "binary_codec_sv2", - "derive_codec_sv2", + "binary_codec_sv2 3.0.0", + "derive_codec_sv2 1.1.1", +] + +[[package]] +name = "binary_sv2" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8295945d51b707f3a49e17810dddef858549e2b52383c7f2c4dd036f6bc1e6" +dependencies = [ + "binary_codec_sv2 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "derive_codec_sv2 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -598,6 +623,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "buffer_sv2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19781425841d2e217eb7ded68089b693b47c8f756eb02231c92122dbf505bcf0" +dependencies = [ + "aes-gcm", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -668,17 +702,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "channels_sv2" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ac02b93b5bd92a7dda2bc4b8c9d1f087e1fffc8b1018b532109135629051fc" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing", +] + [[package]] name = "channels_sv2" version = "2.0.0" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin", - "common_messages_sv2", - "job_declaration_sv2", - "mining_sv2", + "common_messages_sv2 6.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", "primitive-types", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1", "tracing", ] @@ -760,14 +810,28 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +[[package]] +name = "codec_sv2" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e6d43e79e66d0f98038922157db8b6101594921be87ac2cca3754d669f2a05" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand", + "tracing", +] + [[package]] name = "codec_sv2" version = "4.0.0" dependencies = [ - "binary_sv2", - "buffer_sv2", - "framing_sv2", - "noise_sv2", + "binary_sv2 4.0.0", + "buffer_sv2 2.0.0", + "framing_sv2 5.0.1", + "noise_sv2 1.4.0", "rand", "tracing", ] @@ -782,7 +846,16 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" name = "common_messages_sv2" version = "6.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "common_messages_sv2" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6ec6ab527aeebf8ead273d6ab712ff181c050ee5e1082f3f6a2c65c0a10bf6" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -813,6 +886,18 @@ dependencies = [ "yaml-rust2", ] +[[package]] +name = "config_helpers_sv2" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3307b494a63dab36d0bec2b1e830b6568f53300aaa9516ac673a434e799ae" +dependencies = [ + "miniscript", + "serde", + "tracing", + "tracing-subscriber", +] + [[package]] name = "const-random" version = "0.1.18" @@ -983,7 +1068,16 @@ dependencies = [ name = "derive_codec_sv2" version = "1.1.1" dependencies = [ - "binary_codec_sv2", + "binary_codec_sv2 3.0.0", +] + +[[package]] +name = "derive_codec_sv2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924f288d967a5cd37956b195269ee7f710999169895cf670a736e1b2267d6137" +dependencies = [ + "binary_codec_sv2 1.2.0", ] [[package]] @@ -1045,6 +1139,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error_handling" +version = "1.0.0" + +[[package]] +name = "error_handling" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdf3be9049288001eb8a37f21b0f4e922598a6fa0098630fd3a6a14459ef217" + [[package]] name = "event-listener" version = "2.5.3" @@ -1126,9 +1230,20 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" name = "framing_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", - "buffer_sv2", - "noise_sv2", + "binary_sv2 4.0.0", + "buffer_sv2 2.0.0", + "noise_sv2 1.4.0", +] + +[[package]] +name = "framing_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6543955264144174b93780e0e76623ee4293037c9e180cfde3e2c155b59fa9" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1332,16 +1447,31 @@ dependencies = [ "crunchy", ] +[[package]] +name = "handlers_sv2" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "472824f98b68a963dbf4c77625a8b5525c322abe49afa9403dfb816e35dd4d93" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "trait-variant", +] + [[package]] name = "handlers_sv2" version = "0.2.0" dependencies = [ - "binary_sv2", - "common_messages_sv2", - "job_declaration_sv2", - "mining_sv2", - "parsers_sv2", - "template_distribution_sv2", + "binary_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "parsers_sv2 0.1.1", + "template_distribution_sv2 4.0.1", "trait-variant", ] @@ -1644,6 +1774,7 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", + "key-utils 1.2.0", "serde", "stratum-apps", "tokio", @@ -1655,15 +1786,29 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel 1.9.0", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", + "config_helpers_sv2", + "error_handling 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", "nohash-hasher", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "serde", "serde_json", - "stratum-apps", "tokio", "tracing", ] @@ -1672,7 +1817,16 @@ dependencies = [ name = "job_declaration_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "job_declaration_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d4edc436d29e8dcac178539222de2b3681d629f9884191bd7db8831e49dd24" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1696,6 +1850,31 @@ dependencies = [ "serde", ] +[[package]] +name = "key-utils" +version = "1.2.0" +dependencies = [ + "bs58", + "generic-array", + "rand", + "rustversion", + "secp256k1 0.28.2", + "serde", +] + +[[package]] +name = "key-utils" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe8551792fd4461e519fdfd8b8f334d1bf480250786fd202baf418854ff7130" +dependencies = [ + "bs58", + "rand", + "rustversion", + "secp256k1 0.28.2", + "serde", +] + [[package]] name = "kv-log-macro" version = "1.0.7" @@ -1780,16 +1959,29 @@ version = "0.1.3" dependencies = [ "async-channel 1.9.0", "async-recursion", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "config_helpers_sv2", "criterion", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", "half", + "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-format", "num_cpus", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", "rand", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "sha2 0.10.9", - "stratum-apps", "tokio", "tracing", "tracing-subscriber", @@ -1799,7 +1991,16 @@ dependencies = [ name = "mining_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "mining_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1eb3c055232f64d36e3eee4296adcaa584fb3185a57e0de11ad5807766c45edc" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1832,6 +2033,19 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "network_helpers_sv2" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d720d6a31532fb4f08e59b71669084d06462f42e9d2c2aede7368d221d36db" +dependencies = [ + "async-channel 1.9.0", + "codec_sv2 3.0.1", + "futures", + "tokio", + "tracing", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -1850,6 +2064,19 @@ dependencies = [ "secp256k1 0.28.2", ] +[[package]] +name = "noise_sv2" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30964f9fbc4572bb5a1b0046176331d20e9ce6de0ca18afc3cfd42c6e91a94aa" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "rand", + "rand_chacha", + "secp256k1 0.28.2", +] + [[package]] name = "nom" version = "7.1.3" @@ -2002,12 +2229,26 @@ dependencies = [ name = "parsers_sv2" version = "0.1.1" dependencies = [ - "binary_sv2", - "common_messages_sv2", - "framing_sv2", - "job_declaration_sv2", - "mining_sv2", - "template_distribution_sv2", + "binary_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "framing_sv2 5.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "template_distribution_sv2 4.0.1", +] + +[[package]] +name = "parsers_sv2" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109e80bc77241a729f61cad15f3f246f3de12e1b741b31e419fc7e02f20c2ccb" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2150,6 +2391,8 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", + "error_handling 1.0.0", + "key-utils 1.2.0", "rand", "secp256k1 0.28.2", "serde", @@ -2279,24 +2522,48 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" +[[package]] +name = "roles_logic_sv2" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7241840512841396df29ede2094619ad06cbbd1a0dc342553c7a5901506d096b" +dependencies = [ + "bitcoin", + "chacha20poly1305", + "channels_sv2 1.0.2", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "handlers_sv2 0.1.0", + "hex-conservative 0.3.0", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "nohash-hasher", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing", +] + [[package]] name = "roles_logic_sv2" version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88850ead16993f86cb4616d154ddd37b9c0d739ea23711b1cc51f40484e0e39a" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitcoin", "chacha20poly1305", - "channels_sv2", - "codec_sv2", - "common_messages_sv2", - "handlers_sv2", + "channels_sv2 1.0.2", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "handlers_sv2 0.1.0", "hex-conservative 0.3.0", - "job_declaration_sv2", - "mining_sv2", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "nohash-hasher", - "parsers_sv2", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "tracing", ] @@ -2312,6 +2579,22 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rpc_sv2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9b3a6c43d03c5cc6ca9f40797cbf17a9a30b8db236be6c87f5243bd404d6af" +dependencies = [ + "base64 0.21.7", + "hex", + "http-body-util", + "hyper", + "hyper-util", + "serde", + "serde_json", + "stratum-common", +] + [[package]] name = "rust-ini" version = "0.20.0" @@ -2614,12 +2897,14 @@ dependencies = [ "bs58", "clap", "config", + "error_handling 1.0.0", "futures", "generic-array", "hex", "http-body-util", "hyper", "hyper-util", + "key-utils 1.2.0", "miniscript", "rand", "rustversion", @@ -2633,35 +2918,43 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "stratum-common" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77b7dc7a762d19aba6f355599a61440b29603ceece5a158914888691b9867ebe" +dependencies = [ + "roles_logic_sv2 4.0.0", +] + [[package]] name = "stratum-core" version = "0.1.0" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin", - "buffer_sv2", - "channels_sv2", - "codec_sv2", - "common_messages_sv2", - "framing_sv2", - "handlers_sv2", - "job_declaration_sv2", - "mining_sv2", - "noise_sv2", - "parsers_sv2", - "roles_logic_sv2", + "buffer_sv2 2.0.0", + "channels_sv2 2.0.0", + "codec_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "framing_sv2 5.0.1", + "handlers_sv2 0.2.0", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "noise_sv2 1.4.0", + "parsers_sv2 0.1.1", "stratum_translation", "sv1_api", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1", ] [[package]] name = "stratum_translation" version = "0.1.0" dependencies = [ - "binary_sv2", - "channels_sv2", - "mining_sv2", + "binary_sv2 4.0.0", + "channels_sv2 2.0.0", + "mining_sv2 5.0.1", "sv1_api", "tracing", ] @@ -2682,7 +2975,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" name = "sv1_api" version = "2.1.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin_hashes 0.3.2", "byteorder", "hex", @@ -2744,7 +3037,16 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" name = "template_distribution_sv2" version = "4.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "template_distribution_sv2" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6298fc9f339b1c3b654ef3590857d5d3eff6d709891f003b7f7a701b8a64a3a4" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2995,6 +3297,7 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", + "key-utils 1.2.0", "serde", "serde_json", "sha2 0.10.9", diff --git a/roles/jd-server/Cargo.toml b/roles/jd-server/Cargo.toml index 102b6bb6f9..940d8260a3 100644 --- a/roles/jd-server/Cargo.toml +++ b/roles/jd-server/Cargo.toml @@ -17,7 +17,22 @@ name = "jd_server" path = "src/lib/mod.rs" [dependencies] -stratum-apps = { path = "../stratum-apps", features = ["jd_server"] } +rpc_sv2 = { version = "1.1.0" } +config_helpers_sv2 = { version = "0.1.0" } +network_helpers_sv2 = { version = "4.0.0" } +roles_logic_sv2 = { version = "5.0.0" } +# Published versions to match roles_logic_sv2 v5.0.0 exact dependencies +binary_sv2 = { version = "4.0.0" } +job_declaration_sv2 = { version = "5.0.0" } +parsers_sv2 = { version = "0.1" } +codec_sv2 = { version = "3.0.0" } +framing_sv2 = { version = "5.0.0" } +noise_sv2 = { version = "1.1" } +common_messages_sv2 = { version = "6.0.0" } +mining_sv2 = { version = "5.0" } +error_handling = { version = "1.0.0" } +key-utils = { version = "1.2.0" } +bitcoin = "0.32.5" async-channel = "1.5.1" rand = "0.8.4" tokio = { version = "1.44.1", features = ["full"] } diff --git a/roles/jd-server/src/lib/config.rs b/roles/jd-server/src/lib/config.rs index ee01a046ec..821797af5a 100644 --- a/roles/jd-server/src/lib/config.rs +++ b/roles/jd-server/src/lib/config.rs @@ -11,15 +11,13 @@ //! //! Also defines a helper struct [`CoreRpc`] to group RPC parameters. +use config_helpers_sv2::CoinbaseRewardScript; +use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use serde::Deserialize; use std::{ path::{Path, PathBuf}, time::Duration, }; -use stratum_apps::{ - config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, -}; #[derive(Debug, serde::Deserialize, Clone)] pub struct JobDeclaratorServerConfig { @@ -34,7 +32,7 @@ pub struct JobDeclaratorServerConfig { core_rpc_port: u16, core_rpc_user: String, core_rpc_pass: String, - #[serde(deserialize_with = "stratum_apps::config_helpers::duration_from_toml")] + #[serde(deserialize_with = "config_helpers_sv2::duration_from_toml")] mempool_update_interval: Duration, log_file: Option, } @@ -175,9 +173,9 @@ impl CoreRpc { #[cfg(test)] mod tests { use super::super::JobDeclaratorServer; + use bitcoin::{self, Amount, ScriptBuf, TxOut}; use ext_config::{Config, ConfigError, File, FileFormat}; use std::path::PathBuf; - use stratum_apps::stratum_core::bitcoin::{self, Amount, ScriptBuf, TxOut}; use crate::config::JobDeclaratorServerConfig; diff --git a/roles/jd-server/src/lib/error.rs b/roles/jd-server/src/lib/error.rs index 5a830a4bd1..38844c4f83 100644 --- a/roles/jd-server/src/lib/error.rs +++ b/roles/jd-server/src/lib/error.rs @@ -19,9 +19,12 @@ use std::{ sync::{MutexGuard, PoisonError}, }; -use stratum_apps::stratum_core::{ - binary_sv2, codec_sv2, framing_sv2, noise_sv2, parsers_sv2::Mining, roles_logic_sv2, -}; +use binary_sv2; +use codec_sv2; +use framing_sv2; +use noise_sv2; +use parsers_sv2::Mining; +use roles_logic_sv2; use crate::mempool::error::JdsMempoolError; diff --git a/roles/jd-server/src/lib/job_declarator/message_handler.rs b/roles/jd-server/src/lib/job_declarator/message_handler.rs index c0a1a43f48..b5644bad41 100644 --- a/roles/jd-server/src/lib/job_declarator/message_handler.rs +++ b/roles/jd-server/src/lib/job_declarator/message_handler.rs @@ -1,33 +1,30 @@ +use binary_sv2::{Decodable, Serialize, U256}; +use bitcoin::{ + consensus::Decodable as BitcoinDecodable, + hashes::{sha256d, Hash}, + Transaction, Txid, +}; +use job_declaration_sv2::{ + AllocateMiningJobToken, AllocateMiningJobTokenSuccess, DeclareMiningJob, DeclareMiningJobError, + DeclareMiningJobSuccess, ProvideMissingTransactions, ProvideMissingTransactionsSuccess, + PushSolution, +}; +use parsers_sv2::JobDeclaration; +use roles_logic_sv2::{ + errors::Error, + handlers::{job_declaration::ParseJobDeclarationMessagesFromDownstream, SendTo_}, + utils::Mutex, +}; use std::{ convert::TryInto, io::Cursor, sync::{atomic::Ordering, Arc}, }; -use stratum_apps::stratum_core::{ - binary_sv2::{Decodable, Serialize, U256}, - bitcoin::{ - consensus::Decodable as BitcoinDecodable, - hashes::{sha256d, Hash}, - Transaction, Txid, - }, - job_declaration_sv2::{ - AllocateMiningJobToken, AllocateMiningJobTokenSuccess, DeclareMiningJob, - DeclareMiningJobError, DeclareMiningJobSuccess, ProvideMissingTransactions, - ProvideMissingTransactionsSuccess, PushSolution, - }, - parsers_sv2::JobDeclaration, - roles_logic_sv2::{ - handlers::{job_declaration::ParseJobDeclarationMessagesFromDownstream, SendTo_}, - utils::Mutex, - }, -}; pub type SendTo = SendTo_, ()>; use crate::mempool::JDsMempool; use super::{signed_token, TransactionState}; -use stratum_apps::stratum_core::{ - parsers_sv2::AnyMessage as AllMessages, roles_logic_sv2::errors::Error, -}; +use parsers_sv2::AnyMessage as AllMessages; use tracing::{debug, info}; use super::JobDeclaratorDownstream; diff --git a/roles/jd-server/src/lib/job_declarator/mod.rs b/roles/jd-server/src/lib/job_declarator/mod.rs index 2e3cf18558..40b88aa516 100644 --- a/roles/jd-server/src/lib/job_declarator/mod.rs +++ b/roles/jd-server/src/lib/job_declarator/mod.rs @@ -22,38 +22,34 @@ use super::{ error::JdsError, mempool::JDsMempool, status, EitherFrame, JobDeclaratorServerConfig, StdFrame, }; use async_channel::{Receiver, Sender}; +use binary_sv2::{self, B0255, U256}; +use bitcoin::{ + block::{Header, Version}, + consensus::{deserialize, encode::serialize}, + hashes::{sha256d::Hash as DHash, Hash}, + Amount, Block, BlockHash, CompactTarget, Transaction, TxOut, Txid, +}; +use codec_sv2::HandshakeRole; +use common_messages_sv2::{ + Protocol, SetupConnection, SetupConnectionError, SetupConnectionSuccess, +}; use core::panic; +use error_handling::handle_result; +use job_declaration_sv2::{DeclareMiningJob, PushSolution}; +use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; +use network_helpers_sv2::noise_connection::Connection; use nohash_hasher::BuildNoHashHasher; +use noise_sv2::Responder; +use parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}; +use roles_logic_sv2::{ + handlers::job_declaration::{ParseJobDeclarationMessagesFromDownstream, SendTo}, + utils::Mutex, +}; use std::{ collections::HashMap, convert::TryInto, sync::{atomic::AtomicU32, Arc}, }; -use stratum_apps::{ - handle_result, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}, - network_helpers::noise_connection::Connection, - stratum_core::{ - binary_sv2::{self, B0255, U256}, - bitcoin::{ - block::{Header, Version}, - consensus::{deserialize, encode::serialize}, - hashes::{sha256d::Hash as DHash, Hash}, - Amount, Block, BlockHash, CompactTarget, Transaction, TxOut, Txid, - }, - codec_sv2::HandshakeRole, - common_messages_sv2::{ - Protocol, SetupConnection, SetupConnectionError, SetupConnectionSuccess, - }, - job_declaration_sv2::{DeclareMiningJob, PushSolution}, - noise_sv2::Responder, - parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}, - roles_logic_sv2::{ - handlers::job_declaration::{ParseJobDeclarationMessagesFromDownstream, SendTo}, - utils::Mutex, - }, - }, -}; use tokio::{net::TcpListener, time::Duration}; use tracing::{debug, error, info}; @@ -277,7 +273,7 @@ impl JobDeclaratorDownstream { /// Wraps the message into a `StdFrame` and sends it through the established channel. pub async fn send( self_mutex: Arc>, - message: stratum_apps::stratum_core::parsers_sv2::JobDeclaration<'static>, + message: parsers_sv2::JobDeclaration<'static>, ) -> Result<(), ()> { let sv2_frame: StdFrame = JdsMessages::JobDeclaration(message).try_into().unwrap(); let sender = self_mutex.safe_lock(|self_| self_.sender.clone()).unwrap(); diff --git a/roles/jd-server/src/lib/mempool/error.rs b/roles/jd-server/src/lib/mempool/error.rs index 15f5a84951..cb0e2a2971 100644 --- a/roles/jd-server/src/lib/mempool/error.rs +++ b/roles/jd-server/src/lib/mempool/error.rs @@ -11,8 +11,8 @@ //! It also includes a centralized error logging helper (`handle_error`) to standardize warnings //! and diagnostics across components. +use rpc_sv2::mini_rpc_client::RpcError; use std::{convert::From, sync::PoisonError}; -use stratum_apps::rpc::mini_rpc_client::RpcError; use tracing::{error, warn}; /// Errors that may occur during JDS mempool operations. diff --git a/roles/jd-server/src/lib/mempool/mod.rs b/roles/jd-server/src/lib/mempool/mod.rs index c68fedc419..866f406675 100644 --- a/roles/jd-server/src/lib/mempool/mod.rs +++ b/roles/jd-server/src/lib/mempool/mod.rs @@ -19,15 +19,11 @@ pub mod error; use super::job_declarator::AddTrasactionsToMempoolInner; use crate::mempool::error::JdsMempoolError; use async_channel::Receiver; +use bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}; use hashbrown::HashMap; +use roles_logic_sv2::utils::Mutex; +use rpc_sv2::{mini_rpc_client, mini_rpc_client::RpcError}; use std::{str::FromStr, sync::Arc}; -use stratum_apps::{ - rpc::{mini_rpc_client, mini_rpc_client::RpcError}, - stratum_core::{ - bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}, - roles_logic_sv2::utils::Mutex, - }, -}; /// Wrapper around a known transaction and its hash. #[derive(Clone, Debug)] @@ -44,7 +40,7 @@ pub struct JDsMempool { /// Auth for RPC connection to the node. auth: mini_rpc_client::Auth, /// URI of the Bitcoin node. - url: stratum_apps::rpc::Uri, + url: rpc_sv2::Uri, /// Receiver for new block solutions coming from JDC. new_block_receiver: Receiver, } @@ -72,7 +68,7 @@ impl JDsMempool { /// Instantiates a new empty mempool for JDS. pub fn new( - url: stratum_apps::rpc::Uri, + url: rpc_sv2::Uri, username: String, password: String, new_block_receiver: Receiver, diff --git a/roles/jd-server/src/lib/mod.rs b/roles/jd-server/src/lib/mod.rs index 3c04cdbf22..7fa672461a 100644 --- a/roles/jd-server/src/lib/mod.rs +++ b/roles/jd-server/src/lib/mod.rs @@ -23,20 +23,15 @@ pub mod job_declarator; pub mod mempool; pub mod status; use async_channel::{bounded, unbounded, Receiver, Sender}; +use codec_sv2::{StandardEitherFrame, StandardSv2Frame}; use config::JobDeclaratorServerConfig; use error::JdsError; use job_declarator::JobDeclarator; use mempool::error::JdsMempoolError; +use parsers_sv2::AnyMessage as JdsMessages; +use roles_logic_sv2::utils::Mutex; +pub use rpc_sv2::Uri; use std::{ops::Sub, str::FromStr, sync::Arc}; -pub use stratum_apps::rpc::Uri; -use stratum_apps::{ - handle_result, - stratum_core::{ - codec_sv2::{StandardEitherFrame, StandardSv2Frame}, - parsers_sv2::AnyMessage as JdsMessages, - roles_logic_sv2::utils::Mutex, - }, -}; use tokio::{select, task}; use tracing::{error, info, warn}; diff --git a/roles/jd-server/src/lib/status.rs b/roles/jd-server/src/lib/status.rs index ddf8d613a4..acee8a0c26 100644 --- a/roles/jd-server/src/lib/status.rs +++ b/roles/jd-server/src/lib/status.rs @@ -8,7 +8,7 @@ //! //! This allows for centralized, consistent error handling across the application. -use stratum_apps::{error_handling, stratum_core::parsers_sv2::Mining}; +use parsers_sv2::Mining; use super::error::JdsError; @@ -171,10 +171,12 @@ mod tests { use super::*; use async_channel::{bounded, RecvError}; - use stratum_apps::stratum_core::{ - binary_sv2, codec_sv2, framing_sv2, mining_sv2::OpenMiningChannelError, noise_sv2, - roles_logic_sv2, - }; + use binary_sv2; + use codec_sv2; + use framing_sv2; + use noise_sv2; + use parsers_sv2::Mining; + use roles_logic_sv2; #[tokio::test] async fn test_send_status_downstream_listener_shutdown() { @@ -428,13 +430,11 @@ mod tests { let sender = Sender::Downstream(tx); let inner: [u8; 32] = rand::random(); let value = inner.to_vec().try_into().unwrap(); - let error = JdsError::Sv2ProtocolError(( - 12, - Mining::OpenMiningChannelError(OpenMiningChannelError { - request_id: 1, - error_code: value, - }), - )); + let error_msg = mining_sv2::OpenMiningChannelError { + request_id: 1, + error_code: value, + }; + let error = JdsError::Sv2ProtocolError((12, Mining::OpenMiningChannelError(error_msg))); let error_string = "12"; handle_error(&sender, error).await; match rx.recv().await { diff --git a/roles/jd-server/src/main.rs b/roles/jd-server/src/main.rs index 762a6e5808..f17482595d 100644 --- a/roles/jd-server/src/main.rs +++ b/roles/jd-server/src/main.rs @@ -6,8 +6,8 @@ //! The actual task orchestration and shutdown logic are managed in `lib/mod.rs`. mod args; use args::process_cli_args; +use config_helpers_sv2::logging::init_logging; use jd_server::JobDeclaratorServer; -use stratum_apps::config_helpers::logging::init_logging; use tracing::error; /// Entrypoint for the Job Declarator Server binary. diff --git a/roles/test-utils/mining-device/Cargo.toml b/roles/test-utils/mining-device/Cargo.toml index baa134d812..6b766cccac 100644 --- a/roles/test-utils/mining-device/Cargo.toml +++ b/roles/test-utils/mining-device/Cargo.toml @@ -20,7 +20,23 @@ path = "src/lib/mod.rs" [dependencies] -stratum-apps = { path = "../../stratum-apps", features = ["mining_device"] } +# Using published crates from crates.io +rpc_sv2 = { version = "1.1.0" } +config_helpers_sv2 = { version = "0.1.0" } +network_helpers_sv2 = { version = "4.0.0" } +roles_logic_sv2 = { version = "5.0.0" } +# Published protocol crates to match roles_logic_sv2 v5.0.0 +binary_sv2 = { version = "4.0.0" } +parsers_sv2 = { version = "0.1" } +codec_sv2 = { version = "3.0.0" } +framing_sv2 = { version = "5.0.0" } +noise_sv2 = { version = "1.1" } +common_messages_sv2 = { version = "6.0.0" } +mining_sv2 = { version = "5.0" } +buffer_sv2 = { version = "2.0" } +# Utility crates +key-utils = { version = "1.2.0" } +bitcoin = "0.32.5" async-channel = "1.5.1" async-recursion = "0.3.2" rand = "0.8.4" diff --git a/roles/test-utils/mining-device/benches/hasher_bench.rs b/roles/test-utils/mining-device/benches/hasher_bench.rs index 7f4284eec8..0aefda4fe2 100644 --- a/roles/test-utils/mining-device/benches/hasher_bench.rs +++ b/roles/test-utils/mining-device/benches/hasher_bench.rs @@ -1,9 +1,9 @@ +use bitcoin::{ + block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, +}; use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; use mining_device::FastSha256d; use rand::{thread_rng, Rng}; -use stratum_apps::stratum_core::bitcoin::{ - block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, -}; fn random_header() -> Header { let mut rng = thread_rng(); diff --git a/roles/test-utils/mining-device/benches/microbatch_bench.rs b/roles/test-utils/mining-device/benches/microbatch_bench.rs index f5b4e88cd0..308924d969 100644 --- a/roles/test-utils/mining-device/benches/microbatch_bench.rs +++ b/roles/test-utils/mining-device/benches/microbatch_bench.rs @@ -1,10 +1,10 @@ +use bitcoin::{ + block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, +}; use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; use mining_device::{set_nonces_per_call, FastSha256d}; use rand::{thread_rng, Rng}; use std::time::Duration; -use stratum_apps::stratum_core::bitcoin::{ - block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, -}; fn random_header() -> Header { let mut rng = thread_rng(); diff --git a/roles/test-utils/mining-device/benches/scaling_bench.rs b/roles/test-utils/mining-device/benches/scaling_bench.rs index 1efda8ea99..c36ab567ba 100644 --- a/roles/test-utils/mining-device/benches/scaling_bench.rs +++ b/roles/test-utils/mining-device/benches/scaling_bench.rs @@ -1,3 +1,6 @@ +use bitcoin::{ + block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, +}; use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; use mining_device::FastSha256d; use rand::{thread_rng, Rng}; @@ -9,9 +12,6 @@ use std::{ thread, time::Instant, }; -use stratum_apps::stratum_core::bitcoin::{ - block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, -}; fn random_header() -> Header { let mut rng = thread_rng(); diff --git a/roles/test-utils/mining-device/src/lib/mod.rs b/roles/test-utils/mining-device/src/lib/mod.rs index f6b4573890..c7af0a16fe 100644 --- a/roles/test-utils/mining-device/src/lib/mod.rs +++ b/roles/test-utils/mining-device/src/lib/mod.rs @@ -1,8 +1,24 @@ #![allow(clippy::option_map_unit_fn)] use async_channel::{Receiver, Sender}; +use bitcoin::{blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget}; +use codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}; +use common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}; +use key_utils::Secp256k1PublicKey; +use mining_sv2::*; +use network_helpers_sv2::noise_connection::Connection; +use noise_sv2::Initiator; use num_format::{Locale, ToFormattedString}; +use parsers_sv2::{Mining, MiningDeviceMessages}; use primitive_types::U256; use rand::{thread_rng, Rng}; +use roles_logic_sv2::{ + errors::Error, + handlers::{ + common::ParseCommonMessagesFromUpstream, + mining::{ParseMiningMessagesFromUpstream, SendTo, SupportedChannelTypes}, + }, + utils::Mutex, +}; use std::{ net::{SocketAddr, ToSocketAddrs}, sync::{ @@ -12,35 +28,15 @@ use std::{ thread::available_parallelism, time::{Duration, Instant}, }; -use stratum_apps::{ - key_utils::Secp256k1PublicKey, - network_helpers::noise_connection::Connection, - stratum_core::{ - bitcoin::{blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget}, - codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}, - common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}, - mining_sv2::*, - noise_sv2::Initiator, - parsers_sv2::{Mining, MiningDeviceMessages}, - roles_logic_sv2::{ - errors::Error, - handlers::{ - common::ParseCommonMessagesFromUpstream, - mining::{ParseMiningMessagesFromUpstream, SendTo, SupportedChannelTypes}, - }, - utils::Mutex, - }, - }, -}; use tokio::net::TcpStream; use tracing::{debug, error, info}; // Fast SHA256d midstate hasher +use bitcoin::consensus::encode::serialize as btc_serialize; use sha2::{ compress256, digest::generic_array::{typenum::U64, GenericArray}, }; -use stratum_apps::stratum_core::bitcoin::consensus::encode::serialize as btc_serialize; // Tuneable: how many nonces to try per mining loop iteration when fast hasher is available. // Runtime-configurable so the binary and benches can adjust it without changing code. @@ -154,8 +150,9 @@ pub type StdFrame = StandardSv2Frame; pub type EitherFrame = StandardEitherFrame; struct SetupConnectionHandler {} +use bitcoin::block::Version; +use common_messages_sv2::Reconnect; use std::convert::TryInto; -use stratum_apps::stratum_core::{bitcoin::block::Version, common_messages_sv2::Reconnect}; impl SetupConnectionHandler { pub fn new() -> Self { @@ -215,11 +212,8 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_setup_connection_success( &mut self, m: SetupConnectionSuccess, - ) -> Result< - stratum_apps::stratum_core::roles_logic_sv2::handlers::common::SendTo, - stratum_apps::stratum_core::roles_logic_sv2::errors::Error, - > { - use stratum_apps::stratum_core::roles_logic_sv2::handlers::common::SendTo; + ) -> Result { + use roles_logic_sv2::handlers::common::SendTo; info!( "Received `SetupConnectionSuccess`: version={}, flags={:b}", m.used_version, m.flags @@ -229,29 +223,23 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_setup_connection_error( &mut self, - _: stratum_apps::stratum_core::common_messages_sv2::SetupConnectionError, - ) -> Result< - stratum_apps::stratum_core::roles_logic_sv2::handlers::common::SendTo, - stratum_apps::stratum_core::roles_logic_sv2::errors::Error, - > { + _: common_messages_sv2::SetupConnectionError, + ) -> Result { error!("Setup connection error"); todo!() } fn handle_channel_endpoint_changed( &mut self, - _: stratum_apps::stratum_core::common_messages_sv2::ChannelEndpointChanged, - ) -> Result< - stratum_apps::stratum_core::roles_logic_sv2::handlers::common::SendTo, - stratum_apps::stratum_core::roles_logic_sv2::errors::Error, - > { + _: common_messages_sv2::ChannelEndpointChanged, + ) -> Result { todo!() } fn handle_reconnect( &mut self, _m: Reconnect, - ) -> Result { + ) -> Result { todo!() } } @@ -377,10 +365,9 @@ impl Device { .safe_lock(|s| s.notify_changes_to_mining_thread.clone()) .unwrap(); if notify_changes_to_mining_thread.should_send - && (message_type == stratum_apps::stratum_core::mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB - || message_type - == stratum_apps::stratum_core::mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH - || message_type == stratum_apps::stratum_core::mining_sv2::MESSAGE_TYPE_SET_TARGET) + && (message_type == mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB + || message_type == mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH + || message_type == mining_sv2::MESSAGE_TYPE_SET_TARGET) { notify_changes_to_mining_thread .sender diff --git a/roles/test-utils/mining-device/tests/fast_hasher_equivalence.rs b/roles/test-utils/mining-device/tests/fast_hasher_equivalence.rs index 01e5225cf3..8e50eac875 100644 --- a/roles/test-utils/mining-device/tests/fast_hasher_equivalence.rs +++ b/roles/test-utils/mining-device/tests/fast_hasher_equivalence.rs @@ -1,8 +1,8 @@ -use mining_device::FastSha256d; -use rand::{thread_rng, Rng}; -use stratum_apps::stratum_core::bitcoin::{ +use bitcoin::{ block::Version, blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, }; +use mining_device::FastSha256d; +use rand::{thread_rng, Rng}; fn random_header() -> Header { let mut rng = thread_rng(); diff --git a/stratum-core/Cargo.toml b/stratum-core/Cargo.toml index daa524ce1d..9ba3cdd6d6 100644 --- a/stratum-core/Cargo.toml +++ b/stratum-core/Cargo.toml @@ -15,13 +15,13 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"] buffer_sv2 = { path = "../utils/buffer", version = "^2.0.0" } bitcoin = "0.32.5" binary_sv2 = { path = "../protocols/v2/binary-sv2", version = "^4.0.0" } -codec_sv2 = { path = "../protocols/v2/codec-sv2", version = "^4.0.0" } +codec_sv2 = { path = "../protocols/v2/codec-sv2", version = "^4.0.0", features = ["noise_sv2"] } framing_sv2 = { path = "../protocols/v2/framing-sv2", version = "^5.0.0" } noise_sv2 = { path = "../protocols/v2/noise-sv2", version = "^1.0.0" } parsers_sv2 = { path = "../protocols/v2/parsers-sv2", version = "^0.1.0" } handlers_sv2 = { path = "../protocols/v2/handlers-sv2", version = "^0.2.0" } channels_sv2 = { path = "../protocols/v2/channels-sv2", version = "^2.0.0" } -roles_logic_sv2 = { path = "../protocols/v2/roles-logic-sv2", version = "5.0.0" } +#roles_logic_sv2 = { path = "../protocols/v2/roles-logic-sv2", version = "5.0.0" } common_messages_sv2 = { path = "../protocols/v2/subprotocols/common-messages", version = "^6.0.0" } mining_sv2 = { path = "../protocols/v2/subprotocols/mining", version = "^5.0.0" } template_distribution_sv2 = { path = "../protocols/v2/subprotocols/template-distribution", version = "^4.0.0" } diff --git a/stratum-core/src/lib.rs b/stratum-core/src/lib.rs index 19406a8367..3b92faa2e1 100644 --- a/stratum-core/src/lib.rs +++ b/stratum-core/src/lib.rs @@ -21,7 +21,7 @@ pub use job_declaration_sv2; pub use mining_sv2; pub use noise_sv2; pub use parsers_sv2; -pub use roles_logic_sv2; +//pub use roles_logic_sv2; #[cfg(feature = "translation")] pub use stratum_translation; #[cfg(feature = "sv1")] diff --git a/test/integration-tests/Cargo.lock b/test/integration-tests/Cargo.lock index 7d8641a019..0dcb37133c 100644 --- a/test/integration-tests/Cargo.lock +++ b/test/integration-tests/Cargo.lock @@ -246,19 +246,44 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d965446196e3b7decd44aa7ee49e31d630118f90ef12f97900f262eb915c951d" +[[package]] +name = "binary_codec_sv2" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ad24342e0abdcc463ad6ad4ac7b0ec606122c11eddf92de186a657df0114eb7" + [[package]] name = "binary_codec_sv2" version = "3.0.0" dependencies = [ - "buffer_sv2", + "buffer_sv2 2.0.0", +] + +[[package]] +name = "binary_codec_sv2" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16415a0a9ccee2f71820da352c1f2a7f16d9f8e3ae6fb5e97834c6d732e98cd" +dependencies = [ + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "binary_sv2" +version = "4.0.0" +dependencies = [ + "binary_codec_sv2 3.0.0", + "derive_codec_sv2 1.1.1", ] [[package]] name = "binary_sv2" version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8295945d51b707f3a49e17810dddef858549e2b52383c7f2c4dd036f6bc1e6" dependencies = [ - "binary_codec_sv2", - "derive_codec_sv2", + "binary_codec_sv2 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "derive_codec_sv2 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -397,6 +422,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "buffer_sv2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19781425841d2e217eb7ded68089b693b47c8f756eb02231c92122dbf505bcf0" +dependencies = [ + "aes-gcm", +] + [[package]] name = "byte-slice-cast" version = "1.2.3" @@ -455,17 +489,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "channels_sv2" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ac02b93b5bd92a7dda2bc4b8c9d1f087e1fffc8b1018b532109135629051fc" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing", +] + [[package]] name = "channels_sv2" version = "2.0.0" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin", - "common_messages_sv2", - "job_declaration_sv2", - "mining_sv2", + "common_messages_sv2 6.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", "primitive-types", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1", "tracing", ] @@ -520,14 +570,28 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +[[package]] +name = "codec_sv2" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e6d43e79e66d0f98038922157db8b6101594921be87ac2cca3754d669f2a05" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.8.5", + "tracing", +] + [[package]] name = "codec_sv2" version = "4.0.0" dependencies = [ - "binary_sv2", - "buffer_sv2", - "framing_sv2", - "noise_sv2", + "binary_sv2 4.0.0", + "buffer_sv2 2.0.0", + "framing_sv2 5.0.1", + "noise_sv2 1.4.0", "rand 0.8.5", "tracing", ] @@ -542,7 +606,16 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" name = "common_messages_sv2" version = "6.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "common_messages_sv2" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6ec6ab527aeebf8ead273d6ab712ff181c050ee5e1082f3f6a2c65c0a10bf6" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -573,6 +646,18 @@ dependencies = [ "yaml-rust2", ] +[[package]] +name = "config_helpers_sv2" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3307b494a63dab36d0bec2b1e830b6568f53300aaa9516ac673a434e799ae" +dependencies = [ + "miniscript", + "serde", + "tracing", + "tracing-subscriber", +] + [[package]] name = "const-random" version = "0.1.18" @@ -731,7 +816,16 @@ dependencies = [ name = "derive_codec_sv2" version = "1.1.1" dependencies = [ - "binary_codec_sv2", + "binary_codec_sv2 3.0.0", +] + +[[package]] +name = "derive_codec_sv2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924f288d967a5cd37956b195269ee7f710999169895cf670a736e1b2267d6137" +dependencies = [ + "binary_codec_sv2 1.2.0", ] [[package]] @@ -787,6 +881,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error_handling" +version = "1.0.0" + +[[package]] +name = "error_handling" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdf3be9049288001eb8a37f21b0f4e922598a6fa0098630fd3a6a14459ef217" + [[package]] name = "event-listener" version = "2.5.3" @@ -849,9 +953,20 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" name = "framing_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", - "buffer_sv2", - "noise_sv2", + "binary_sv2 4.0.0", + "buffer_sv2 2.0.0", + "noise_sv2 1.4.0", +] + +[[package]] +name = "framing_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6543955264144174b93780e0e76623ee4293037c9e180cfde3e2c155b59fa9" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1017,16 +1132,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "handlers_sv2" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "472824f98b68a963dbf4c77625a8b5525c322abe49afa9403dfb816e35dd4d93" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "trait-variant", +] + [[package]] name = "handlers_sv2" version = "0.2.0" dependencies = [ - "binary_sv2", - "common_messages_sv2", - "job_declaration_sv2", - "mining_sv2", - "parsers_sv2", - "template_distribution_sv2", + "binary_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "parsers_sv2 0.1.1", + "template_distribution_sv2 4.0.1", "trait-variant", ] @@ -1250,6 +1380,7 @@ dependencies = [ "flate2", "jd_client_sv2", "jd_server", + "key-utils 1.2.0", "mining_device", "minreq", "once_cell", @@ -1300,6 +1431,7 @@ dependencies = [ "async-channel", "clap", "config", + "key-utils 1.2.0", "serde", "stratum-apps", "tokio", @@ -1311,15 +1443,29 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", + "config_helpers_sv2", + "error_handling 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", "nohash-hasher", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.8.5", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "serde", "serde_json", - "stratum-apps", "tokio", "tracing", ] @@ -1328,7 +1474,16 @@ dependencies = [ name = "job_declaration_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "job_declaration_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d4edc436d29e8dcac178539222de2b3681d629f9884191bd7db8831e49dd24" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1354,6 +1509,31 @@ dependencies = [ "serde_json", ] +[[package]] +name = "key-utils" +version = "1.2.0" +dependencies = [ + "bs58", + "generic-array", + "rand 0.8.5", + "rustversion", + "secp256k1 0.28.2", + "serde", +] + +[[package]] +name = "key-utils" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe8551792fd4461e519fdfd8b8f334d1bf480250786fd202baf418854ff7130" +dependencies = [ + "bs58", + "rand 0.8.5", + "rustversion", + "secp256k1 0.28.2", + "serde", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1425,13 +1605,26 @@ version = "0.1.3" dependencies = [ "async-channel", "async-recursion", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", + "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "config_helpers_sv2", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", + "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-format", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", "rand 0.8.5", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "sha2 0.10.9", - "stratum-apps", "tokio", "tracing", "tracing-subscriber", @@ -1441,7 +1634,16 @@ dependencies = [ name = "mining_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "mining_sv2" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1eb3c055232f64d36e3eee4296adcaa584fb3185a57e0de11ad5807766c45edc" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1490,6 +1692,19 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "network_helpers_sv2" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d720d6a31532fb4f08e59b71669084d06462f42e9d2c2aede7368d221d36db" +dependencies = [ + "async-channel", + "codec_sv2 3.0.1", + "futures", + "tokio", + "tracing", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -1508,6 +1723,19 @@ dependencies = [ "secp256k1 0.28.2", ] +[[package]] +name = "noise_sv2" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30964f9fbc4572bb5a1b0046176331d20e9ce6de0ca18afc3cfd42c6e91a94aa" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "rand 0.8.5", + "rand_chacha 0.3.1", + "secp256k1 0.28.2", +] + [[package]] name = "nom" version = "7.1.3" @@ -1629,12 +1857,26 @@ dependencies = [ name = "parsers_sv2" version = "0.1.1" dependencies = [ - "binary_sv2", - "common_messages_sv2", - "framing_sv2", - "job_declaration_sv2", - "mining_sv2", - "template_distribution_sv2", + "binary_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "framing_sv2 5.0.1", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "template_distribution_sv2 4.0.1", +] + +[[package]] +name = "parsers_sv2" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109e80bc77241a729f61cad15f3f246f3de12e1b741b31e419fc7e02f20c2ccb" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1736,6 +1978,8 @@ dependencies = [ "async-channel", "clap", "config", + "error_handling 1.0.0", + "key-utils 1.2.0", "rand 0.8.5", "secp256k1 0.28.2", "serde", @@ -1902,24 +2146,48 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roles_logic_sv2" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7241840512841396df29ede2094619ad06cbbd1a0dc342553c7a5901506d096b" +dependencies = [ + "bitcoin", + "chacha20poly1305", + "channels_sv2 1.0.2", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "handlers_sv2 0.1.0", + "hex-conservative 0.3.0", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "nohash-hasher", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing", +] + [[package]] name = "roles_logic_sv2" version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88850ead16993f86cb4616d154ddd37b9c0d739ea23711b1cc51f40484e0e39a" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitcoin", "chacha20poly1305", - "channels_sv2", - "codec_sv2", - "common_messages_sv2", - "handlers_sv2", + "channels_sv2 1.0.2", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "handlers_sv2 0.1.0", "hex-conservative 0.3.0", - "job_declaration_sv2", - "mining_sv2", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "nohash-hasher", - "parsers_sv2", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "tracing", ] @@ -1935,6 +2203,22 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rpc_sv2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9b3a6c43d03c5cc6ca9f40797cbf17a9a30b8db236be6c87f5243bd404d6af" +dependencies = [ + "base64 0.21.7", + "hex", + "http-body-util", + "hyper", + "hyper-util", + "serde", + "serde_json", + "stratum-common", +] + [[package]] name = "rust-ini" version = "0.20.0" @@ -2209,16 +2493,11 @@ name = "stratum-apps" version = "0.1.0" dependencies = [ "async-channel", - "base64 0.21.7", - "bs58", "clap", "config", + "error_handling 1.0.0", "futures", - "generic-array", - "hex", - "http-body-util", - "hyper", - "hyper-util", + "key-utils 1.2.0", "miniscript", "rand 0.8.5", "rustversion", @@ -2232,35 +2511,43 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "stratum-common" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77b7dc7a762d19aba6f355599a61440b29603ceece5a158914888691b9867ebe" +dependencies = [ + "roles_logic_sv2 4.0.0", +] + [[package]] name = "stratum-core" version = "0.1.0" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin", - "buffer_sv2", - "channels_sv2", - "codec_sv2", - "common_messages_sv2", - "framing_sv2", - "handlers_sv2", - "job_declaration_sv2", - "mining_sv2", - "noise_sv2", - "parsers_sv2", - "roles_logic_sv2", + "buffer_sv2 2.0.0", + "channels_sv2 2.0.0", + "codec_sv2 4.0.0", + "common_messages_sv2 6.0.1", + "framing_sv2 5.0.1", + "handlers_sv2 0.2.0", + "job_declaration_sv2 5.0.1", + "mining_sv2 5.0.1", + "noise_sv2 1.4.0", + "parsers_sv2 0.1.1", "stratum_translation", "sv1_api", - "template_distribution_sv2", + "template_distribution_sv2 4.0.1", ] [[package]] name = "stratum_translation" version = "0.1.0" dependencies = [ - "binary_sv2", - "channels_sv2", - "mining_sv2", + "binary_sv2 4.0.0", + "channels_sv2 2.0.0", + "mining_sv2 5.0.1", "sv1_api", "tracing", ] @@ -2281,7 +2568,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" name = "sv1_api" version = "2.1.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", "bitcoin_hashes 0.3.2", "byteorder", "hex", @@ -2365,7 +2652,16 @@ dependencies = [ name = "template_distribution_sv2" version = "4.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", +] + +[[package]] +name = "template_distribution_sv2" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6298fc9f339b1c3b654ef3590857d5d3eff6d709891f003b7f7a701b8a64a3a4" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2607,6 +2903,7 @@ dependencies = [ "async-channel", "clap", "config", + "key-utils 1.2.0", "serde", "serde_json", "stratum-apps", diff --git a/utils/Cargo.lock b/utils/Cargo.lock index 4c12cd360d..e815a16e45 100644 --- a/utils/Cargo.lock +++ b/utils/Cargo.lock @@ -94,9 +94,6 @@ checksum = "d965446196e3b7decd44aa7ee49e31d630118f90ef12f97900f262eb915c951d" [[package]] name = "binary_codec_sv2" version = "3.0.0" -dependencies = [ - "buffer_sv2", -] [[package]] name = "binary_sv2" @@ -429,7 +426,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", - "rand_core", "typenum", ] @@ -505,7 +501,6 @@ name = "framing_sv2" version = "5.0.1" dependencies = [ "binary_sv2", - "buffer_sv2", "noise_sv2", ] @@ -611,15 +606,6 @@ dependencies = [ "arrayvec", ] -[[package]] -name = "hex-conservative" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4afe881d0527571892c4034822e59bb10c6c991cce6abe8199b6f5cf10766f55" -dependencies = [ - "arrayvec", -] - [[package]] name = "hex_lit" version = "0.1.1" @@ -734,12 +720,6 @@ dependencies = [ "binary_sv2", ] -[[package]] -name = "nohash-hasher" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" - [[package]] name = "noise_sv2" version = "1.4.0" @@ -1008,27 +988,6 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" -[[package]] -name = "roles_logic_sv2" -version = "5.0.0" -dependencies = [ - "binary_sv2", - "bitcoin", - "chacha20poly1305", - "channels_sv2", - "codec_sv2", - "common_messages_sv2", - "handlers_sv2", - "hex-conservative 0.3.0", - "job_declaration_sv2", - "mining_sv2", - "nohash-hasher", - "parsers_sv2", - "primitive-types", - "template_distribution_sv2", - "tracing", -] - [[package]] name = "rustc-hex" version = "2.1.0" @@ -1175,7 +1134,6 @@ dependencies = [ "mining_sv2", "noise_sv2", "parsers_sv2", - "roles_logic_sv2", "template_distribution_sv2", ] From 413fc7d745526b8ec9e503a8a85cb42a861263d8 Mon Sep 17 00:00:00 2001 From: Lucas Balieiro Date: Thu, 16 Oct 2025 13:52:48 -0400 Subject: [PATCH 4/5] [WIP] fix the errors on apps to make integration buildable --- roles/Cargo.lock | 149 +--------- roles/jd-client/Cargo.toml | 2 +- .../downstream_message_handler.rs | 152 ++++++---- .../jd-client/src/lib/channel_manager/mod.rs | 6 +- .../upstream_message_handler.rs | 237 ++++++++------- roles/jd-client/src/lib/downstream/mod.rs | 2 +- roles/jd-client/src/lib/error.rs | 11 +- roles/jd-client/src/lib/job_declarator/mod.rs | 6 +- .../src/lib/template_receiver/mod.rs | 5 +- roles/jd-client/src/lib/upstream/mod.rs | 6 +- roles/jd-server/Cargo.toml | 19 +- roles/jd-server/src/lib/config.rs | 8 +- roles/jd-server/src/lib/error.rs | 10 +- .../src/lib/job_declarator/message_handler.rs | 10 +- roles/jd-server/src/lib/job_declarator/mod.rs | 26 +- roles/jd-server/src/lib/mempool/error.rs | 2 +- roles/jd-server/src/lib/mempool/mod.rs | 8 +- roles/jd-server/src/lib/mod.rs | 7 +- roles/jd-server/src/lib/status.rs | 79 ++--- roles/pool/Cargo.toml | 2 +- roles/pool/src/lib/channel_manager/mod.rs | 7 +- roles/pool/src/lib/config.rs | 1 - roles/pool/src/lib/downstream/mod.rs | 2 +- roles/pool/src/lib/error.rs | 31 +- roles/stratum-apps/Cargo.toml | 9 +- roles/stratum-apps/src/custom_mutex.rs | 117 ++++++++ roles/stratum-apps/src/errors.rs | 276 ++++++++++++++++++ roles/stratum-apps/src/lib.rs | 5 +- roles/test-utils/mining-device/Cargo.toml | 23 +- roles/test-utils/mining-device/src/lib/mod.rs | 35 ++- roles/translator/src/lib/error.rs | 17 +- .../translator/src/lib/sv1/downstream/data.rs | 10 +- .../src/lib/sv1/downstream/downstream.rs | 14 +- .../lib/sv1/sv1_server/difficulty_manager.rs | 16 +- .../src/lib/sv1/sv1_server/sv1_server.rs | 2 +- .../sv2/channel_manager/channel_manager.rs | 16 +- .../src/lib/sv2/channel_manager/data.rs | 8 +- .../sv2/channel_manager/message_handler.rs | 3 +- roles/translator/src/lib/utils.rs | 34 ++- test/integration-tests/Cargo.lock | 57 +--- test/integration-tests/Cargo.toml | 2 +- .../lib/message_aggregator.rs | 3 +- test/integration-tests/lib/mod.rs | 6 +- test/integration-tests/lib/utils.rs | 2 +- 44 files changed, 847 insertions(+), 596 deletions(-) create mode 100644 roles/stratum-apps/src/custom_mutex.rs create mode 100644 roles/stratum-apps/src/errors.rs diff --git a/roles/Cargo.lock b/roles/Cargo.lock index f2279dd026..bbea2ae658 100644 --- a/roles/Cargo.lock +++ b/roles/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -886,18 +886,6 @@ dependencies = [ "yaml-rust2", ] -[[package]] -name = "config_helpers_sv2" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3307b494a63dab36d0bec2b1e830b6568f53300aaa9516ac673a434e799ae" -dependencies = [ - "miniscript", - "serde", - "tracing", - "tracing-subscriber", -] - [[package]] name = "const-random" version = "0.1.18" @@ -1139,16 +1127,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - -[[package]] -name = "error_handling" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfdf3be9049288001eb8a37f21b0f4e922598a6fa0098630fd3a6a14459ef217" - [[package]] name = "event-listener" version = "2.5.3" @@ -1774,7 +1752,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "key-utils 1.2.0", "serde", "stratum-apps", "tokio", @@ -1786,29 +1763,16 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel 1.9.0", - "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bitcoin", "clap", - "codec_sv2 3.0.1", - "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", - "config_helpers_sv2", - "error_handling 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", - "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "network_helpers_sv2", "nohash-hasher", - "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand", - "roles_logic_sv2 5.0.0", - "rpc_sv2", + "roles_logic_sv2", "serde", "serde_json", + "stratum-apps", "tokio", "tracing", ] @@ -1850,31 +1814,6 @@ dependencies = [ "serde", ] -[[package]] -name = "key-utils" -version = "1.2.0" -dependencies = [ - "bs58", - "generic-array", - "rand", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - -[[package]] -name = "key-utils" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe8551792fd4461e519fdfd8b8f334d1bf480250786fd202baf418854ff7130" -dependencies = [ - "bs58", - "rand", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - [[package]] name = "kv-log-macro" version = "1.0.7" @@ -1959,29 +1898,17 @@ version = "0.1.3" dependencies = [ "async-channel 1.9.0", "async-recursion", - "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bitcoin", - "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap", - "codec_sv2 3.0.1", - "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "config_helpers_sv2", "criterion", - "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", "half", - "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "network_helpers_sv2", - "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-format", "num_cpus", - "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", "rand", - "roles_logic_sv2 5.0.0", - "rpc_sv2", + "roles_logic_sv2", "sha2 0.10.9", + "stratum-apps", "tokio", "tracing", "tracing-subscriber", @@ -2033,19 +1960,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "network_helpers_sv2" -version = "4.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05d720d6a31532fb4f08e59b71669084d06462f42e9d2c2aede7368d221d36db" -dependencies = [ - "async-channel 1.9.0", - "codec_sv2 3.0.1", - "futures", - "tokio", - "tracing", -] - [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2391,8 +2305,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "error_handling 1.0.0", - "key-utils 1.2.0", "rand", "secp256k1 0.28.2", "serde", @@ -2544,29 +2456,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "roles_logic_sv2" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88850ead16993f86cb4616d154ddd37b9c0d739ea23711b1cc51f40484e0e39a" -dependencies = [ - "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bitcoin", - "chacha20poly1305", - "channels_sv2 1.0.2", - "codec_sv2 3.0.1", - "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "handlers_sv2 0.1.0", - "hex-conservative 0.3.0", - "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "nohash-hasher", - "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "primitive-types", - "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tracing", -] - [[package]] name = "ron" version = "0.8.1" @@ -2579,22 +2468,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "rpc_sv2" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af9b3a6c43d03c5cc6ca9f40797cbf17a9a30b8db236be6c87f5243bd404d6af" -dependencies = [ - "base64 0.21.7", - "hex", - "http-body-util", - "hyper", - "hyper-util", - "serde", - "serde_json", - "stratum-common", -] - [[package]] name = "rust-ini" version = "0.20.0" @@ -2897,14 +2770,12 @@ dependencies = [ "bs58", "clap", "config", - "error_handling 1.0.0", "futures", "generic-array", "hex", "http-body-util", "hyper", "hyper-util", - "key-utils 1.2.0", "miniscript", "rand", "rustversion", @@ -2918,15 +2789,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "stratum-common" -version = "4.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77b7dc7a762d19aba6f355599a61440b29603ceece5a158914888691b9867ebe" -dependencies = [ - "roles_logic_sv2 4.0.0", -] - [[package]] name = "stratum-core" version = "0.1.0" @@ -3297,7 +3159,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "key-utils 1.2.0", "serde", "serde_json", "sha2 0.10.9", diff --git a/roles/jd-client/Cargo.toml b/roles/jd-client/Cargo.toml index 46b41dedf5..a161bdce71 100644 --- a/roles/jd-client/Cargo.toml +++ b/roles/jd-client/Cargo.toml @@ -22,4 +22,4 @@ serde = { version = "1.0.89", default-features = false, features = ["derive", "a tokio = { version = "1.44.1", features = ["full"] } ext-config = { version = "0.14.0", features = ["toml"], package = "config" } tracing = { version = "0.1" } -clap = { version = "4.5.39", features = ["derive"] } \ No newline at end of file +clap = { version = "4.5.39", features = ["derive"] } diff --git a/roles/jd-client/src/lib/channel_manager/downstream_message_handler.rs b/roles/jd-client/src/lib/channel_manager/downstream_message_handler.rs index 42c2c575d2..360a5a7b8c 100644 --- a/roles/jd-client/src/lib/channel_manager/downstream_message_handler.rs +++ b/roles/jd-client/src/lib/channel_manager/downstream_message_handler.rs @@ -1,27 +1,29 @@ use std::sync::atomic::Ordering; -use stratum_apps::stratum_core::{ - binary_sv2::Str0255, - bitcoin::Amount, - channels_sv2::{ - client, - outputs::deserialize_outputs, - server::{ - error::{ExtendedChannelError, StandardChannelError}, - extended::ExtendedChannel, - group::GroupChannel, - jobs::job_store::DefaultJobStore, - share_accounting::{ShareValidationError, ShareValidationResult}, - standard::StandardChannel, +use stratum_apps::{ + errors::Error, + stratum_core::{ + binary_sv2::Str0255, + bitcoin::Amount, + channels_sv2::{ + client, + outputs::deserialize_outputs, + server::{ + error::{ExtendedChannelError, StandardChannelError}, + extended::ExtendedChannel, + group::GroupChannel, + jobs::job_store::DefaultJobStore, + share_accounting::{ShareValidationError, ShareValidationResult}, + standard::StandardChannel, + }, + Vardiff, VardiffState, }, - Vardiff, VardiffState, + handlers_sv2::{HandleMiningMessagesFromClientAsync, SupportedChannelTypes}, + job_declaration_sv2::PushSolution, + mining_sv2::*, + parsers_sv2::{AnyMessage, JobDeclaration, Mining, TemplateDistribution}, + template_distribution_sv2::SubmitSolution, }, - handlers_sv2::{HandleMiningMessagesFromClientAsync, SupportedChannelTypes}, - job_declaration_sv2::PushSolution, - mining_sv2::*, - parsers_sv2::{AnyMessage, JobDeclaration, Mining, TemplateDistribution}, - roles_logic_sv2, - template_distribution_sv2::SubmitSolution, }; use tracing::{debug, error, info, warn}; @@ -265,36 +267,47 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { let mut messages: Vec = vec![]; if !data.require_std_job && data.group_channels.is_none() { - let group_channel_id = channel_manager_data.channel_id_factory.fetch_add(1, Ordering::Relaxed); + let group_channel_id = channel_manager_data + .channel_id_factory + .fetch_add(1, Ordering::Relaxed); let job_store = DefaultJobStore::new(); - let full_extranonce_size = channel_manager_data.upstream_channel.as_ref().map(|channel| channel.get_full_extranonce_size()).unwrap_or(32); - let mut group_channel = match GroupChannel::new_for_job_declaration_client( - group_channel_id, - job_store, - full_extranonce_size, - channel_manager_data.pool_tag_string.clone(), - self.miner_tag_string.clone(), - ) { - Ok(channel) => channel, - Err(e) => { - error!(?e, "Failed to create group channel"); - return Err(JDCError::FailedToCreateGroupChannel(e)); - } - }; + let full_extranonce_size = channel_manager_data + .upstream_channel + .as_ref() + .map(|channel| channel.get_full_extranonce_size()) + .unwrap_or(32); + let mut group_channel = + match GroupChannel::new_for_job_declaration_client( + group_channel_id, + job_store, + full_extranonce_size, + channel_manager_data.pool_tag_string.clone(), + self.miner_tag_string.clone(), + ) { + Ok(channel) => channel, + Err(e) => { + error!(?e, "Failed to create group channel"); + return Err(JDCError::FailedToCreateGroupChannel(e)); + } + }; if let Err(e) = group_channel.on_new_template( last_future_template.clone(), coinbase_outputs.clone(), ) { error!(?e, "Failed to apply template to group channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessNewTemplateGroupChannel(e))); + return Err(JDCError::RolesSv2Logic( + Error::FailedToProcessNewTemplateGroupChannel(e), + )); } if let Err(e) = group_channel.on_set_new_prev_hash(last_new_prev_hash.clone()) { error!(?e, "Failed to apply prevhash to group channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessSetNewPrevHashGroupChannel(e))); + return Err(JDCError::RolesSv2Logic( + Error::FailedToProcessSetNewPrevHashGroupChannel(e), + )); }; data.group_channels = Some(group_channel); @@ -308,7 +321,9 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { .as_ref() .map(|gc| gc.get_group_channel_id()) .unwrap_or(0); - let standard_channel_id = channel_manager_data.channel_id_factory.fetch_add(1, Ordering::Relaxed); + let standard_channel_id = channel_manager_data + .channel_id_factory + .fetch_add(1, Ordering::Relaxed); let extranonce_prefix = match channel_manager_data .extranonce_prefix_factory_standard @@ -317,7 +332,9 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { Ok(p) => p, Err(e) => { error!(?e, "Failed to get extranonce prefix"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::ExtranoncePrefixFactoryError(e))); + return Err(JDCError::RolesSv2Logic( + Error::ExtranoncePrefixFactoryError(e), + )); } }; @@ -339,18 +356,22 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { Err(e) => { error!(?e, "Failed to create standard channel"); return match e { - StandardChannelError::InvalidNominalHashrate => { - Ok(vec![(downstream_id, build_error("invalid-nominal-hashrate")).into()]) - } + StandardChannelError::InvalidNominalHashrate => Ok(vec![( + downstream_id, + build_error("invalid-nominal-hashrate"), + ) + .into()]), StandardChannelError::RequestedMaxTargetOutOfRange => { - Ok(vec![(downstream_id, build_error("max-target-out-of-range")).into()]) - } - other => Err( - JDCError::RolesSv2Logic( - roles_logic_sv2::Error::FailedToCreateStandardChannel(other) + Ok(vec![( + downstream_id, + build_error("max-target-out-of-range"), ) - ), - } + .into()]) + } + other => Err(JDCError::RolesSv2Logic( + Error::FailedToCreateStandardChannel(other), + )), + }; } }; @@ -382,7 +403,9 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { .on_new_template(last_future_template.clone(), coinbase_outputs.clone()) { error!(?e, "Failed to apply template to standard channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessNewTemplateStandardChannel(e))); + return Err(JDCError::RolesSv2Logic( + Error::FailedToProcessNewTemplateStandardChannel(e), + )); } let future_standard_job_id = standard_channel @@ -422,7 +445,9 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { standard_channel.on_set_new_prev_hash(last_new_prev_hash.clone()) { error!(?e, "Failed to apply prevhash to standard channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessSetNewPrevHashStandardChannel(e))); + return Err(JDCError::RolesSv2Logic( + Error::FailedToProcessSetNewPrevHashStandardChannel(e), + )); } messages.push( ( @@ -432,15 +457,24 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { .into(), ); - let vardiff = VardiffState::new().expect("Vardiff state should instantiate."); + let vardiff = + VardiffState::new().expect("Vardiff state should instantiate."); - channel_manager_data.vardiff.insert((standard_channel_id, downstream_id),vardiff); - data.standard_channels.insert(standard_channel_id, standard_channel); + channel_manager_data + .vardiff + .insert((standard_channel_id, downstream_id), vardiff); + data.standard_channels + .insert(standard_channel_id, standard_channel); channel_manager_data .channel_id_to_downstream_id .insert(standard_channel_id, downstream_id); - channel_manager_data.downstream_channel_id_and_job_id_to_template_id.insert((standard_channel_id, future_standard_job_id), last_future_template.template_id); + channel_manager_data + .downstream_channel_id_and_job_id_to_template_id + .insert( + (standard_channel_id, future_standard_job_id), + last_future_template.template_id, + ); if let Some(group_channel) = data.group_channels.as_mut() { group_channel.add_standard_channel_id(standard_channel_id); } @@ -525,7 +559,7 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { Ok(p) => p, Err(e) => { error!(?e, "Extranonce prefix error"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::ExtranoncePrefixFactoryError(e))); + return Err(JDCError::RolesSv2Logic(Error::ExtranoncePrefixFactoryError(e))); } }; @@ -570,7 +604,7 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { } other => Err( JDCError::RolesSv2Logic( - roles_logic_sv2::Error::FailedToCreateExtendedChannel(other) + Error::FailedToCreateExtendedChannel(other) ) ), } @@ -611,7 +645,7 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { extended_channel.on_new_template(last_future_template.clone(), coinbase_outputs) { error!(?e, "Failed to apply template to extended channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessNewTemplateExtendedChannel(e))); + return Err(JDCError::RolesSv2Logic(Error::FailedToProcessNewTemplateExtendedChannel(e))); } let future_extended_job_id = extended_channel @@ -649,7 +683,7 @@ impl HandleMiningMessagesFromClientAsync for ChannelManager { }; if let Err(e) = extended_channel.on_set_new_prev_hash(last_new_prev_hash) { error!(?e, "Failed to set prevhash on extended channel"); - return Err(JDCError::RolesSv2Logic(roles_logic_sv2::Error::FailedToProcessSetNewPrevHashExtendedChannel(e))); + return Err(JDCError::RolesSv2Logic(Error::FailedToProcessSetNewPrevHashExtendedChannel(e))); } messages.push(( downstream_id, diff --git a/roles/jd-client/src/lib/channel_manager/mod.rs b/roles/jd-client/src/lib/channel_manager/mod.rs index 096eac4e4b..d614e43e2a 100644 --- a/roles/jd-client/src/lib/channel_manager/mod.rs +++ b/roles/jd-client/src/lib/channel_manager/mod.rs @@ -1,3 +1,4 @@ +use async_channel::{Receiver, Sender}; use std::{ collections::{HashMap, VecDeque}, net::SocketAddr, @@ -6,9 +7,8 @@ use std::{ Arc, }, }; - -use async_channel::{Receiver, Sender}; use stratum_apps::{ + custom_mutex::Mutex, key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ @@ -38,10 +38,10 @@ use stratum_apps::{ }, noise_sv2::Responder, parsers_sv2::{AnyMessage, JobDeclaration, Mining}, - roles_logic_sv2::utils::Mutex, template_distribution_sv2::{NewTemplate, SetNewPrevHash as SetNewPrevHashTdp}, }, }; + use tokio::{net::TcpListener, select, sync::broadcast}; use tracing::{debug, error, info, warn}; diff --git a/roles/jd-client/src/lib/channel_manager/upstream_message_handler.rs b/roles/jd-client/src/lib/channel_manager/upstream_message_handler.rs index ed3208f6ae..f1cfc53252 100644 --- a/roles/jd-client/src/lib/channel_manager/upstream_message_handler.rs +++ b/roles/jd-client/src/lib/channel_manager/upstream_message_handler.rs @@ -1,15 +1,16 @@ use std::sync::atomic::Ordering; - -use stratum_apps::stratum_core::{ - channels_sv2::{ - client::extended::ExtendedChannel, outputs::deserialize_outputs, - server::jobs::factory::JobFactory, +use stratum_apps::{ + errors::Error, + stratum_core::{ + channels_sv2::{ + client::extended::ExtendedChannel, outputs::deserialize_outputs, + server::jobs::factory::JobFactory, + }, + handlers_sv2::{HandleMiningMessagesFromServerAsync, SupportedChannelTypes}, + mining_sv2::*, + parsers_sv2::{AnyMessage, Mining, TemplateDistribution}, + template_distribution_sv2::RequestTransactionData, }, - handlers_sv2::{HandleMiningMessagesFromServerAsync, SupportedChannelTypes}, - mining_sv2::*, - parsers_sv2::{AnyMessage, Mining, TemplateDistribution}, - roles_logic_sv2, - template_distribution_sv2::RequestTransactionData, }; use tracing::{debug, error, info, warn}; @@ -335,122 +336,142 @@ impl HandleMiningMessagesFromServerAsync for ChannelManager { msg: SetExtranoncePrefix<'_>, ) -> Result<(), Self::Error> { info!("Received: {}", msg); - let messages_results = self - .channel_manager_data - .super_safe_lock(|channel_manager_data| { - let mut messages_results: Vec> = vec![]; - if let Some(upstream_channel) = channel_manager_data.upstream_channel.as_mut() { - if let Err(_e) = - upstream_channel.set_extranonce_prefix(msg.extranonce_prefix.to_vec()) - { - // Correct these errors, we need Extended Channel Error but on client side. - return Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::BadPayloadSize), - ); - } + let messages_results = + self.channel_manager_data + .super_safe_lock(|channel_manager_data| { + let mut messages_results: Vec> = vec![]; + if let Some(upstream_channel) = channel_manager_data.upstream_channel.as_mut() { + if let Err(_e) = + upstream_channel.set_extranonce_prefix(msg.extranonce_prefix.to_vec()) + { + // Correct these errors, we need Extended Channel Error but on client + // side. + return Err(JDCError::RolesSv2Logic(Error::BadPayloadSize)); + } - let new_prefix_len = msg.extranonce_prefix.len(); - let rollable_extranonce_size = upstream_channel.get_rollable_extranonce_size(); - let full_extranonce_size = new_prefix_len + rollable_extranonce_size as usize; - if full_extranonce_size > MAX_EXTRANONCE_LEN { - return Err(JDCError::ExtranonceSizeTooLarge); - } + let new_prefix_len = msg.extranonce_prefix.len(); + let rollable_extranonce_size = + upstream_channel.get_rollable_extranonce_size(); + let full_extranonce_size = + new_prefix_len + rollable_extranonce_size as usize; + if full_extranonce_size > MAX_EXTRANONCE_LEN { + return Err(JDCError::ExtranonceSizeTooLarge); + } - let range_0 = 0..new_prefix_len; - let range_1 = new_prefix_len..new_prefix_len + JDC_SEARCH_SPACE_BYTES; - let range_2 = new_prefix_len + JDC_SEARCH_SPACE_BYTES..full_extranonce_size; + let range_0 = 0..new_prefix_len; + let range_1 = new_prefix_len..new_prefix_len + JDC_SEARCH_SPACE_BYTES; + let range_2 = new_prefix_len + JDC_SEARCH_SPACE_BYTES..full_extranonce_size; - debug!( - new_prefix_len, - rollable_extranonce_size, - full_extranonce_size, - "Calculated extranonce ranges" - ); - let extranonces = match ExtendedExtranonce::from_upstream_extranonce( - msg.extranonce_prefix.clone().into(), - range_0, - range_1, - range_2, - ) { - Ok(e) => e, - Err(e) => { - warn!("Failed to build extranonce factory: {e:?}"); - return Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::ExtranoncePrefixFactoryError(e), - )); - } - }; - - channel_manager_data.extranonce_prefix_factory_extended = extranonces.clone(); - channel_manager_data.extranonce_prefix_factory_standard = extranonces; - - for (downstream_id, downstream) in channel_manager_data.downstream.iter_mut() { - downstream.downstream_data.super_safe_lock(|data| { - for (channel_id, standard_channel) in data.standard_channels.iter_mut() - { - match channel_manager_data - .extranonce_prefix_factory_standard - .next_prefix_standard() + debug!( + new_prefix_len, + rollable_extranonce_size, + full_extranonce_size, + "Calculated extranonce ranges" + ); + let extranonces = match ExtendedExtranonce::from_upstream_extranonce( + msg.extranonce_prefix.clone().into(), + range_0, + range_1, + range_2, + ) { + Ok(e) => e, + Err(e) => { + warn!("Failed to build extranonce factory: {e:?}"); + return Err(JDCError::RolesSv2Logic( + Error::ExtranoncePrefixFactoryError(e), + )); + } + }; + + channel_manager_data.extranonce_prefix_factory_extended = + extranonces.clone(); + channel_manager_data.extranonce_prefix_factory_standard = extranonces; + + for (downstream_id, downstream) in + channel_manager_data.downstream.iter_mut() + { + downstream.downstream_data.super_safe_lock(|data| { + for (channel_id, standard_channel) in + data.standard_channels.iter_mut() { - Ok(prefix) => match standard_channel.set_extranonce_prefix(prefix.clone().to_vec()) { - Ok(_) => { - messages_results.push(Ok(( - *downstream_id, - Mining::SetExtranoncePrefix(SetExtranoncePrefix { - channel_id: *channel_id, - extranonce_prefix: prefix.into(), - }), - ) - .into())); - } + match channel_manager_data + .extranonce_prefix_factory_standard + .next_prefix_standard() + { + Ok(prefix) => match standard_channel + .set_extranonce_prefix(prefix.clone().to_vec()) + { + Ok(_) => { + messages_results.push(Ok(( + *downstream_id, + Mining::SetExtranoncePrefix( + SetExtranoncePrefix { + channel_id: *channel_id, + extranonce_prefix: prefix.into(), + }, + ), + ) + .into())); + } + Err(e) => { + messages_results.push(Err( + JDCError::RolesSv2Logic( + Error::FailedToUpdateStandardChannel(e), + ), + )); + } + }, Err(e) => { messages_results.push(Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::FailedToUpdateStandardChannel(e), + Error::ExtranoncePrefixFactoryError(e), ))); } - }, - Err(e) => { - messages_results.push(Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::ExtranoncePrefixFactoryError(e), - ))); } } - } - for (channel_id, extended_channel) in data.extended_channels.iter_mut() - { - match channel_manager_data - .extranonce_prefix_factory_extended - .next_prefix_extended(extended_channel.get_rollable_extranonce_size() as usize) + for (channel_id, extended_channel) in + data.extended_channels.iter_mut() { - Ok(prefix) => match extended_channel.set_extranonce_prefix(prefix.clone().to_vec()) { - Ok(_) => { - messages_results.push(Ok(( - *downstream_id, - Mining::SetExtranoncePrefix(SetExtranoncePrefix { - channel_id: *channel_id, - extranonce_prefix: prefix.into(), - }), - ) - .into())); - } + match channel_manager_data + .extranonce_prefix_factory_extended + .next_prefix_extended( + extended_channel.get_rollable_extranonce_size() + as usize, + ) { + Ok(prefix) => match extended_channel + .set_extranonce_prefix(prefix.clone().to_vec()) + { + Ok(_) => { + messages_results.push(Ok(( + *downstream_id, + Mining::SetExtranoncePrefix( + SetExtranoncePrefix { + channel_id: *channel_id, + extranonce_prefix: prefix.into(), + }, + ), + ) + .into())); + } + Err(e) => { + messages_results.push(Err( + JDCError::RolesSv2Logic( + Error::FailedToUpdateExtendedChannel(e), + ), + )); + } + }, Err(e) => { messages_results.push(Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::FailedToUpdateExtendedChannel(e), + Error::ExtranoncePrefixFactoryError(e), ))); } - }, - Err(e) => { - messages_results.push(Err(JDCError::RolesSv2Logic( - roles_logic_sv2::Error::ExtranoncePrefixFactoryError(e), - ))); } } - } - }); + }); + } } - } - Ok(messages_results) - })?; + Ok(messages_results) + })?; for message in messages_results.into_iter().flatten() { message.forward(&self.channel_manager_channel).await; diff --git a/roles/jd-client/src/lib/downstream/mod.rs b/roles/jd-client/src/lib/downstream/mod.rs index 1fb36095c6..a9a37d8014 100644 --- a/roles/jd-client/src/lib/downstream/mod.rs +++ b/roles/jd-client/src/lib/downstream/mod.rs @@ -2,6 +2,7 @@ use std::{collections::HashMap, sync::Arc}; use async_channel::{unbounded, Receiver, Sender}; use stratum_apps::{ + custom_mutex::Mutex, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::server::{ @@ -13,7 +14,6 @@ use stratum_apps::{ common_messages_sv2::MESSAGE_TYPE_SETUP_CONNECTION, handlers_sv2::HandleCommonMessagesFromClientAsync, parsers_sv2::{AnyMessage, IsSv2Message}, - roles_logic_sv2::utils::Mutex, }, }; diff --git a/roles/jd-client/src/lib/error.rs b/roles/jd-client/src/lib/error.rs index 569d299fba..f50fd5def4 100644 --- a/roles/jd-client/src/lib/error.rs +++ b/roles/jd-client/src/lib/error.rs @@ -14,10 +14,11 @@ use ext_config::ConfigError; use std::fmt; use stratum_apps::{ + errors::Error, network_helpers, stratum_core::{ binary_sv2, bitcoin, channels_sv2::server::error::GroupChannelError, framing_sv2, - handlers_sv2::HandlerErrorType, noise_sv2, parsers_sv2::ParserError, roles_logic_sv2, + handlers_sv2::HandlerErrorType, noise_sv2, parsers_sv2::ParserError, }, }; use tokio::{sync::broadcast, time::error::Elapsed}; @@ -41,8 +42,8 @@ pub enum JDCError { /// Errors on bad `String` to `int` conversion. ParseInt(std::num::ParseIntError), /// Errors from `roles_logic_sv2` crate. - RolesSv2Logic(roles_logic_sv2::errors::Error), - UpstreamIncoming(roles_logic_sv2::errors::Error), + RolesSv2Logic(Error), + UpstreamIncoming(Error), #[allow(dead_code)] SubprotocolMining(String), // Locking Errors @@ -248,8 +249,8 @@ impl From for JDCError { } } -impl From for JDCError { - fn from(e: roles_logic_sv2::errors::Error) -> Self { +impl From for JDCError { + fn from(e: Error) -> Self { JDCError::RolesSv2Logic(e) } } diff --git a/roles/jd-client/src/lib/job_declarator/mod.rs b/roles/jd-client/src/lib/job_declarator/mod.rs index f1ccee52f0..aa74c98601 100644 --- a/roles/jd-client/src/lib/job_declarator/mod.rs +++ b/roles/jd-client/src/lib/job_declarator/mod.rs @@ -1,12 +1,12 @@ -use std::{net::SocketAddr, sync::Arc}; - use async_channel::{unbounded, Receiver, Sender}; +use std::{net::SocketAddr, sync::Arc}; use stratum_apps::{ + custom_mutex::Mutex, key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ codec_sv2::HandshakeRole, framing_sv2, handlers_sv2::HandleCommonMessagesFromServerAsync, - noise_sv2::Initiator, roles_logic_sv2::utils::Mutex, + noise_sv2::Initiator, }, }; use tokio::{ diff --git a/roles/jd-client/src/lib/template_receiver/mod.rs b/roles/jd-client/src/lib/template_receiver/mod.rs index eb0ed7d9f4..147a6e39cc 100644 --- a/roles/jd-client/src/lib/template_receiver/mod.rs +++ b/roles/jd-client/src/lib/template_receiver/mod.rs @@ -10,10 +10,10 @@ //! - Forward messages from the channel manager upstream to the template provider //! - Send [`CoinbaseOutputConstraints`] to the template provider -use std::{net::SocketAddr, sync::Arc}; - use async_channel::{unbounded, Receiver, Sender}; +use std::{net::SocketAddr, sync::Arc}; use stratum_apps::{ + custom_mutex::Mutex, key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ @@ -26,7 +26,6 @@ use stratum_apps::{ handlers_sv2::HandleCommonMessagesFromServerAsync, noise_sv2::Initiator, parsers_sv2::{AnyMessage, TemplateDistribution}, - roles_logic_sv2::utils::Mutex, template_distribution_sv2::CoinbaseOutputConstraints, }, }; diff --git a/roles/jd-client/src/lib/upstream/mod.rs b/roles/jd-client/src/lib/upstream/mod.rs index b014a1d309..d7c02e7e6e 100644 --- a/roles/jd-client/src/lib/upstream/mod.rs +++ b/roles/jd-client/src/lib/upstream/mod.rs @@ -9,15 +9,15 @@ //! - Forward SV2 mining messages between upstream and channel manager //! - Handle common messages from upstream -use std::{net::SocketAddr, sync::Arc}; - use async_channel::{unbounded, Receiver, Sender}; +use std::{net::SocketAddr, sync::Arc}; use stratum_apps::{ + custom_mutex::Mutex, key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ codec_sv2::HandshakeRole, framing_sv2, handlers_sv2::HandleCommonMessagesFromServerAsync, - noise_sv2::Initiator, roles_logic_sv2::utils::Mutex, + noise_sv2::Initiator, }, }; use tokio::{ diff --git a/roles/jd-server/Cargo.toml b/roles/jd-server/Cargo.toml index 940d8260a3..f8ed98eb95 100644 --- a/roles/jd-server/Cargo.toml +++ b/roles/jd-server/Cargo.toml @@ -17,22 +17,8 @@ name = "jd_server" path = "src/lib/mod.rs" [dependencies] -rpc_sv2 = { version = "1.1.0" } -config_helpers_sv2 = { version = "0.1.0" } -network_helpers_sv2 = { version = "4.0.0" } -roles_logic_sv2 = { version = "5.0.0" } -# Published versions to match roles_logic_sv2 v5.0.0 exact dependencies -binary_sv2 = { version = "4.0.0" } -job_declaration_sv2 = { version = "5.0.0" } -parsers_sv2 = { version = "0.1" } -codec_sv2 = { version = "3.0.0" } -framing_sv2 = { version = "5.0.0" } -noise_sv2 = { version = "1.1" } -common_messages_sv2 = { version = "6.0.0" } -mining_sv2 = { version = "5.0" } -error_handling = { version = "1.0.0" } -key-utils = { version = "1.2.0" } -bitcoin = "0.32.5" +stratum-apps = { path = "../stratum-apps", features = ["jd_server"] } +roles_logic_sv2 = "4.0.0" async-channel = "1.5.1" rand = "0.8.4" tokio = { version = "1.44.1", features = ["full"] } @@ -44,3 +30,4 @@ serde = { version = "1.0.89", features = ["derive", "alloc"], default-features = hashbrown = { version = "0.11", default-features = false, features = ["ahash", "serde"] } hex = "0.4.3" clap = { version = "4.5.39", features = ["derive"] } + diff --git a/roles/jd-server/src/lib/config.rs b/roles/jd-server/src/lib/config.rs index 821797af5a..b3d95ecfe2 100644 --- a/roles/jd-server/src/lib/config.rs +++ b/roles/jd-server/src/lib/config.rs @@ -11,13 +11,13 @@ //! //! Also defines a helper struct [`CoreRpc`] to group RPC parameters. -use config_helpers_sv2::CoinbaseRewardScript; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use serde::Deserialize; use std::{ path::{Path, PathBuf}, time::Duration, }; +use stratum_apps::config_helpers::CoinbaseRewardScript; +use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; #[derive(Debug, serde::Deserialize, Clone)] pub struct JobDeclaratorServerConfig { @@ -32,7 +32,7 @@ pub struct JobDeclaratorServerConfig { core_rpc_port: u16, core_rpc_user: String, core_rpc_pass: String, - #[serde(deserialize_with = "config_helpers_sv2::duration_from_toml")] + #[serde(deserialize_with = "stratum_apps::config_helpers::duration_from_toml")] mempool_update_interval: Duration, log_file: Option, } @@ -173,8 +173,8 @@ impl CoreRpc { #[cfg(test)] mod tests { use super::super::JobDeclaratorServer; - use bitcoin::{self, Amount, ScriptBuf, TxOut}; use ext_config::{Config, ConfigError, File, FileFormat}; + use roles_logic_sv2::bitcoin::{self, Amount, ScriptBuf, TxOut}; use std::path::PathBuf; use crate::config::JobDeclaratorServerConfig; diff --git a/roles/jd-server/src/lib/error.rs b/roles/jd-server/src/lib/error.rs index 38844c4f83..323eeb119b 100644 --- a/roles/jd-server/src/lib/error.rs +++ b/roles/jd-server/src/lib/error.rs @@ -19,12 +19,12 @@ use std::{ sync::{MutexGuard, PoisonError}, }; -use binary_sv2; -use codec_sv2; -use framing_sv2; -use noise_sv2; -use parsers_sv2::Mining; use roles_logic_sv2; +use roles_logic_sv2::codec_sv2; +use roles_logic_sv2::codec_sv2::binary_sv2; +use roles_logic_sv2::codec_sv2::framing_sv2; +use roles_logic_sv2::codec_sv2::noise_sv2; +use roles_logic_sv2::parsers_sv2::Mining; use crate::mempool::error::JdsMempoolError; diff --git a/roles/jd-server/src/lib/job_declarator/message_handler.rs b/roles/jd-server/src/lib/job_declarator/message_handler.rs index b5644bad41..eabc8b75a1 100644 --- a/roles/jd-server/src/lib/job_declarator/message_handler.rs +++ b/roles/jd-server/src/lib/job_declarator/message_handler.rs @@ -1,15 +1,15 @@ -use binary_sv2::{Decodable, Serialize, U256}; -use bitcoin::{ +use roles_logic_sv2::bitcoin::{ consensus::Decodable as BitcoinDecodable, hashes::{sha256d, Hash}, Transaction, Txid, }; -use job_declaration_sv2::{ +use roles_logic_sv2::codec_sv2::binary_sv2::{Decodable, Serialize, U256}; +use roles_logic_sv2::job_declaration_sv2::{ AllocateMiningJobToken, AllocateMiningJobTokenSuccess, DeclareMiningJob, DeclareMiningJobError, DeclareMiningJobSuccess, ProvideMissingTransactions, ProvideMissingTransactionsSuccess, PushSolution, }; -use parsers_sv2::JobDeclaration; +use roles_logic_sv2::parsers_sv2::JobDeclaration; use roles_logic_sv2::{ errors::Error, handlers::{job_declaration::ParseJobDeclarationMessagesFromDownstream, SendTo_}, @@ -24,7 +24,7 @@ pub type SendTo = SendTo_, ()>; use crate::mempool::JDsMempool; use super::{signed_token, TransactionState}; -use parsers_sv2::AnyMessage as AllMessages; +use roles_logic_sv2::parsers_sv2::AnyMessage as AllMessages; use tracing::{debug, info}; use super::JobDeclaratorDownstream; diff --git a/roles/jd-server/src/lib/job_declarator/mod.rs b/roles/jd-server/src/lib/job_declarator/mod.rs index 40b88aa516..1296ef7957 100644 --- a/roles/jd-server/src/lib/job_declarator/mod.rs +++ b/roles/jd-server/src/lib/job_declarator/mod.rs @@ -22,25 +22,22 @@ use super::{ error::JdsError, mempool::JDsMempool, status, EitherFrame, JobDeclaratorServerConfig, StdFrame, }; use async_channel::{Receiver, Sender}; -use binary_sv2::{self, B0255, U256}; -use bitcoin::{ +use core::panic; +use nohash_hasher::BuildNoHashHasher; +use roles_logic_sv2::bitcoin::{ block::{Header, Version}, consensus::{deserialize, encode::serialize}, hashes::{sha256d::Hash as DHash, Hash}, Amount, Block, BlockHash, CompactTarget, Transaction, TxOut, Txid, }; -use codec_sv2::HandshakeRole; -use common_messages_sv2::{ +use roles_logic_sv2::codec_sv2::binary_sv2::{self, B0255, U256}; +use roles_logic_sv2::codec_sv2::noise_sv2::Responder; +use roles_logic_sv2::codec_sv2::HandshakeRole; +use roles_logic_sv2::common_messages_sv2::{ Protocol, SetupConnection, SetupConnectionError, SetupConnectionSuccess, }; -use core::panic; -use error_handling::handle_result; -use job_declaration_sv2::{DeclareMiningJob, PushSolution}; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; -use network_helpers_sv2::noise_connection::Connection; -use nohash_hasher::BuildNoHashHasher; -use noise_sv2::Responder; -use parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}; +use roles_logic_sv2::job_declaration_sv2::{DeclareMiningJob, PushSolution}; +use roles_logic_sv2::parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}; use roles_logic_sv2::{ handlers::job_declaration::{ParseJobDeclarationMessagesFromDownstream, SendTo}, utils::Mutex, @@ -50,6 +47,9 @@ use std::{ convert::TryInto, sync::{atomic::AtomicU32, Arc}, }; +use stratum_apps::handle_result; +use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; +use stratum_apps::network_helpers::noise_connection::Connection; use tokio::{net::TcpListener, time::Duration}; use tracing::{debug, error, info}; @@ -273,7 +273,7 @@ impl JobDeclaratorDownstream { /// Wraps the message into a `StdFrame` and sends it through the established channel. pub async fn send( self_mutex: Arc>, - message: parsers_sv2::JobDeclaration<'static>, + message: roles_logic_sv2::parsers_sv2::JobDeclaration<'static>, ) -> Result<(), ()> { let sv2_frame: StdFrame = JdsMessages::JobDeclaration(message).try_into().unwrap(); let sender = self_mutex.safe_lock(|self_| self_.sender.clone()).unwrap(); diff --git a/roles/jd-server/src/lib/mempool/error.rs b/roles/jd-server/src/lib/mempool/error.rs index cb0e2a2971..15f5a84951 100644 --- a/roles/jd-server/src/lib/mempool/error.rs +++ b/roles/jd-server/src/lib/mempool/error.rs @@ -11,8 +11,8 @@ //! It also includes a centralized error logging helper (`handle_error`) to standardize warnings //! and diagnostics across components. -use rpc_sv2::mini_rpc_client::RpcError; use std::{convert::From, sync::PoisonError}; +use stratum_apps::rpc::mini_rpc_client::RpcError; use tracing::{error, warn}; /// Errors that may occur during JDS mempool operations. diff --git a/roles/jd-server/src/lib/mempool/mod.rs b/roles/jd-server/src/lib/mempool/mod.rs index 866f406675..8684545d9f 100644 --- a/roles/jd-server/src/lib/mempool/mod.rs +++ b/roles/jd-server/src/lib/mempool/mod.rs @@ -19,11 +19,11 @@ pub mod error; use super::job_declarator::AddTrasactionsToMempoolInner; use crate::mempool::error::JdsMempoolError; use async_channel::Receiver; -use bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}; use hashbrown::HashMap; +use roles_logic_sv2::bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}; use roles_logic_sv2::utils::Mutex; -use rpc_sv2::{mini_rpc_client, mini_rpc_client::RpcError}; use std::{str::FromStr, sync::Arc}; +use stratum_apps::rpc::{mini_rpc_client, mini_rpc_client::RpcError}; /// Wrapper around a known transaction and its hash. #[derive(Clone, Debug)] @@ -40,7 +40,7 @@ pub struct JDsMempool { /// Auth for RPC connection to the node. auth: mini_rpc_client::Auth, /// URI of the Bitcoin node. - url: rpc_sv2::Uri, + url: stratum_apps::rpc::Uri, /// Receiver for new block solutions coming from JDC. new_block_receiver: Receiver, } @@ -68,7 +68,7 @@ impl JDsMempool { /// Instantiates a new empty mempool for JDS. pub fn new( - url: rpc_sv2::Uri, + url: stratum_apps::rpc::Uri, username: String, password: String, new_block_receiver: Receiver, diff --git a/roles/jd-server/src/lib/mod.rs b/roles/jd-server/src/lib/mod.rs index 7fa672461a..0d4af32cf2 100644 --- a/roles/jd-server/src/lib/mod.rs +++ b/roles/jd-server/src/lib/mod.rs @@ -23,15 +23,16 @@ pub mod job_declarator; pub mod mempool; pub mod status; use async_channel::{bounded, unbounded, Receiver, Sender}; -use codec_sv2::{StandardEitherFrame, StandardSv2Frame}; use config::JobDeclaratorServerConfig; use error::JdsError; use job_declarator::JobDeclarator; use mempool::error::JdsMempoolError; -use parsers_sv2::AnyMessage as JdsMessages; +use roles_logic_sv2::codec_sv2::{StandardEitherFrame, StandardSv2Frame}; +use roles_logic_sv2::parsers_sv2::AnyMessage as JdsMessages; use roles_logic_sv2::utils::Mutex; -pub use rpc_sv2::Uri; use std::{ops::Sub, str::FromStr, sync::Arc}; +use stratum_apps::handle_result; +pub use stratum_apps::rpc::Uri; use tokio::{select, task}; use tracing::{error, info, warn}; diff --git a/roles/jd-server/src/lib/status.rs b/roles/jd-server/src/lib/status.rs index acee8a0c26..680ebeee04 100644 --- a/roles/jd-server/src/lib/status.rs +++ b/roles/jd-server/src/lib/status.rs @@ -8,7 +8,8 @@ //! //! This allows for centralized, consistent error handling across the application. -use parsers_sv2::Mining; +use roles_logic_sv2::parsers_sv2::Mining; +use stratum_apps::error_handling::ErrorBranch; use super::error::JdsError; @@ -59,11 +60,7 @@ pub struct Status { /// /// This is the core logic used to determine which status variant should be sent /// based on the error type and sender context. -async fn send_status( - sender: &Sender, - e: JdsError, - outcome: error_handling::ErrorBranch, -) -> error_handling::ErrorBranch { +async fn send_status(sender: &Sender, e: JdsError, outcome: ErrorBranch) -> ErrorBranch { match sender { Sender::Downstream(tx) => match e { JdsError::Sv2ProtocolError((id, Mining::OpenMiningChannelError(_))) => { @@ -118,50 +115,36 @@ async fn send_status( /// /// Used by the `handle_result!` macro across the codebase. /// Decides whether the task should `Continue` or `Break` based on the error type and source. -pub async fn handle_error(sender: &Sender, e: JdsError) -> error_handling::ErrorBranch { +pub async fn handle_error(sender: &Sender, e: JdsError) -> ErrorBranch { tracing::debug!("Error: {:?}", &e); match e { - JdsError::Io(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, + JdsError::Io(_) => send_status(sender, e, ErrorBranch::Break).await, JdsError::ChannelSend(_) => { //This should be a continue because if we fail to send to 1 downstream we should // continue processing the other downstreams in the loop we are in. // Otherwise if a downstream fails to send to then subsequent downstreams in // the map won't get send called on them - send_status(sender, e, error_handling::ErrorBranch::Continue).await - } - JdsError::ChannelRecv(_) => { - send_status(sender, e, error_handling::ErrorBranch::Break).await - } - JdsError::BinarySv2(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::Codec(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::Noise(_) => send_status(sender, e, error_handling::ErrorBranch::Continue).await, - JdsError::RolesLogic(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::Custom(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::Framing(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::PoisonLock(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::Sv2ProtocolError(_) => { - send_status(sender, e, error_handling::ErrorBranch::Break).await - } - JdsError::MempoolError(_) => { - send_status(sender, e, error_handling::ErrorBranch::Break).await + send_status(sender, e, ErrorBranch::Continue).await } + JdsError::ChannelRecv(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::BinarySv2(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::Codec(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::Noise(_) => send_status(sender, e, ErrorBranch::Continue).await, + JdsError::RolesLogic(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::Custom(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::Framing(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::PoisonLock(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::Sv2ProtocolError(_) => send_status(sender, e, ErrorBranch::Break).await, + JdsError::MempoolError(_) => send_status(sender, e, ErrorBranch::Break).await, JdsError::ImpossibleToReconstructBlock(_) => { - send_status(sender, e, error_handling::ErrorBranch::Continue).await - } - JdsError::NoLastDeclaredJob => { - send_status(sender, e, error_handling::ErrorBranch::Continue).await - } - JdsError::InvalidRPCUrl => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::BadCliArgs => send_status(sender, e, error_handling::ErrorBranch::Break).await, - JdsError::InvalidPrevHash => { - send_status(sender, e, error_handling::ErrorBranch::Break).await - } - JdsError::InvalidCoinbase => { - send_status(sender, e, error_handling::ErrorBranch::Break).await - } - JdsError::InvalidMerkleRoot => { - send_status(sender, e, error_handling::ErrorBranch::Break).await + send_status(sender, e, ErrorBranch::Continue).await } + JdsError::NoLastDeclaredJob => send_status(sender, e, ErrorBranch::Continue).await, + JdsError::InvalidRPCUrl => send_status(sender, e, ErrorBranch::Break).await, + JdsError::BadCliArgs => send_status(sender, e, ErrorBranch::Break).await, + JdsError::InvalidPrevHash => send_status(sender, e, ErrorBranch::Break).await, + JdsError::InvalidCoinbase => send_status(sender, e, ErrorBranch::Break).await, + JdsError::InvalidMerkleRoot => send_status(sender, e, ErrorBranch::Break).await, } } @@ -171,12 +154,12 @@ mod tests { use super::*; use async_channel::{bounded, RecvError}; - use binary_sv2; - use codec_sv2; - use framing_sv2; - use noise_sv2; - use parsers_sv2::Mining; use roles_logic_sv2; + use roles_logic_sv2::codec_sv2; + use roles_logic_sv2::codec_sv2::binary_sv2; + use roles_logic_sv2::codec_sv2::framing_sv2; + use roles_logic_sv2::codec_sv2::noise_sv2; + use roles_logic_sv2::parsers_sv2::Mining; #[tokio::test] async fn test_send_status_downstream_listener_shutdown() { @@ -184,7 +167,7 @@ mod tests { let sender = Sender::DownstreamListener(tx); let error = JdsError::ChannelRecv(async_channel::RecvError); - send_status(&sender, error, error_handling::ErrorBranch::Continue).await; + send_status(&sender, error, ErrorBranch::Continue).await; match rx.recv().await { Ok(status) => match status.state { State::DownstreamShutdown(e) => { @@ -202,7 +185,7 @@ mod tests { let sender = Sender::Upstream(tx); let error = JdsError::MempoolError(crate::mempool::error::JdsMempoolError::EmptyMempool); let error_string = error.to_string(); - send_status(&sender, error, error_handling::ErrorBranch::Continue).await; + send_status(&sender, error, ErrorBranch::Continue).await; match rx.recv().await { Ok(status) => match status.state { @@ -430,7 +413,7 @@ mod tests { let sender = Sender::Downstream(tx); let inner: [u8; 32] = rand::random(); let value = inner.to_vec().try_into().unwrap(); - let error_msg = mining_sv2::OpenMiningChannelError { + let error_msg = roles_logic_sv2::mining_sv2::OpenMiningChannelError { request_id: 1, error_code: value, }; diff --git a/roles/pool/Cargo.toml b/roles/pool/Cargo.toml index 921436edda..dffd724e02 100644 --- a/roles/pool/Cargo.toml +++ b/roles/pool/Cargo.toml @@ -25,4 +25,4 @@ secp256k1 = { version = "0.28.2", default-features = false, features = ["alloc", tokio = { version = "1.44.1", features = ["full"] } ext-config = { version = "0.14.0", features = ["toml"], package = "config" } tracing = { version = "0.1" } -clap = { version = "4.5.39", features = ["derive"] } \ No newline at end of file +clap = { version = "4.5.39", features = ["derive"] } diff --git a/roles/pool/src/lib/channel_manager/mod.rs b/roles/pool/src/lib/channel_manager/mod.rs index e5d2d40c0d..204ecaa183 100644 --- a/roles/pool/src/lib/channel_manager/mod.rs +++ b/roles/pool/src/lib/channel_manager/mod.rs @@ -1,13 +1,13 @@ +use async_channel::{Receiver, Sender}; +use core::sync::atomic::Ordering; use std::{ collections::HashMap, net::SocketAddr, sync::{atomic::AtomicUsize, Arc}, }; - -use async_channel::{Receiver, Sender}; -use core::sync::atomic::Ordering; use stratum_apps::{ config_helpers::CoinbaseRewardScript, + custom_mutex::Mutex, key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ @@ -25,7 +25,6 @@ use stratum_apps::{ mining_sv2::{ExtendedExtranonce, SetTarget}, noise_sv2::Responder, parsers_sv2::{Mining, TemplateDistribution}, - roles_logic_sv2::utils::Mutex, template_distribution_sv2::{NewTemplate, SetNewPrevHash}, }, }; diff --git a/roles/pool/src/lib/config.rs b/roles/pool/src/lib/config.rs index 51e74317b4..ca1904dc58 100644 --- a/roles/pool/src/lib/config.rs +++ b/roles/pool/src/lib/config.rs @@ -12,7 +12,6 @@ use std::{ net::SocketAddr, path::{Path, PathBuf}, }; - use stratum_apps::{ config_helpers::CoinbaseRewardScript, key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, diff --git a/roles/pool/src/lib/downstream/mod.rs b/roles/pool/src/lib/downstream/mod.rs index 9d090f8561..180c79fab0 100644 --- a/roles/pool/src/lib/downstream/mod.rs +++ b/roles/pool/src/lib/downstream/mod.rs @@ -8,6 +8,7 @@ use std::{ use async_channel::{unbounded, Receiver, Sender}; use stratum_apps::{ + custom_mutex::Mutex, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::server::{ @@ -20,7 +21,6 @@ use stratum_apps::{ handlers_sv2::HandleCommonMessagesFromClientAsync, noise_sv2::Error, parsers_sv2::{AnyMessage, Mining}, - roles_logic_sv2::utils::Mutex, }, }; use tokio::sync::broadcast; diff --git a/roles/pool/src/lib/error.rs b/roles/pool/src/lib/error.rs index 6b859e3036..696cdc6095 100644 --- a/roles/pool/src/lib/error.rs +++ b/roles/pool/src/lib/error.rs @@ -3,19 +3,20 @@ use std::{ fmt::Debug, sync::{MutexGuard, PoisonError}, }; - -use stratum_apps::stratum_core::{ - binary_sv2, bitcoin, - channels_sv2::{ - server::error::{ExtendedChannelError, GroupChannelError, StandardChannelError}, - vardiff::error::VardiffError, +use stratum_apps::{ + errors::Error, + stratum_core::{ + binary_sv2, bitcoin, + channels_sv2::{ + server::error::{ExtendedChannelError, GroupChannelError, StandardChannelError}, + vardiff::error::VardiffError, + }, + codec_sv2, framing_sv2, + handlers_sv2::HandlerErrorType, + mining_sv2::ExtendedExtranonceError, + noise_sv2, + parsers_sv2::{Mining, ParserError}, }, - codec_sv2, framing_sv2, - handlers_sv2::HandlerErrorType, - mining_sv2::ExtendedExtranonceError, - noise_sv2, - parsers_sv2::{Mining, ParserError}, - roles_logic_sv2, }; pub type PoolResult = Result; @@ -47,7 +48,7 @@ pub enum PoolError { /// Error from the `noise_sv2` crate. Noise(noise_sv2::Error), /// Error from the `roles_logic_sv2` crate. - RolesLogic(roles_logic_sv2::Error), + RolesLogic(Error), /// Error related to SV2 message framing. Framing(framing_sv2::Error), /// Error due to a poisoned lock, typically from a failed mutex operation. @@ -179,8 +180,8 @@ impl From for PoolError { } } -impl From for PoolError { - fn from(e: roles_logic_sv2::Error) -> PoolError { +impl From for PoolError { + fn from(e: Error) -> PoolError { PoolError::RolesLogic(e) } } diff --git a/roles/stratum-apps/Cargo.toml b/roles/stratum-apps/Cargo.toml index 3cfe3fa778..fd2a4e3e63 100644 --- a/roles/stratum-apps/Cargo.toml +++ b/roles/stratum-apps/Cargo.toml @@ -13,7 +13,7 @@ keywords = ["stratum", "mining", "bitcoin", "protocol", "sv2"] [dependencies] # Core protocol layer -stratum-core = { path = "../../stratum-core", version = "0.1.0" } +stratum-core = { path = "../../stratum-core", version = "0.1.0", optional = true} # External dependencies needed by the modules # Network helpers dependencies @@ -55,16 +55,17 @@ network = ["tokio-util"] config = [] rpc = ["serde_json", "hex", "base64", "hyper", "hyper-util", "http-body-util"] std = ["bs58/std", "secp256k1/rand-std", "rand/std", "rand/std_rng"] +core = ["stratum-core"] # Protocol features passed through to stratum-core sv1 = ["stratum-core/sv1", "stratum-core/translation", "tokio-util", "serde_json"] with_buffer_pool = ["stratum-core/with_buffer_pool"] # Convenience feature bundles for different role types -pool = ["network", "config", "with_buffer_pool"] -jd_client = ["network", "config", "with_buffer_pool"] +pool = ["network", "config", "with_buffer_pool", "core"] +jd_client = ["network", "config", "with_buffer_pool", "core"] jd_server = ["network", "config", "rpc", "with_buffer_pool"] -translator = ["network", "config", "sv1", "with_buffer_pool"] +translator = ["network", "config", "sv1", "with_buffer_pool", "core"] mining_device = ["network", "config", "with_buffer_pool"] [package.metadata.docs.rs] diff --git a/roles/stratum-apps/src/custom_mutex.rs b/roles/stratum-apps/src/custom_mutex.rs new file mode 100644 index 0000000000..bbb5ed1ef3 --- /dev/null +++ b/roles/stratum-apps/src/custom_mutex.rs @@ -0,0 +1,117 @@ +//! # Custom Mutex +//! +//! This crate provides a thin wrapper around [`std::sync::Mutex`] with convenience methods +//! for closure-based locking. +//! +//! It exposes two main methods for accessing the inner value: +//! - [`safe_lock`] lets you run a closure while handling poisoned locks explicitly. +//! - [`super_safe_lock`] unwraps the result of `safe_lock`, panicking if the lock is poisoned. + +use std::sync::{Mutex as Mutex_, MutexGuard, PoisonError}; + +/// Custom synchronization primitive for managing shared mutable state. +/// +/// This custom mutex implementation builds on [`std::sync::Mutex`] to enhance usability and safety +/// in concurrent environments. It provides ergonomic methods to safely access and modify inner +/// values while reducing the risk of deadlocks and panics. It is used throughout SRI applications +/// to managed shared state across multiple threads, such as tracking active mining sessions, +/// routing jobs, and managing connections safely and efficiently. +/// +/// ## Advantages +/// - **Closure-Based Locking:** The `safe_lock` method encapsulates the locking process, ensuring +/// the lock is automatically released after the closure completes. +/// - **Error Handling:** `safe_lock` enforces explicit handling of potential [`PoisonError`] +/// conditions, reducing the risk of panics caused by poisoned locks. +/// - **Panic-Safe Option:** The `super_safe_lock` method provides an alternative that unwraps the +/// result of `safe_lock`, with optional runtime safeguards against panics. +/// - **Extensibility:** Includes feature-gated functionality to customize behavior, such as +/// stricter runtime checks using external tools like +/// [`no-panic`](https://github.com/dtolnay/no-panic). +#[derive(Debug)] +pub struct Mutex(Mutex_); + +impl Mutex { + /// Mutex safe lock. + /// + /// Safely locks the `Mutex` and executes a closer (`thunk`) with a mutable reference to the + /// inner value. This ensures that the lock is automatically released after the closure + /// completes, preventing deadlocks. It explicitly returns a [`PoisonError`] containing a + /// [`MutexGuard`] to the inner value in cases where the lock is poisoned. + /// + /// To prevent poison lock errors, unwraps should never be used within the closure. The result + /// should always be returned and handled outside of the sage lock. + pub fn safe_lock(&self, thunk: F) -> Result>> + where + F: FnOnce(&mut T) -> Ret, + { + let mut lock = self.0.lock()?; + let return_value = thunk(&mut *lock); + drop(lock); + Ok(return_value) + } + + /// Mutex super safe lock. + /// + /// Locks the `Mutex` and executes a closure (`thunk`) with a mutable reference to the inner + /// value, panicking if the lock is poisoned. + /// + /// This is a convenience wrapper around `safe_lock` for cases where explicit error handling is + /// unnecessary or undesirable. Use with caution in production code. + pub fn super_safe_lock(&self, thunk: F) -> Ret + where + F: FnOnce(&mut T) -> Ret, + { + //#[cfg(feature = "disable_nopanic")] + { + self.safe_lock(thunk).unwrap() + } + //#[cfg(not(feature = "disable_nopanic"))] + //{ + // // based on https://github.com/dtolnay/no-panic + // struct __NoPanic; + // extern "C" { + // #[link_name = "super_safe_lock called on a function that may panic"] + // fn trigger() -> !; + // } + // impl core::ops::Drop for __NoPanic { + // fn drop(&mut self) { + // unsafe { + // trigger(); + // } + // } + // } + // let mut lock = self.0.lock().expect("threads to never panic"); + // let __guard = __NoPanic; + // let return_value = thunk(&mut *lock); + // core::mem::forget(__guard); + // drop(lock); + // return_value + //} + } + + /// Creates a new [`Mutex`] instance, storing the initial value inside. + pub fn new(v: T) -> Self { + Mutex(Mutex_::new(v)) + } + + /// Removes lock for direct access. + /// + /// Acquires a lock on the [`Mutex`] and returns a [`MutexGuard`] for direct access to the + /// inner value. Allows for manual lock handling and is useful in scenarios where closures are + /// not convenient. + pub fn to_remove(&self) -> Result, PoisonError>> { + self.0.lock() + } +} + +#[cfg(test)] +mod tests { + + #[test] + fn test_super_safe_lock() { + let m = super::Mutex::new(1u32); + m.safe_lock(|i| *i += 1).unwrap(); + // m.super_safe_lock(|i| *i = (*i).checked_add(1).unwrap()); // will not compile + m.super_safe_lock(|i| *i = (*i).checked_add(1).unwrap_or_default()); // compiles + } +} diff --git a/roles/stratum-apps/src/errors.rs b/roles/stratum-apps/src/errors.rs new file mode 100644 index 0000000000..82fda6028e --- /dev/null +++ b/roles/stratum-apps/src/errors.rs @@ -0,0 +1,276 @@ +//! # Error Handling +//! +//! This module defines error types and utilities for handling errors in the `roles_logic_sv2` +//! module. It includes the [`Error`] enum for representing various errors. + +use std::{ + fmt::{self, Display, Formatter}, + sync::{MutexGuard, PoisonError}, +}; +use stratum_core::{ + binary_sv2::Error as BinarySv2Error, + bitcoin::hashes::FromSliceError, + channels_sv2::{ + server::error::{ExtendedChannelError, GroupChannelError, StandardChannelError}, + target::InputError, + vardiff::error::VardiffError, + }, + mining_sv2::ExtendedExtranonceError, + parsers_sv2::AnyMessage as AllMessages, +}; + +/// Error enum +#[derive(Debug)] +pub enum Error { + /// Payload size is too big to fit into a frame + BadPayloadSize, + /// Expected Length of 32, but received different length + ExpectedLen32(usize), + /// Error serializing/deserializing binary format + BinarySv2Error(BinarySv2Error), + /// Downstream is not connected anymore + DownstreamDown, + /// A channel was attempted to be added to an Upstream, but no groups are specified + NoGroupsFound, + /// Unexpected message received. + UnexpectedMessage(u8), + /// Extended channels do not have group IDs + NoGroupIdOnExtendedChannel, + /// No pairable upstream. Parameters are: (`min_v`, `max_v`, all flags supported) + NoPairableUpstream((u16, u16, u32)), + /// Error if the hashmap `future_jobs` field in the `GroupChannelJobDispatcher` is empty. + NoFutureJobs, + /// No Downstream's connected + NoDownstreamsConnected, + /// PrevHash requires non-existent Job Id + PrevHashRequireNonExistentJobId(u32), + /// Request Id not mapped + RequestIdNotMapped(u32), + /// There are no upstream connected + NoUpstreamsConnected, + /// Protocol has not been implemented, but should be + UnimplementedProtocol, + /// Unexpected `PoolMessage` type + UnexpectedPoolMessage, + /// Upstream is answering with a wrong request ID {} or + /// `DownstreamMiningSelector::on_open_standard_channel_request` has not been called + /// before relaying open channel request to upstream + UnknownRequestId(u32), + /// No more extranonces + NoMoreExtranonces, + /// A non future job always expect a previous new prev hash + JobIsNotFutureButPrevHashNotPresent, + /// If a channel is neither extended or part of a pool, + /// the only thing to do when a OpenStandardChannel is received + /// is to relay it upstream with and updated request id + ChannelIsNeitherExtendedNeitherInAPool, + /// No more available extranonces for downstream" + ExtranonceSpaceEnded, + /// Impossible to calculate merkle root + ImpossibleToCalculateMerkleRoot, + /// Group Id not found + GroupIdNotFound, + /// A share has been received but no job for it exist + ShareDoNotMatchAnyJob, + /// A share has been received but no channel for it exist + ShareDoNotMatchAnyChannel, + /// Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase + InvalidCoinbase, + /// Value remaining in coinbase output was not correctly updated (it's equal to 0) + ValueRemainingNotUpdated, + /// Block header version cannot be bigger than `i32::MAX` + VersionTooBig, + /// Tx version cannot be bigger than `i32::MAX` + TxVersionTooBig, + /// Tx version cannot be lower than 1 + TxVersionTooLow, + /// Impossible to decode tx + TxDecodingError(String), + /// No downstream has been registered for this channel id + NotFoundChannelId, + /// Impossible to create a standard job for channel + /// because no valid job has been received from upstream yet + NoValidJob, + /// Impossible to create an extended job for channel + /// because no valid job has been received from upstream yet + NoValidTranslatorJob, + /// Impossible to retrieve a template for the required job id + NoTemplateForId, + /// Impossible to retrieve a template for the required template id + NoValidTemplate(String), + /// Invalid extranonce size. Params: (required min, requested) + InvalidExtranonceSize(u16, u16), + /// Failed to create ExtendedExtranonce. Param: (error message) + ExtendedExtranonceCreationFailed(String), + /// Poison Lock + PoisonLock(String), + /// Channel Factory did not update job. Params: (downstream_job_id, upstream_job_id) + JobNotUpdated(u32, u32), + /// Impossible to get Target + TargetError(InputError), + /// Impossible to get Hashrate + HashrateError(InputError), + /// Message is well formatted but can not be handled + LogicErrorMessage(std::boxed::Box>), + /// JD server cannot propagate the block due to missing transactions + JDSMissingTransactions, + IoError(std::io::Error), + FromSliceError(FromSliceError), + /// Invalid user identity + InvalidUserIdentity(String), + ExtranoncePrefixFactoryError(ExtendedExtranonceError), + FailedToCreateStandardChannel(StandardChannelError), + Vardiff(VardiffError), + FailedToCreateExtendedChannel(ExtendedChannelError), + FailedToUpdateStandardChannel(StandardChannelError), + FailedToUpdateExtendedChannel(ExtendedChannelError), + FailedToProcessNewTemplateGroupChannel(GroupChannelError), + FailedToProcessSetNewPrevHashGroupChannel(GroupChannelError), + FailedToProcessNewTemplateExtendedChannel(ExtendedChannelError), + FailedToProcessNewTemplateStandardChannel(StandardChannelError), + FailedToProcessSetNewPrevHashExtendedChannel(ExtendedChannelError), + FailedToProcessSetNewPrevHashStandardChannel(StandardChannelError), + FailedToProcessGroupChannelJob(StandardChannelError), + NoActiveJob, + FailedToSendSolution, + FailedToSetCustomMiningJob(ExtendedChannelError), + FailedToDeserializeCoinbaseOutputs, + /// Error from parsers_sv2 + ParserError(stratum_core::parsers_sv2::ParserError), +} + +impl From for Error { + fn from(v: BinarySv2Error) -> Error { + Error::BinarySv2Error(v) + } +} + +impl From for Error { + fn from(v: std::io::Error) -> Error { + Error::IoError(v) + } +} + +impl From for Error { + fn from(v: FromSliceError) -> Error { + Error::FromSliceError(v) + } +} + +impl From for Error { + fn from(value: VardiffError) -> Self { + Error::Vardiff(value) + } +} + +impl From for Error { + fn from(v: stratum_core::parsers_sv2::ParserError) -> Error { + Error::ParserError(v) + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + use Error::*; + match self { + BadPayloadSize => write!(f, "Payload is too big to fit into the frame"), + BinarySv2Error(v) => write!( + f, + "BinarySv2Error: error in serializing/deserializing binary format {v:?}" + ), + DownstreamDown => { + write!( + f, + "Downstream is not connected anymore" + ) + } + ExpectedLen32(l) => write!(f, "Expected length of 32, but received length of {l}"), + NoGroupsFound => write!( + f, + "A channel was attempted to be added to an Upstream, but no groups are specified" + ), + UnexpectedMessage(type_) => write!(f, "Error: Unexpected message received. Recv m type: {type_:x}"), + NoGroupIdOnExtendedChannel => write!(f, "Extended channels do not have group IDs"), + NoPairableUpstream(a) => { + write!(f, "No pairable upstream node: {a:?}") + } + NoFutureJobs => write!(f, "GroupChannelJobDispatcher does not have any future jobs"), + NoDownstreamsConnected => write!(f, "NoDownstreamsConnected"), + PrevHashRequireNonExistentJobId(id) => { + write!(f, "PrevHashRequireNonExistentJobId {id}") + } + RequestIdNotMapped(id) => write!(f, "RequestIdNotMapped {id}"), + NoUpstreamsConnected => write!(f, "There are no upstream connected"), + UnexpectedPoolMessage => write!(f, "Unexpected `PoolMessage` type"), + UnimplementedProtocol => write!( + f, + "TODO: `Protocol` has not been implemented, but should be" + ), + UnknownRequestId(id) => write!( + f, + "Upstream is answering with a wrong request ID {id} or + DownstreamMiningSelector::on_open_standard_channel_request has not been called + before relaying open channel request to upstream" + ), + InvalidExtranonceSize(required_min, requested) => { + write!( + f, + "Invalid extranonce size: required min {required_min}, requested {requested}" + ) + }, + NoMoreExtranonces => write!(f, "No more extranonces"), + JobIsNotFutureButPrevHashNotPresent => write!(f, "A non future job always expect a previous new prev hash"), + ChannelIsNeitherExtendedNeitherInAPool => write!(f, "If a channel is neither extended neither is part of a pool the only thing to do when a OpenStandardChannel is received is to relay it upstream with and updated request id"), + ExtranonceSpaceEnded => write!(f, "No more available extranonces for downstream"), + ImpossibleToCalculateMerkleRoot => write!(f, "Impossible to calculate merkle root"), + GroupIdNotFound => write!(f, "Group id not found"), + ShareDoNotMatchAnyJob => write!(f, "A share has been received but no job for it exist"), + ShareDoNotMatchAnyChannel => write!(f, "A share has been received but no channel for it exist"), + InvalidCoinbase => write!(f, "Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase"), + ValueRemainingNotUpdated => write!(f, "Value remaining in coinbase output was not correctly updated (it's equal to 0)"), + VersionTooBig => write!(f, "We are trying to construct a block header with version bigger than i32::MAX"), + TxVersionTooBig => write!(f, "Tx version can not be greater than i32::MAX"), + TxVersionTooLow => write!(f, "Tx version can not be lower than 1"), + TxDecodingError(e) => write!(f, "Impossible to decode tx: {e:?}"), + NotFoundChannelId => write!(f, "No downstream has been registered for this channel id"), + NoValidJob => write!(f, "Impossible to create a standard job for channelA cause no valid job has been received from upstream yet"), + NoValidTranslatorJob => write!(f, "Impossible to create a extended job for channel cause no valid job has been received from upstream yet"), + NoTemplateForId => write!(f, "Impossible to retrieve a template for the required job id"), + NoValidTemplate(e) => write!(f, "Impossible to retrieve a template for the required template id: {e}"), + PoisonLock(e) => write!(f, "Poison lock: {e}"), + JobNotUpdated(ds_job_id, us_job_id) => write!(f, "Channel Factory did not update job: Downstream job id = {ds_job_id}, Upstream job id = {us_job_id}"), + TargetError(e) => write!(f, "Impossible to get Target: {e:?}"), + HashrateError(e) => write!(f, "Impossible to get Hashrate: {e:?}"), + LogicErrorMessage(e) => write!(f, "Message is well formatted but can not be handled: {e:?}"), + JDSMissingTransactions => write!(f, "JD server cannot propagate the block: missing transactions"), + IoError(e) => write!(f, "IO error: {e:?}"), + ExtendedExtranonceCreationFailed(e) => write!(f, "Failed to create ExtendedExtranonce: {e}"), + FromSliceError(e) => write!(f, "Failed to hash from slice: {e}"), + InvalidUserIdentity(e) => write!(f, "Invalid user identity: {e}"), + ExtranoncePrefixFactoryError(e) => write!(f, "Failed to create ExtranoncePrefixFactory: {e:?}"), + Vardiff(e) => write!(f, "Failed to adjust diff in vardiff module: {e:?}"), + FailedToCreateStandardChannel(e) => write!(f, "Failed to create StandardChannel: {e:?}"), + FailedToCreateExtendedChannel(e) => write!(f, "Failed to create ExtendedChannel: {e:?}"), + FailedToProcessNewTemplateGroupChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), + FailedToProcessSetNewPrevHashGroupChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), + NoActiveJob => write!(f, "No active job"), + FailedToUpdateStandardChannel(e) => write!(f, "Failed to update StandardChannel: {e:?}"), + FailedToUpdateExtendedChannel(e) => write!(f, "Failed to update ExtendedChannel: {e:?}"), + FailedToSendSolution => write!(f, "Failed to send solution"), + FailedToSetCustomMiningJob(e) => write!(f, "Failed to set custom mining job: {e:?}"), + FailedToProcessNewTemplateExtendedChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), + FailedToProcessNewTemplateStandardChannel(e) => write!(f, "Failed to process NewTemplate: {e:?}"), + FailedToProcessSetNewPrevHashExtendedChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), + FailedToProcessSetNewPrevHashStandardChannel(e) => write!(f, "Failed to process SetNewPrevHash: {e:?}"), + FailedToDeserializeCoinbaseOutputs => write!(f, "Failed to deserialize coinbase outputs"), + FailedToProcessGroupChannelJob(e) => write!(f, "Failed to process group channel job: {e:?}"), + ParserError(v) => write!(f, "Parser error: {v}"), + } + } +} + +impl From>> for Error { + fn from(value: PoisonError>) -> Self { + Error::PoisonLock(value.to_string()) + } +} diff --git a/roles/stratum-apps/src/lib.rs b/roles/stratum-apps/src/lib.rs index 6a9060717c..3a4ad0773a 100644 --- a/roles/stratum-apps/src/lib.rs +++ b/roles/stratum-apps/src/lib.rs @@ -25,8 +25,11 @@ //! - [`rpc`] - RPC utilities with custom serializable types (`Hash`, `BlockHash`, `Amount`) /// Re-export all the modules from `stratum_core` +#[cfg(feature = "core")] pub use stratum_core; - +/// A wrapper around std::sync:Mutex +pub mod custom_mutex; +pub mod errors; /// High-level networking utilities for SV2 connections /// /// Provides connection management, encrypted streams, and protocol handling. diff --git a/roles/test-utils/mining-device/Cargo.toml b/roles/test-utils/mining-device/Cargo.toml index 6b766cccac..ae00e9d8c1 100644 --- a/roles/test-utils/mining-device/Cargo.toml +++ b/roles/test-utils/mining-device/Cargo.toml @@ -20,23 +20,8 @@ path = "src/lib/mod.rs" [dependencies] -# Using published crates from crates.io -rpc_sv2 = { version = "1.1.0" } -config_helpers_sv2 = { version = "0.1.0" } -network_helpers_sv2 = { version = "4.0.0" } -roles_logic_sv2 = { version = "5.0.0" } -# Published protocol crates to match roles_logic_sv2 v5.0.0 -binary_sv2 = { version = "4.0.0" } -parsers_sv2 = { version = "0.1" } -codec_sv2 = { version = "3.0.0" } -framing_sv2 = { version = "5.0.0" } -noise_sv2 = { version = "1.1" } -common_messages_sv2 = { version = "6.0.0" } -mining_sv2 = { version = "5.0" } -buffer_sv2 = { version = "2.0" } -# Utility crates -key-utils = { version = "1.2.0" } -bitcoin = "0.32.5" +stratum-apps = {path = "../../stratum-apps/", features = ["mining_device"]} +roles_logic_sv2 = {version = "4.0.0"} async-channel = "1.5.1" async-recursion = "0.3.2" rand = "0.8.4" @@ -66,3 +51,7 @@ harness = false [[bench]] name = "scaling_bench" harness = false + + +[patch.crates-io] +key-utils = { path = "../../../utils/key-utils" } diff --git a/roles/test-utils/mining-device/src/lib/mod.rs b/roles/test-utils/mining-device/src/lib/mod.rs index c7af0a16fe..d1a3ea3ee4 100644 --- a/roles/test-utils/mining-device/src/lib/mod.rs +++ b/roles/test-utils/mining-device/src/lib/mod.rs @@ -1,16 +1,16 @@ #![allow(clippy::option_map_unit_fn)] use async_channel::{Receiver, Sender}; -use bitcoin::{blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget}; -use codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}; -use common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}; -use key_utils::Secp256k1PublicKey; -use mining_sv2::*; -use network_helpers_sv2::noise_connection::Connection; -use noise_sv2::Initiator; use num_format::{Locale, ToFormattedString}; -use parsers_sv2::{Mining, MiningDeviceMessages}; use primitive_types::U256; use rand::{thread_rng, Rng}; +use roles_logic_sv2::bitcoin::{ + blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, +}; +use roles_logic_sv2::codec_sv2::noise_sv2::Initiator; +use roles_logic_sv2::codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}; +use roles_logic_sv2::common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}; +use roles_logic_sv2::mining_sv2::*; +use roles_logic_sv2::parsers_sv2::{Mining, MiningDeviceMessages}; use roles_logic_sv2::{ errors::Error, handlers::{ @@ -28,11 +28,13 @@ use std::{ thread::available_parallelism, time::{Duration, Instant}, }; +use stratum_apps::key_utils::Secp256k1PublicKey; +use stratum_apps::network_helpers::noise_connection::Connection; use tokio::net::TcpStream; use tracing::{debug, error, info}; // Fast SHA256d midstate hasher -use bitcoin::consensus::encode::serialize as btc_serialize; +use roles_logic_sv2::bitcoin::consensus::encode::serialize as btc_serialize; use sha2::{ compress256, digest::generic_array::{typenum::U64, GenericArray}, @@ -150,8 +152,8 @@ pub type StdFrame = StandardSv2Frame; pub type EitherFrame = StandardEitherFrame; struct SetupConnectionHandler {} -use bitcoin::block::Version; -use common_messages_sv2::Reconnect; +use roles_logic_sv2::bitcoin::block::Version; +use roles_logic_sv2::common_messages_sv2::Reconnect; use std::convert::TryInto; impl SetupConnectionHandler { @@ -223,7 +225,7 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_setup_connection_error( &mut self, - _: common_messages_sv2::SetupConnectionError, + _: roles_logic_sv2::common_messages_sv2::SetupConnectionError, ) -> Result { error!("Setup connection error"); todo!() @@ -231,7 +233,7 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_channel_endpoint_changed( &mut self, - _: common_messages_sv2::ChannelEndpointChanged, + _: roles_logic_sv2::common_messages_sv2::ChannelEndpointChanged, ) -> Result { todo!() } @@ -365,9 +367,10 @@ impl Device { .safe_lock(|s| s.notify_changes_to_mining_thread.clone()) .unwrap(); if notify_changes_to_mining_thread.should_send - && (message_type == mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB - || message_type == mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH - || message_type == mining_sv2::MESSAGE_TYPE_SET_TARGET) + && (message_type == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB + || message_type + == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH + || message_type == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_SET_TARGET) { notify_changes_to_mining_thread .sender diff --git a/roles/translator/src/lib/error.rs b/roles/translator/src/lib/error.rs index 8fba09339c..2c5897f290 100644 --- a/roles/translator/src/lib/error.rs +++ b/roles/translator/src/lib/error.rs @@ -10,13 +10,12 @@ use ext_config::ConfigError; use std::{fmt, sync::PoisonError}; -use stratum_apps::stratum_core::{ - binary_sv2, framing_sv2, - handlers_sv2::HandlerErrorType, - noise_sv2, - parsers_sv2::ParserError as RolesParserError, - roles_logic_sv2::{errors::Error as RolesLogicError, Error as RolesSv2Error}, - sv1_api::server_to_client::SetDifficulty, +use stratum_apps::{ + errors::Error, + stratum_core::{ + binary_sv2, framing_sv2, handlers_sv2::HandlerErrorType, noise_sv2, + parsers_sv2::ParserError as RolesParserError, sv1_api::server_to_client::SetDifficulty, + }, }; use tokio::sync::broadcast; @@ -27,7 +26,7 @@ pub enum TproxyError { /// Error from the network helpers library NetworkHelpersError(stratum_apps::network_helpers::Error), /// Error from the roles logic library - RolesSv2LogicError(RolesSv2Error), + RolesSv2LogicError(Error), /// Error from roles logic parser library ParserError(RolesParserError), /// Errors on bad CLI argument input. @@ -47,7 +46,7 @@ pub enum TproxyError { /// Errors on bad `String` to `int` conversion. ParseInt(std::num::ParseIntError), /// Error parsing incoming upstream messages - UpstreamIncoming(RolesLogicError), + UpstreamIncoming(Error), /// Mutex poison lock error PoisonLock, /// Channel receiver error diff --git a/roles/translator/src/lib/sv1/downstream/data.rs b/roles/translator/src/lib/sv1/downstream/data.rs index 35d1b1ef9f..cf09dbf0a3 100644 --- a/roles/translator/src/lib/sv1/downstream/data.rs +++ b/roles/translator/src/lib/sv1/downstream/data.rs @@ -2,10 +2,12 @@ use std::{ cell::RefCell, sync::{atomic::AtomicBool, Arc}, }; -use stratum_apps::stratum_core::{ - mining_sv2::Target, - roles_logic_sv2::utils::Mutex, - sv1_api::{json_rpc, utils::HexU32Be}, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + mining_sv2::Target, + sv1_api::{json_rpc, utils::HexU32Be}, + }, }; use tracing::debug; diff --git a/roles/translator/src/lib/sv1/downstream/downstream.rs b/roles/translator/src/lib/sv1/downstream/downstream.rs index 9410fe8377..3190fbf9ba 100644 --- a/roles/translator/src/lib/sv1/downstream/downstream.rs +++ b/roles/translator/src/lib/sv1/downstream/downstream.rs @@ -11,12 +11,14 @@ use crate::{ }; use async_channel::{Receiver, Sender}; use std::sync::Arc; -use stratum_apps::stratum_core::{ - mining_sv2::Target, - roles_logic_sv2::utils::Mutex, - sv1_api::{ - json_rpc::{self, Message}, - server_to_client, IsServer, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + mining_sv2::Target, + sv1_api::{ + json_rpc::{self, Message}, + server_to_client, IsServer, + }, }, }; use tokio::sync::{broadcast, mpsc}; diff --git a/roles/translator/src/lib/sv1/sv1_server/difficulty_manager.rs b/roles/translator/src/lib/sv1/sv1_server/difficulty_manager.rs index d050ae5a56..0774c99c02 100644 --- a/roles/translator/src/lib/sv1/sv1_server/difficulty_manager.rs +++ b/roles/translator/src/lib/sv1/sv1_server/difficulty_manager.rs @@ -4,13 +4,15 @@ use crate::{ }; use async_channel::Sender; use std::{collections::HashMap, sync::Arc, time::Duration}; -use stratum_apps::stratum_core::{ - channels_sv2::{target::hash_rate_to_target, Vardiff}, - mining_sv2::{SetTarget, Target, UpdateChannel}, - parsers_sv2::Mining, - roles_logic_sv2::utils::Mutex, - stratum_translation::sv2_to_sv1::build_sv1_set_difficulty_from_sv2_target, - sv1_api::json_rpc, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + channels_sv2::{target::hash_rate_to_target, Vardiff}, + mining_sv2::{SetTarget, Target, UpdateChannel}, + parsers_sv2::Mining, + stratum_translation::sv2_to_sv1::build_sv1_set_difficulty_from_sv2_target, + sv1_api::json_rpc, + }, }; use tokio::{sync::broadcast, time}; use tracing::{debug, error, info, trace, warn}; diff --git a/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs b/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs index ba3ce943cf..373c2af3a7 100644 --- a/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs +++ b/roles/translator/src/lib/sv1/sv1_server/sv1_server.rs @@ -22,13 +22,13 @@ use std::{ }, }; use stratum_apps::{ + custom_mutex::Mutex, network_helpers::sv1_connection::ConnectionSV1, stratum_core::{ binary_sv2::Str0255, channels_sv2::{target::hash_rate_to_target, Vardiff, VardiffState}, mining_sv2::{CloseChannel, SetTarget, Target}, parsers_sv2::Mining, - roles_logic_sv2::utils::Mutex, stratum_translation::{ sv1_to_sv2::{ build_sv2_open_extended_mining_channel, diff --git a/roles/translator/src/lib/sv2/channel_manager/channel_manager.rs b/roles/translator/src/lib/sv2/channel_manager/channel_manager.rs index 978b649d6f..397894c522 100644 --- a/roles/translator/src/lib/sv2/channel_manager/channel_manager.rs +++ b/roles/translator/src/lib/sv2/channel_manager/channel_manager.rs @@ -13,13 +13,15 @@ use crate::{ }; use async_channel::{Receiver, Sender}; use std::sync::{Arc, RwLock}; -use stratum_apps::stratum_core::{ - channels_sv2::client::extended::ExtendedChannel, - framing_sv2::framing::Frame, - handlers_sv2::HandleMiningMessagesFromServerAsync, - mining_sv2::OpenExtendedMiningChannelSuccess, - parsers_sv2::{AnyMessage, Mining}, - roles_logic_sv2::utils::Mutex, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + channels_sv2::client::extended::ExtendedChannel, + framing_sv2::framing::Frame, + handlers_sv2::HandleMiningMessagesFromServerAsync, + mining_sv2::OpenExtendedMiningChannelSuccess, + parsers_sv2::{AnyMessage, Mining}, + }, }; use tokio::sync::{broadcast, mpsc}; use tracing::{debug, error, info, warn}; diff --git a/roles/translator/src/lib/sv2/channel_manager/data.rs b/roles/translator/src/lib/sv2/channel_manager/data.rs index 18208be144..c79bae825b 100644 --- a/roles/translator/src/lib/sv2/channel_manager/data.rs +++ b/roles/translator/src/lib/sv2/channel_manager/data.rs @@ -2,9 +2,11 @@ use std::{ collections::HashMap, sync::{Arc, RwLock}, }; -use stratum_apps::stratum_core::{ - channels_sv2::client::extended::ExtendedChannel, mining_sv2::ExtendedExtranonce, - roles_logic_sv2::utils::Mutex, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + channels_sv2::client::extended::ExtendedChannel, mining_sv2::ExtendedExtranonce, + }, }; /// Defines the operational mode for channel management. diff --git a/roles/translator/src/lib/sv2/channel_manager/message_handler.rs b/roles/translator/src/lib/sv2/channel_manager/message_handler.rs index 4019ec7b85..1806d2c611 100644 --- a/roles/translator/src/lib/sv2/channel_manager/message_handler.rs +++ b/roles/translator/src/lib/sv2/channel_manager/message_handler.rs @@ -5,6 +5,8 @@ use crate::{ sv2::{channel_manager::ChannelMode, ChannelManager}, utils::proxy_extranonce_prefix_len, }; +use stratum_apps::custom_mutex::Mutex; + use stratum_apps::stratum_core::{ channels_sv2::client::extended::ExtendedChannel, handlers_sv2::{HandleMiningMessagesFromServerAsync, SupportedChannelTypes}, @@ -18,7 +20,6 @@ use stratum_apps::stratum_core::{ MESSAGE_TYPE_SET_GROUP_CHANNEL, }, parsers_sv2::Mining, - roles_logic_sv2::utils::Mutex, }; use tracing::{debug, error, info, warn}; diff --git a/roles/translator/src/lib/utils.rs b/roles/translator/src/lib/utils.rs index 431b1c916d..75bea673a2 100644 --- a/roles/translator/src/lib/utils.rs +++ b/roles/translator/src/lib/utils.rs @@ -1,20 +1,22 @@ -use stratum_apps::stratum_core::{ - binary_sv2::{Sv2DataType, U256}, - bitcoin::{ - block::{Header, Version}, - hashes::Hash, - CompactTarget, TxMerkleNode, - }, - buffer_sv2::Slice, - channels_sv2::{ - merkle_root::merkle_root_from_path, - target::{bytes_to_hex, u256_to_block_hash}, +use stratum_apps::{ + custom_mutex::Mutex, + stratum_core::{ + binary_sv2::{Sv2DataType, U256}, + bitcoin::{ + block::{Header, Version}, + hashes::Hash, + CompactTarget, TxMerkleNode, + }, + buffer_sv2::Slice, + channels_sv2::{ + merkle_root::merkle_root_from_path, + target::{bytes_to_hex, u256_to_block_hash}, + }, + framing_sv2::framing::Frame, + mining_sv2::Target, + parsers_sv2::{AnyMessage, CommonMessages}, + sv1_api::{client_to_server, utils::HexU32Be}, }, - framing_sv2::framing::Frame, - mining_sv2::Target, - parsers_sv2::{AnyMessage, CommonMessages}, - roles_logic_sv2::utils::Mutex, - sv1_api::{client_to_server, utils::HexU32Be}, }; use tracing::{debug, error}; diff --git a/test/integration-tests/Cargo.lock b/test/integration-tests/Cargo.lock index 0dcb37133c..e5b863bf86 100644 --- a/test/integration-tests/Cargo.lock +++ b/test/integration-tests/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -881,16 +881,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - -[[package]] -name = "error_handling" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfdf3be9049288001eb8a37f21b0f4e922598a6fa0098630fd3a6a14459ef217" - [[package]] name = "event-listener" version = "2.5.3" @@ -1380,7 +1370,6 @@ dependencies = [ "flate2", "jd_client_sv2", "jd_server", - "key-utils 1.2.0", "mining_device", "minreq", "once_cell", @@ -1431,7 +1420,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils 1.2.0", "serde", "stratum-apps", "tokio", @@ -1443,29 +1431,16 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel", - "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bitcoin", "clap", - "codec_sv2 3.0.1", - "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", - "config_helpers_sv2", - "error_handling 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", - "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "network_helpers_sv2", "nohash-hasher", - "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.8.5", - "roles_logic_sv2 5.0.0", - "rpc_sv2", + "roles_logic_sv2 4.0.0", "serde", "serde_json", + "stratum-apps", "tokio", "tracing", ] @@ -1509,18 +1484,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "key-utils" -version = "1.2.0" -dependencies = [ - "bs58", - "generic-array", - "rand 0.8.5", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - [[package]] name = "key-utils" version = "1.2.0" @@ -1614,7 +1577,7 @@ dependencies = [ "config_helpers_sv2", "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", - "key-utils 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "key-utils", "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "network_helpers_sv2", "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1978,8 +1941,6 @@ dependencies = [ "async-channel", "clap", "config", - "error_handling 1.0.0", - "key-utils 1.2.0", "rand 0.8.5", "secp256k1 0.28.2", "serde", @@ -2493,11 +2454,16 @@ name = "stratum-apps" version = "0.1.0" dependencies = [ "async-channel", + "base64 0.21.7", + "bs58", "clap", "config", - "error_handling 1.0.0", "futures", - "key-utils 1.2.0", + "generic-array", + "hex", + "http-body-util", + "hyper", + "hyper-util", "miniscript", "rand 0.8.5", "rustversion", @@ -2903,7 +2869,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils 1.2.0", "serde", "serde_json", "stratum-apps", diff --git a/test/integration-tests/Cargo.toml b/test/integration-tests/Cargo.toml index 42f66452b0..884ec26136 100644 --- a/test/integration-tests/Cargo.toml +++ b/test/integration-tests/Cargo.toml @@ -30,4 +30,4 @@ tracing = { version = "0.1.41", default-features = false } tracing-subscriber = { version = "0.3.19", default-features = false } [lib] -path = "lib/mod.rs" \ No newline at end of file +path = "lib/mod.rs" diff --git a/test/integration-tests/lib/message_aggregator.rs b/test/integration-tests/lib/message_aggregator.rs index 34cca5f23c..5f8e64593f 100644 --- a/test/integration-tests/lib/message_aggregator.rs +++ b/test/integration-tests/lib/message_aggregator.rs @@ -1,5 +1,6 @@ use std::{collections::VecDeque, sync::Arc}; -use stratum_apps::stratum_core::{parsers_sv2::AnyMessage, roles_logic_sv2::utils::Mutex}; +use stratum_apps::custom_mutex::Mutex; +use stratum_apps::stratum_core::parsers_sv2::AnyMessage; use crate::types::MsgType; diff --git a/test/integration-tests/lib/mod.rs b/test/integration-tests/lib/mod.rs index a93b836a47..3faf7e3531 100644 --- a/test/integration-tests/lib/mod.rs +++ b/test/integration-tests/lib/mod.rs @@ -10,10 +10,8 @@ use std::{ net::{Ipv4Addr, SocketAddr}, time::Duration, }; -use stratum_apps::{ - config_helpers::CoinbaseRewardScript, - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, -}; +use stratum_apps::config_helpers::CoinbaseRewardScript; +use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use tracing::Level; use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; use translator_sv2::TranslatorSv2; diff --git a/test/integration-tests/lib/utils.rs b/test/integration-tests/lib/utils.rs index 0c7c8575b8..bf8929ca81 100644 --- a/test/integration-tests/lib/utils.rs +++ b/test/integration-tests/lib/utils.rs @@ -5,6 +5,7 @@ use crate::{ types::{MessageFrame, MsgType}, }; use async_channel::{Receiver, Sender}; +use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use once_cell::sync::Lazy; use std::{ collections::HashSet, @@ -13,7 +14,6 @@ use std::{ sync::Mutex, }; use stratum_apps::{ - key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_connection::Connection, stratum_core::{ codec_sv2::{HandshakeRole, StandardEitherFrame}, From 93c1209b7bd9502585b3cf9a57a700eaaa1362f1 Mon Sep 17 00:00:00 2001 From: GitGab19 Date: Fri, 17 Oct 2025 00:57:29 +0200 Subject: [PATCH 5/5] Migrate JD Server and test-utils/mining-device to use published crates.io versions of protocol crates instead of local workspace versions. This allows these components to use the deprecated roles_logic_sv2 while the rest of the workspace continues with local implementations. - Add crates.io protocol dependencies (roles_logic_sv2, codec_sv2, etc.) - Update imports to use direct crate references - Use network_helpers_sv2 and rpc_sv2 from crates.io - Configure stratum-apps to exclude core/network features for jd_server --- benches/Cargo.toml | 2 +- protocols/Cargo.toml | 1 - roles/Cargo.lock | 175 +++++++++--------- roles/jd-server/Cargo.toml | 13 +- roles/jd-server/src/lib/config.rs | 8 +- roles/jd-server/src/lib/error.rs | 10 +- .../src/lib/job_declarator/message_handler.rs | 10 +- roles/jd-server/src/lib/job_declarator/mod.rs | 28 +-- roles/jd-server/src/lib/mempool/error.rs | 2 +- roles/jd-server/src/lib/mempool/mod.rs | 8 +- roles/jd-server/src/lib/mod.rs | 6 +- roles/jd-server/src/lib/status.rs | 15 +- roles/jd-server/src/main.rs | 2 +- roles/stratum-apps/Cargo.toml | 10 +- roles/test-utils/mining-device/Cargo.toml | 11 +- roles/test-utils/mining-device/src/lib/mod.rs | 33 ++-- test/integration-tests/Cargo.lock | 144 +++----------- .../lib/message_aggregator.rs | 3 +- test/integration-tests/lib/mod.rs | 6 +- test/integration-tests/lib/utils.rs | 2 +- 20 files changed, 215 insertions(+), 274 deletions(-) diff --git a/benches/Cargo.toml b/benches/Cargo.toml index 24c541d7c3..083080a3d6 100644 --- a/benches/Cargo.toml +++ b/benches/Cargo.toml @@ -12,7 +12,7 @@ v1 = { path="../protocols/v1", package="sv1_api" } serde_json = { version = "1.0.64", default-features = false, features = ["alloc"] } iai="0.1" mining_sv2 = { path = "../protocols/v2/subprotocols/mining" } -roles_logic_sv2 = { path = "../protocols/v2/roles-logic-sv2" } +roles_logic_sv2 = "5.0.0" framing_sv2 = { path = "../protocols/v2/framing-sv2" } serde = { version = "1.0.89", default-features = false, features = ["derive", "alloc"] } num-bigint = "0.4.3" diff --git a/protocols/Cargo.toml b/protocols/Cargo.toml index 60cb571df9..9dba924c2f 100644 --- a/protocols/Cargo.toml +++ b/protocols/Cargo.toml @@ -14,7 +14,6 @@ members = [ "v2/subprotocols/template-distribution", "v2/subprotocols/mining", "v2/subprotocols/job-declaration", - "v2/roles-logic-sv2", "v2/channels-sv2", "v2/parsers-sv2", "v2/handlers-sv2", diff --git a/roles/Cargo.lock b/roles/Cargo.lock index bbea2ae658..a591ca9197 100644 --- a/roles/Cargo.lock +++ b/roles/Cargo.lock @@ -1,21 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +version = 3 [[package]] name = "aead" @@ -392,21 +377,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link 0.2.1", -] - [[package]] name = "base58ck" version = "0.1.0" @@ -674,9 +644,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" @@ -1378,12 +1348,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - [[package]] name = "gloo-timers" version = "0.3.0" @@ -1696,17 +1660,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "io-uring" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046fa2d4d00aea763528b4950358d0ead425372445dc8ff86312b3c69ff7727b" -dependencies = [ - "bitflags 2.9.4", - "cfg-if", - "libc", -] - [[package]] name = "ipnet" version = "2.11.0" @@ -1763,13 +1716,24 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel 1.9.0", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", "nohash-hasher", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand", - "roles_logic_sv2", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "serde", "serde_json", "stratum-apps", @@ -1898,15 +1862,24 @@ version = "0.1.3" dependencies = [ "async-channel 1.9.0", "async-recursion", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "criterion", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", "half", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-format", "num_cpus", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types", "rand", - "roles_logic_sv2", + "roles_logic_sv2 5.0.0", "sha2 0.10.9", "stratum-apps", "tokio", @@ -1940,15 +1913,6 @@ dependencies = [ "bitcoin", ] -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", -] - [[package]] name = "mio" version = "1.0.4" @@ -1960,6 +1924,19 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "network_helpers_sv2" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d720d6a31532fb4f08e59b71669084d06462f42e9d2c2aede7368d221d36db" +dependencies = [ + "async-channel 1.9.0", + "codec_sv2 3.0.1", + "futures", + "tokio", + "tracing", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2039,15 +2016,6 @@ dependencies = [ "libc", ] -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - [[package]] name = "once_cell" version = "1.21.3" @@ -2456,6 +2424,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "roles_logic_sv2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88850ead16993f86cb4616d154ddd37b9c0d739ea23711b1cc51f40484e0e39a" +dependencies = [ + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", + "chacha20poly1305", + "channels_sv2 1.0.2", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "handlers_sv2 0.1.0", + "hex-conservative 0.3.0", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "nohash-hasher", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types", + "template_distribution_sv2 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing", +] + [[package]] name = "ron" version = "0.8.1" @@ -2468,6 +2459,22 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rpc_sv2" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9b3a6c43d03c5cc6ca9f40797cbf17a9a30b8db236be6c87f5243bd404d6af" +dependencies = [ + "base64 0.21.7", + "hex", + "http-body-util", + "hyper", + "hyper-util", + "serde", + "serde_json", + "stratum-common", +] + [[package]] name = "rust-ini" version = "0.20.0" @@ -2478,12 +2485,6 @@ dependencies = [ "ordered-multimap", ] -[[package]] -name = "rustc-demangle" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" - [[package]] name = "rustc-hex" version = "2.1.0" @@ -2789,6 +2790,15 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "stratum-common" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77b7dc7a762d19aba6f355599a61440b29603ceece5a158914888691b9867ebe" +dependencies = [ + "roles_logic_sv2 4.0.0", +] + [[package]] name = "stratum-core" version = "0.1.0" @@ -2961,29 +2971,26 @@ dependencies = [ [[package]] name = "tokio" -version = "1.47.1" +version = "1.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ - "backtrace", "bytes", - "io-uring", "libc", "mio", "parking_lot", "pin-project-lite", "signal-hook-registry", - "slab", "socket2 0.6.1", "tokio-macros", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", diff --git a/roles/jd-server/Cargo.toml b/roles/jd-server/Cargo.toml index f8ed98eb95..5488fd29fc 100644 --- a/roles/jd-server/Cargo.toml +++ b/roles/jd-server/Cargo.toml @@ -18,7 +18,18 @@ path = "src/lib/mod.rs" [dependencies] stratum-apps = { path = "../stratum-apps", features = ["jd_server"] } -roles_logic_sv2 = "4.0.0" +roles_logic_sv2 = "5.0.0" +binary_sv2 = "4.0.0" +codec_sv2 = "3.0.1" +framing_sv2 = "5.0.1" +mining_sv2 = "5.0.1" +noise_sv2 = "1.4.0" +parsers_sv2 = "0.1.1" +job_declaration_sv2 = "5.0.1" +common_messages_sv2 = "6.0.1" +network_helpers_sv2 = "4.0.1" +rpc_sv2 = "1.1.1" +bitcoin = "0.32.5" async-channel = "1.5.1" rand = "0.8.4" tokio = { version = "1.44.1", features = ["full"] } diff --git a/roles/jd-server/src/lib/config.rs b/roles/jd-server/src/lib/config.rs index b3d95ecfe2..85a34f4be9 100644 --- a/roles/jd-server/src/lib/config.rs +++ b/roles/jd-server/src/lib/config.rs @@ -16,8 +16,10 @@ use std::{ path::{Path, PathBuf}, time::Duration, }; -use stratum_apps::config_helpers::CoinbaseRewardScript; -use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; +use stratum_apps::{ + config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, +}; #[derive(Debug, serde::Deserialize, Clone)] pub struct JobDeclaratorServerConfig { @@ -173,8 +175,8 @@ impl CoreRpc { #[cfg(test)] mod tests { use super::super::JobDeclaratorServer; + use bitcoin::{self, Amount, ScriptBuf, TxOut}; use ext_config::{Config, ConfigError, File, FileFormat}; - use roles_logic_sv2::bitcoin::{self, Amount, ScriptBuf, TxOut}; use std::path::PathBuf; use crate::config::JobDeclaratorServerConfig; diff --git a/roles/jd-server/src/lib/error.rs b/roles/jd-server/src/lib/error.rs index 323eeb119b..38844c4f83 100644 --- a/roles/jd-server/src/lib/error.rs +++ b/roles/jd-server/src/lib/error.rs @@ -19,12 +19,12 @@ use std::{ sync::{MutexGuard, PoisonError}, }; +use binary_sv2; +use codec_sv2; +use framing_sv2; +use noise_sv2; +use parsers_sv2::Mining; use roles_logic_sv2; -use roles_logic_sv2::codec_sv2; -use roles_logic_sv2::codec_sv2::binary_sv2; -use roles_logic_sv2::codec_sv2::framing_sv2; -use roles_logic_sv2::codec_sv2::noise_sv2; -use roles_logic_sv2::parsers_sv2::Mining; use crate::mempool::error::JdsMempoolError; diff --git a/roles/jd-server/src/lib/job_declarator/message_handler.rs b/roles/jd-server/src/lib/job_declarator/message_handler.rs index eabc8b75a1..b5644bad41 100644 --- a/roles/jd-server/src/lib/job_declarator/message_handler.rs +++ b/roles/jd-server/src/lib/job_declarator/message_handler.rs @@ -1,15 +1,15 @@ -use roles_logic_sv2::bitcoin::{ +use binary_sv2::{Decodable, Serialize, U256}; +use bitcoin::{ consensus::Decodable as BitcoinDecodable, hashes::{sha256d, Hash}, Transaction, Txid, }; -use roles_logic_sv2::codec_sv2::binary_sv2::{Decodable, Serialize, U256}; -use roles_logic_sv2::job_declaration_sv2::{ +use job_declaration_sv2::{ AllocateMiningJobToken, AllocateMiningJobTokenSuccess, DeclareMiningJob, DeclareMiningJobError, DeclareMiningJobSuccess, ProvideMissingTransactions, ProvideMissingTransactionsSuccess, PushSolution, }; -use roles_logic_sv2::parsers_sv2::JobDeclaration; +use parsers_sv2::JobDeclaration; use roles_logic_sv2::{ errors::Error, handlers::{job_declaration::ParseJobDeclarationMessagesFromDownstream, SendTo_}, @@ -24,7 +24,7 @@ pub type SendTo = SendTo_, ()>; use crate::mempool::JDsMempool; use super::{signed_token, TransactionState}; -use roles_logic_sv2::parsers_sv2::AnyMessage as AllMessages; +use parsers_sv2::AnyMessage as AllMessages; use tracing::{debug, info}; use super::JobDeclaratorDownstream; diff --git a/roles/jd-server/src/lib/job_declarator/mod.rs b/roles/jd-server/src/lib/job_declarator/mod.rs index 1296ef7957..74b46b074f 100644 --- a/roles/jd-server/src/lib/job_declarator/mod.rs +++ b/roles/jd-server/src/lib/job_declarator/mod.rs @@ -22,22 +22,23 @@ use super::{ error::JdsError, mempool::JDsMempool, status, EitherFrame, JobDeclaratorServerConfig, StdFrame, }; use async_channel::{Receiver, Sender}; -use core::panic; -use nohash_hasher::BuildNoHashHasher; -use roles_logic_sv2::bitcoin::{ +use binary_sv2::{self, B0255, U256}; +use bitcoin::{ block::{Header, Version}, consensus::{deserialize, encode::serialize}, hashes::{sha256d::Hash as DHash, Hash}, Amount, Block, BlockHash, CompactTarget, Transaction, TxOut, Txid, }; -use roles_logic_sv2::codec_sv2::binary_sv2::{self, B0255, U256}; -use roles_logic_sv2::codec_sv2::noise_sv2::Responder; -use roles_logic_sv2::codec_sv2::HandshakeRole; -use roles_logic_sv2::common_messages_sv2::{ +use codec_sv2::HandshakeRole; +use common_messages_sv2::{ Protocol, SetupConnection, SetupConnectionError, SetupConnectionSuccess, }; -use roles_logic_sv2::job_declaration_sv2::{DeclareMiningJob, PushSolution}; -use roles_logic_sv2::parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}; +use core::panic; +use job_declaration_sv2::{DeclareMiningJob, PushSolution}; +use network_helpers_sv2::noise_connection::Connection; +use nohash_hasher::BuildNoHashHasher; +use noise_sv2::Responder; +use parsers_sv2::{AnyMessage as JdsMessages, JobDeclaration}; use roles_logic_sv2::{ handlers::job_declaration::{ParseJobDeclarationMessagesFromDownstream, SendTo}, utils::Mutex, @@ -47,9 +48,10 @@ use std::{ convert::TryInto, sync::{atomic::AtomicU32, Arc}, }; -use stratum_apps::handle_result; -use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; -use stratum_apps::network_helpers::noise_connection::Connection; +use stratum_apps::{ + handle_result, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}, +}; use tokio::{net::TcpListener, time::Duration}; use tracing::{debug, error, info}; @@ -273,7 +275,7 @@ impl JobDeclaratorDownstream { /// Wraps the message into a `StdFrame` and sends it through the established channel. pub async fn send( self_mutex: Arc>, - message: roles_logic_sv2::parsers_sv2::JobDeclaration<'static>, + message: parsers_sv2::JobDeclaration<'static>, ) -> Result<(), ()> { let sv2_frame: StdFrame = JdsMessages::JobDeclaration(message).try_into().unwrap(); let sender = self_mutex.safe_lock(|self_| self_.sender.clone()).unwrap(); diff --git a/roles/jd-server/src/lib/mempool/error.rs b/roles/jd-server/src/lib/mempool/error.rs index 15f5a84951..cb0e2a2971 100644 --- a/roles/jd-server/src/lib/mempool/error.rs +++ b/roles/jd-server/src/lib/mempool/error.rs @@ -11,8 +11,8 @@ //! It also includes a centralized error logging helper (`handle_error`) to standardize warnings //! and diagnostics across components. +use rpc_sv2::mini_rpc_client::RpcError; use std::{convert::From, sync::PoisonError}; -use stratum_apps::rpc::mini_rpc_client::RpcError; use tracing::{error, warn}; /// Errors that may occur during JDS mempool operations. diff --git a/roles/jd-server/src/lib/mempool/mod.rs b/roles/jd-server/src/lib/mempool/mod.rs index 8684545d9f..866f406675 100644 --- a/roles/jd-server/src/lib/mempool/mod.rs +++ b/roles/jd-server/src/lib/mempool/mod.rs @@ -19,11 +19,11 @@ pub mod error; use super::job_declarator::AddTrasactionsToMempoolInner; use crate::mempool::error::JdsMempoolError; use async_channel::Receiver; +use bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}; use hashbrown::HashMap; -use roles_logic_sv2::bitcoin::{blockdata::transaction::Transaction, hash_types::Txid}; use roles_logic_sv2::utils::Mutex; +use rpc_sv2::{mini_rpc_client, mini_rpc_client::RpcError}; use std::{str::FromStr, sync::Arc}; -use stratum_apps::rpc::{mini_rpc_client, mini_rpc_client::RpcError}; /// Wrapper around a known transaction and its hash. #[derive(Clone, Debug)] @@ -40,7 +40,7 @@ pub struct JDsMempool { /// Auth for RPC connection to the node. auth: mini_rpc_client::Auth, /// URI of the Bitcoin node. - url: stratum_apps::rpc::Uri, + url: rpc_sv2::Uri, /// Receiver for new block solutions coming from JDC. new_block_receiver: Receiver, } @@ -68,7 +68,7 @@ impl JDsMempool { /// Instantiates a new empty mempool for JDS. pub fn new( - url: stratum_apps::rpc::Uri, + url: rpc_sv2::Uri, username: String, password: String, new_block_receiver: Receiver, diff --git a/roles/jd-server/src/lib/mod.rs b/roles/jd-server/src/lib/mod.rs index 0d4af32cf2..933570f55b 100644 --- a/roles/jd-server/src/lib/mod.rs +++ b/roles/jd-server/src/lib/mod.rs @@ -23,16 +23,16 @@ pub mod job_declarator; pub mod mempool; pub mod status; use async_channel::{bounded, unbounded, Receiver, Sender}; +use codec_sv2::{StandardEitherFrame, StandardSv2Frame}; use config::JobDeclaratorServerConfig; use error::JdsError; use job_declarator::JobDeclarator; use mempool::error::JdsMempoolError; -use roles_logic_sv2::codec_sv2::{StandardEitherFrame, StandardSv2Frame}; -use roles_logic_sv2::parsers_sv2::AnyMessage as JdsMessages; +use parsers_sv2::AnyMessage as JdsMessages; use roles_logic_sv2::utils::Mutex; +pub use rpc_sv2::Uri; use std::{ops::Sub, str::FromStr, sync::Arc}; use stratum_apps::handle_result; -pub use stratum_apps::rpc::Uri; use tokio::{select, task}; use tracing::{error, info, warn}; diff --git a/roles/jd-server/src/lib/status.rs b/roles/jd-server/src/lib/status.rs index 680ebeee04..46cd5205d6 100644 --- a/roles/jd-server/src/lib/status.rs +++ b/roles/jd-server/src/lib/status.rs @@ -8,7 +8,7 @@ //! //! This allows for centralized, consistent error handling across the application. -use roles_logic_sv2::parsers_sv2::Mining; +use parsers_sv2::Mining; use stratum_apps::error_handling::ErrorBranch; use super::error::JdsError; @@ -154,12 +154,13 @@ mod tests { use super::*; use async_channel::{bounded, RecvError}; + use binary_sv2; + use codec_sv2; + use framing_sv2; + use mining_sv2; + use noise_sv2; + use parsers_sv2::Mining; use roles_logic_sv2; - use roles_logic_sv2::codec_sv2; - use roles_logic_sv2::codec_sv2::binary_sv2; - use roles_logic_sv2::codec_sv2::framing_sv2; - use roles_logic_sv2::codec_sv2::noise_sv2; - use roles_logic_sv2::parsers_sv2::Mining; #[tokio::test] async fn test_send_status_downstream_listener_shutdown() { @@ -413,7 +414,7 @@ mod tests { let sender = Sender::Downstream(tx); let inner: [u8; 32] = rand::random(); let value = inner.to_vec().try_into().unwrap(); - let error_msg = roles_logic_sv2::mining_sv2::OpenMiningChannelError { + let error_msg = mining_sv2::OpenMiningChannelError { request_id: 1, error_code: value, }; diff --git a/roles/jd-server/src/main.rs b/roles/jd-server/src/main.rs index f17482595d..762a6e5808 100644 --- a/roles/jd-server/src/main.rs +++ b/roles/jd-server/src/main.rs @@ -6,8 +6,8 @@ //! The actual task orchestration and shutdown logic are managed in `lib/mod.rs`. mod args; use args::process_cli_args; -use config_helpers_sv2::logging::init_logging; use jd_server::JobDeclaratorServer; +use stratum_apps::config_helpers::logging::init_logging; use tracing::error; /// Entrypoint for the Job Declarator Server binary. diff --git a/roles/stratum-apps/Cargo.toml b/roles/stratum-apps/Cargo.toml index fd2a4e3e63..8b6331991e 100644 --- a/roles/stratum-apps/Cargo.toml +++ b/roles/stratum-apps/Cargo.toml @@ -51,7 +51,7 @@ ext-config = { version = "0.14.0", features = ["toml"], package = "config" } default = ["network", "config", "std"] # Core module features -network = ["tokio-util"] +network = ["tokio-util", "core"] config = [] rpc = ["serde_json", "hex", "base64", "hyper", "hyper-util", "http-body-util"] std = ["bs58/std", "secp256k1/rand-std", "rand/std", "rand/std_rng"] @@ -63,10 +63,12 @@ with_buffer_pool = ["stratum-core/with_buffer_pool"] # Convenience feature bundles for different role types pool = ["network", "config", "with_buffer_pool", "core"] -jd_client = ["network", "config", "with_buffer_pool", "core"] -jd_server = ["network", "config", "rpc", "with_buffer_pool"] +jd_client = ["network", "config", "with_buffer_pool", "core"] +# Note: jd_server intentionally excludes 'core', 'network', and 'rpc' - it uses crates.io crates directly +jd_server = ["config"] translator = ["network", "config", "sv1", "with_buffer_pool", "core"] -mining_device = ["network", "config", "with_buffer_pool"] +# Note: mining_device intentionally excludes 'core', 'network', and 'rpc' - it uses crates.io crates directly +mining_device = ["config"] [package.metadata.docs.rs] features = ["pool", "jd_client", "jd_server", "translator", "sv1", "rpc"] diff --git a/roles/test-utils/mining-device/Cargo.toml b/roles/test-utils/mining-device/Cargo.toml index ae00e9d8c1..3755794e11 100644 --- a/roles/test-utils/mining-device/Cargo.toml +++ b/roles/test-utils/mining-device/Cargo.toml @@ -21,7 +21,16 @@ path = "src/lib/mod.rs" [dependencies] stratum-apps = {path = "../../stratum-apps/", features = ["mining_device"]} -roles_logic_sv2 = {version = "4.0.0"} +roles_logic_sv2 = "5.0.0" +binary_sv2 = "4.0.0" +codec_sv2 = "3.0.1" +framing_sv2 = "5.0.1" +noise_sv2 = "1.4.0" +parsers_sv2 = "0.1.1" +common_messages_sv2 = "6.0.1" +mining_sv2 = "5.0.1" +network_helpers_sv2 = "4.0.1" +bitcoin = "0.32.5" async-channel = "1.5.1" async-recursion = "0.3.2" rand = "0.8.4" diff --git a/roles/test-utils/mining-device/src/lib/mod.rs b/roles/test-utils/mining-device/src/lib/mod.rs index d1a3ea3ee4..f4b8bb7aec 100644 --- a/roles/test-utils/mining-device/src/lib/mod.rs +++ b/roles/test-utils/mining-device/src/lib/mod.rs @@ -1,16 +1,15 @@ #![allow(clippy::option_map_unit_fn)] use async_channel::{Receiver, Sender}; +use bitcoin::{blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget}; +use codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}; +use common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}; +use mining_sv2::*; +use network_helpers_sv2::noise_connection::Connection; +use noise_sv2::Initiator; use num_format::{Locale, ToFormattedString}; +use parsers_sv2::{Mining, MiningDeviceMessages}; use primitive_types::U256; use rand::{thread_rng, Rng}; -use roles_logic_sv2::bitcoin::{ - blockdata::block::Header, hash_types::BlockHash, hashes::Hash, CompactTarget, -}; -use roles_logic_sv2::codec_sv2::noise_sv2::Initiator; -use roles_logic_sv2::codec_sv2::{self, StandardEitherFrame, StandardSv2Frame}; -use roles_logic_sv2::common_messages_sv2::{Protocol, SetupConnection, SetupConnectionSuccess}; -use roles_logic_sv2::mining_sv2::*; -use roles_logic_sv2::parsers_sv2::{Mining, MiningDeviceMessages}; use roles_logic_sv2::{ errors::Error, handlers::{ @@ -29,12 +28,11 @@ use std::{ time::{Duration, Instant}, }; use stratum_apps::key_utils::Secp256k1PublicKey; -use stratum_apps::network_helpers::noise_connection::Connection; use tokio::net::TcpStream; use tracing::{debug, error, info}; // Fast SHA256d midstate hasher -use roles_logic_sv2::bitcoin::consensus::encode::serialize as btc_serialize; +use bitcoin::consensus::encode::serialize as btc_serialize; use sha2::{ compress256, digest::generic_array::{typenum::U64, GenericArray}, @@ -152,8 +150,8 @@ pub type StdFrame = StandardSv2Frame; pub type EitherFrame = StandardEitherFrame; struct SetupConnectionHandler {} -use roles_logic_sv2::bitcoin::block::Version; -use roles_logic_sv2::common_messages_sv2::Reconnect; +use bitcoin::block::Version; +use common_messages_sv2::Reconnect; use std::convert::TryInto; impl SetupConnectionHandler { @@ -225,7 +223,7 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_setup_connection_error( &mut self, - _: roles_logic_sv2::common_messages_sv2::SetupConnectionError, + _: common_messages_sv2::SetupConnectionError, ) -> Result { error!("Setup connection error"); todo!() @@ -233,7 +231,7 @@ impl ParseCommonMessagesFromUpstream for SetupConnectionHandler { fn handle_channel_endpoint_changed( &mut self, - _: roles_logic_sv2::common_messages_sv2::ChannelEndpointChanged, + _: common_messages_sv2::ChannelEndpointChanged, ) -> Result { todo!() } @@ -367,10 +365,9 @@ impl Device { .safe_lock(|s| s.notify_changes_to_mining_thread.clone()) .unwrap(); if notify_changes_to_mining_thread.should_send - && (message_type == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB - || message_type - == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH - || message_type == roles_logic_sv2::mining_sv2::MESSAGE_TYPE_SET_TARGET) + && (message_type == mining_sv2::MESSAGE_TYPE_NEW_MINING_JOB + || message_type == mining_sv2::MESSAGE_TYPE_MINING_SET_NEW_PREV_HASH + || message_type == mining_sv2::MESSAGE_TYPE_SET_TARGET) { notify_changes_to_mining_thread .sender diff --git a/test/integration-tests/Cargo.lock b/test/integration-tests/Cargo.lock index e5b863bf86..89dba2bc0d 100644 --- a/test/integration-tests/Cargo.lock +++ b/test/integration-tests/Cargo.lock @@ -1,15 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] +version = 3 [[package]] name = "adler2" @@ -197,21 +188,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link 0.2.1", -] - [[package]] name = "base58ck" version = "0.1.0" @@ -461,9 +437,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" @@ -646,18 +622,6 @@ dependencies = [ "yaml-rust2", ] -[[package]] -name = "config_helpers_sv2" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3307b494a63dab36d0bec2b1e830b6568f53300aaa9516ac673a434e799ae" -dependencies = [ - "miniscript", - "serde", - "tracing", - "tracing-subscriber", -] - [[package]] name = "const-random" version = "0.1.18" @@ -1072,19 +1036,19 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.1+wasi-snapshot-preview1", + "wasi", ] [[package]] name = "getrandom" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", "r-efi", - "wasi 0.14.7+wasi-0.2.4", + "wasip2", ] [[package]] @@ -1097,12 +1061,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - [[package]] name = "h2" version = "0.4.12" @@ -1384,17 +1342,6 @@ dependencies = [ "translator_sv2", ] -[[package]] -name = "io-uring" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046fa2d4d00aea763528b4950358d0ead425372445dc8ff86312b3c69ff7727b" -dependencies = [ - "bitflags", - "cfg-if", - "libc", -] - [[package]] name = "ipnet" version = "2.11.0" @@ -1431,13 +1378,24 @@ name = "jd_server" version = "0.1.3" dependencies = [ "async-channel", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bitcoin", "clap", + "codec_sv2 3.0.1", + "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "config", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", + "job_declaration_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "network_helpers_sv2", "nohash-hasher", + "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parsers_sv2 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.8.5", - "roles_logic_sv2 4.0.0", + "roles_logic_sv2 5.0.0", + "rpc_sv2", "serde", "serde_json", "stratum-apps", @@ -1484,19 +1442,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "key-utils" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe8551792fd4461e519fdfd8b8f334d1bf480250786fd202baf418854ff7130" -dependencies = [ - "bs58", - "rand 0.8.5", - "rustversion", - "secp256k1 0.28.2", - "serde", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -1570,14 +1515,11 @@ dependencies = [ "async-recursion", "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitcoin", - "buffer_sv2 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "clap", "codec_sv2 3.0.1", "common_messages_sv2 6.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "config_helpers_sv2", "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "futures", - "key-utils", "mining_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "network_helpers_sv2", "noise_sv2 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1586,8 +1528,8 @@ dependencies = [ "primitive-types", "rand 0.8.5", "roles_logic_sv2 5.0.0", - "rpc_sv2", "sha2 0.10.9", + "stratum-apps", "tokio", "tracing", "tracing-subscriber", @@ -1651,7 +1593,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "wasi 0.11.1+wasi-snapshot-preview1", + "wasi", "windows-sys 0.59.0", ] @@ -1728,15 +1670,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - [[package]] name = "once_cell" version = "1.21.3" @@ -2064,7 +1997,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.3", + "getrandom 0.3.4", ] [[package]] @@ -2190,12 +2123,6 @@ dependencies = [ "ordered-multimap", ] -[[package]] -name = "rustc-demangle" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" - [[package]] name = "rustc-hex" version = "2.1.0" @@ -2454,16 +2381,11 @@ name = "stratum-apps" version = "0.1.0" dependencies = [ "async-channel", - "base64 0.21.7", "bs58", "clap", "config", "futures", "generic-array", - "hex", - "http-body-util", - "hyper", - "hyper-util", "miniscript", "rand 0.8.5", "rustversion", @@ -2670,30 +2592,27 @@ dependencies = [ [[package]] name = "tokio" -version = "1.47.1" +version = "1.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ - "backtrace", "bytes", - "io-uring", "libc", "mio", "parking_lot", "pin-project-lite", "signal-hook-registry", - "slab", "socket2", "tokio-macros", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", @@ -2973,15 +2892,6 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" -[[package]] -name = "wasi" -version = "0.14.7+wasi-0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" -dependencies = [ - "wasip2", -] - [[package]] name = "wasip2" version = "1.0.1+wasi-0.2.4" diff --git a/test/integration-tests/lib/message_aggregator.rs b/test/integration-tests/lib/message_aggregator.rs index 5f8e64593f..56d8a3cfa0 100644 --- a/test/integration-tests/lib/message_aggregator.rs +++ b/test/integration-tests/lib/message_aggregator.rs @@ -1,6 +1,5 @@ use std::{collections::VecDeque, sync::Arc}; -use stratum_apps::custom_mutex::Mutex; -use stratum_apps::stratum_core::parsers_sv2::AnyMessage; +use stratum_apps::{custom_mutex::Mutex, stratum_core::parsers_sv2::AnyMessage}; use crate::types::MsgType; diff --git a/test/integration-tests/lib/mod.rs b/test/integration-tests/lib/mod.rs index 3faf7e3531..a93b836a47 100644 --- a/test/integration-tests/lib/mod.rs +++ b/test/integration-tests/lib/mod.rs @@ -10,8 +10,10 @@ use std::{ net::{Ipv4Addr, SocketAddr}, time::Duration, }; -use stratum_apps::config_helpers::CoinbaseRewardScript; -use stratum_apps::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; +use stratum_apps::{ + config_helpers::CoinbaseRewardScript, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, +}; use tracing::Level; use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; use translator_sv2::TranslatorSv2; diff --git a/test/integration-tests/lib/utils.rs b/test/integration-tests/lib/utils.rs index bf8929ca81..0c7c8575b8 100644 --- a/test/integration-tests/lib/utils.rs +++ b/test/integration-tests/lib/utils.rs @@ -5,7 +5,6 @@ use crate::{ types::{MessageFrame, MsgType}, }; use async_channel::{Receiver, Sender}; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use once_cell::sync::Lazy; use std::{ collections::HashSet, @@ -14,6 +13,7 @@ use std::{ sync::Mutex, }; use stratum_apps::{ + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_connection::Connection, stratum_core::{ codec_sv2::{HandshakeRole, StandardEitherFrame},