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/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/.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..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 @@ -105,14 +101,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/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/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/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/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/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/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/roles/Cargo.lock b/roles/Cargo.lock index cf7436e9ed..a591ca9197 100644 --- a/roles/Cargo.lock +++ b/roles/Cargo.lock @@ -2,21 +2,6 @@ # It is not intended for manual editing. version = 3 -[[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" - [[package]] name = "aead" version = "0.5.2" @@ -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" @@ -435,19 +405,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 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", + "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 +593,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" @@ -640,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" @@ -668,17 +672,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 +780,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 +816,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]] @@ -983,7 +1026,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,10 +1097,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - [[package]] name = "event-listener" version = "2.5.3" @@ -1130,9 +1178,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]] @@ -1289,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" @@ -1336,16 +1389,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", ] @@ -1592,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" @@ -1648,7 +1705,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "key-utils", "serde", "stratum-apps", "tokio", @@ -1660,14 +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", - "error_handling", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", - "key-utils", + "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 5.0.0", + "rpc_sv2", "serde", "serde_json", "stratum-apps", @@ -1679,7 +1745,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]] @@ -1703,18 +1778,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" @@ -1799,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", - "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)", "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", "sha2 0.10.9", "stratum-apps", "tokio", @@ -1819,26 +1891,26 @@ dependencies = [ name = "mining_sv2" version = "5.0.1" dependencies = [ - "binary_sv2", + "binary_sv2 4.0.0", ] [[package]] -name = "miniscript" -version = "12.3.5" +name = "mining_sv2" +version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487906208f38448e186e3deb02f2b8ef046a9078b0de00bdb28bf4fb9b76951c" +checksum = "1eb3c055232f64d36e3eee4296adcaa584fb3185a57e0de11ad5807766c45edc" dependencies = [ - "bech32", - "bitcoin", + "binary_sv2 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "miniz_oxide" -version = "0.8.9" +name = "miniscript" +version = "12.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +checksum = "487906208f38448e186e3deb02f2b8ef046a9078b0de00bdb28bf4fb9b76951c" dependencies = [ - "adler2", + "bech32", + "bitcoin", ] [[package]] @@ -1852,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" @@ -1870,6 +1955,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" @@ -1918,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" @@ -2022,12 +2111,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]] @@ -2170,8 +2273,6 @@ dependencies = [ "async-channel 1.9.0", "clap", "config", - "error_handling", - "key-utils", "rand", "secp256k1 0.28.2", "serde", @@ -2301,24 +2402,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", ] @@ -2334,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" @@ -2344,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" @@ -2633,16 +2768,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", @@ -2652,35 +2790,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", ] @@ -2701,7 +2847,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", @@ -2763,7 +2909,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]] @@ -2816,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", @@ -3014,7 +3166,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..a161bdce71 100644 --- a/roles/jd-client/Cargo.toml +++ b/roles/jd-client/Cargo.toml @@ -17,10 +17,9 @@ 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"] } 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 21f6f5d0eb..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,10 +7,9 @@ use std::{ Arc, }, }; - -use async_channel::{Receiver, Sender}; -use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ + custom_mutex::Mutex, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::{ @@ -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/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/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 bc45ef71ed..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 key_utils::Secp256k1PublicKey; +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/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..147a6e39cc 100644 --- a/roles/jd-client/src/lib/template_receiver/mod.rs +++ b/roles/jd-client/src/lib/template_receiver/mod.rs @@ -10,11 +10,11 @@ //! - 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 key_utils::Secp256k1PublicKey; +use std::{net::SocketAddr, sync::Arc}; use stratum_apps::{ + custom_mutex::Mutex, + key_utils::Secp256k1PublicKey, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ bitcoin::{ @@ -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 7601c7bbc0..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 key_utils::Secp256k1PublicKey; +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 2b52d8c28d..5488fd29fc 100644 --- a/roles/jd-server/Cargo.toml +++ b/roles/jd-server/Cargo.toml @@ -18,8 +18,18 @@ 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" } +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"] } @@ -31,3 +41,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 e151f7b891..85a34f4be9 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 { @@ -173,9 +175,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 308c9cfc16..74b46b074f 100644 --- a/roles/jd-server/src/lib/job_declarator/mod.rs +++ b/roles/jd-server/src/lib/job_declarator/mod.rs @@ -22,37 +22,35 @@ 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 key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}; +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, +}; use std::{ collections::HashMap, convert::TryInto, sync::{atomic::AtomicU32, Arc}, }; use stratum_apps::{ - 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, - }, - }, + handle_result, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey, SignatureService}, }; use tokio::{net::TcpListener, time::Duration}; use tracing::{debug, error, info}; @@ -277,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: 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 ca15ad47d0..933570f55b 100644 --- a/roles/jd-server/src/lib/mod.rs +++ b/roles/jd-server/src/lib/mod.rs @@ -23,18 +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 error_handling::handle_result; 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::stratum_core::{ - codec_sv2::{StandardEitherFrame, StandardSv2Frame}, - parsers_sv2::AnyMessage as JdsMessages, - roles_logic_sv2::utils::Mutex, -}; +use stratum_apps::handle_result; 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..46cd5205d6 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 stratum_apps::stratum_core::parsers_sv2::Mining; +use 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,10 +154,13 @@ 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 mining_sv2; + use noise_sv2; + use parsers_sv2::Mining; + use roles_logic_sv2; #[tokio::test] async fn test_send_status_downstream_listener_shutdown() { @@ -182,7 +168,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) => { @@ -200,7 +186,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 { @@ -428,13 +414,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/pool/Cargo.toml b/roles/pool/Cargo.toml index 22d2bb7342..dffd724e02 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 } @@ -27,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 004982e113..204ecaa183 100644 --- a/roles/pool/src/lib/channel_manager/mod.rs +++ b/roles/pool/src/lib/channel_manager/mod.rs @@ -1,14 +1,14 @@ +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 key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use stratum_apps::{ config_helpers::CoinbaseRewardScript, + custom_mutex::Mutex, + key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}, network_helpers::noise_stream::NoiseTcpStream, stratum_core::{ channels_sv2::{ @@ -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 17b06d8c94..ca1904dc58 100644 --- a/roles/pool/src/lib/config.rs +++ b/roles/pool/src/lib/config.rs @@ -12,10 +12,9 @@ use std::{ net::SocketAddr, 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/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/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..8b6331991e 100644 --- a/roles/stratum-apps/Cargo.toml +++ b/roles/stratum-apps/Cargo.toml @@ -13,11 +13,7 @@ keywords = ["stratum", "mining", "bitcoin", "protocol", "sv2"] [dependencies] # 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" } +stratum-core = { path = "../../stratum-core", version = "0.1.0", optional = true} # External dependencies needed by the modules # Network helpers dependencies @@ -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,23 +48,27 @@ 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"] +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"] +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"] -jd_server = ["network", "config", "rpc", "with_buffer_pool"] -translator = ["network", "config", "sv1", "with_buffer_pool"] -mining_device = ["network", "config", "with_buffer_pool"] +pool = ["network", "config", "with_buffer_pool", "core"] +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"] +# 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/protocols/v2/roles-logic-sv2/src/utils.rs b/roles/stratum-apps/src/custom_mutex.rs similarity index 92% rename from protocols/v2/roles-logic-sv2/src/utils.rs rename to roles/stratum-apps/src/custom_mutex.rs index 8b23742da9..bbb5ed1ef3 100644 --- a/protocols/v2/roles-logic-sv2/src/utils.rs +++ b/roles/stratum-apps/src/custom_mutex.rs @@ -1,9 +1,11 @@ -//! # Collection of Helper Primitives +//! # Custom Mutex //! -//! 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. +//! 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}; 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/protocols/v2/roles-logic-sv2/src/errors.rs b/roles/stratum-apps/src/errors.rs similarity index 96% rename from protocols/v2/roles-logic-sv2/src/errors.rs rename to roles/stratum-apps/src/errors.rs index d58da2dc3c..82fda6028e 100644 --- a/protocols/v2/roles-logic-sv2/src/errors.rs +++ b/roles/stratum-apps/src/errors.rs @@ -3,19 +3,21 @@ //! 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}, }; +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)] @@ -134,7 +136,7 @@ pub enum Error { FailedToSetCustomMiningJob(ExtendedChannelError), FailedToDeserializeCoinbaseOutputs, /// Error from parsers_sv2 - ParserError(parsers_sv2::ParserError), + ParserError(stratum_core::parsers_sv2::ParserError), } impl From for Error { @@ -161,8 +163,8 @@ impl From for Error { } } -impl From for Error { - fn from(v: parsers_sv2::ParserError) -> Error { +impl From for Error { + fn from(v: stratum_core::parsers_sv2::ParserError) -> Error { Error::ParserError(v) } } 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..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. @@ -47,3 +50,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..3755794e11 100644 --- a/roles/test-utils/mining-device/Cargo.toml +++ b/roles/test-utils/mining-device/Cargo.toml @@ -20,12 +20,21 @@ path = "src/lib/mod.rs" [dependencies] -stratum-apps = { path = "../../stratum-apps", features = ["mining_device"] } +stratum-apps = {path = "../../stratum-apps/", features = ["mining_device"]} +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" 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" @@ -51,3 +60,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/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 e407112af5..f4b8bb7aec 100644 --- a/roles/test-utils/mining-device/src/lib/mod.rs +++ b/roles/test-utils/mining-device/src/lib/mod.rs @@ -1,9 +1,23 @@ #![allow(clippy::option_map_unit_fn)] use async_channel::{Receiver, Sender}; -use key_utils::Secp256k1PublicKey; +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::{ + errors::Error, + handlers::{ + common::ParseCommonMessagesFromUpstream, + mining::{ParseMiningMessagesFromUpstream, SendTo, SupportedChannelTypes}, + }, + utils::Mutex, +}; use std::{ net::{SocketAddr, ToSocketAddrs}, sync::{ @@ -13,34 +27,16 @@ use std::{ thread::available_parallelism, time::{Duration, Instant}, }; -use stratum_apps::{ - 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 stratum_apps::key_utils::Secp256k1PublicKey; 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/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/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/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/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 69f149ffeb..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, @@ -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/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/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/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/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/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 5c7df5db8f..89dba2bc0d 100644 --- a/test/integration-tests/Cargo.lock +++ b/test/integration-tests/Cargo.lock @@ -2,15 +2,6 @@ # It is not intended for manual editing. version = 3 -[[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" @@ -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" @@ -246,19 +222,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 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 = [ - "buffer_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", - "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 +398,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" @@ -427,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" @@ -455,17 +465,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 +546,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 +582,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]] @@ -731,7 +780,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,10 +845,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "error_handling" -version = "1.0.0" - [[package]] name = "event-listener" version = "2.5.3" @@ -853,9 +907,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]] @@ -971,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]] @@ -996,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" @@ -1021,16 +1080,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", ] @@ -1254,7 +1328,6 @@ dependencies = [ "flate2", "jd_client_sv2", "jd_server", - "key-utils", "mining_device", "minreq", "once_cell", @@ -1269,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" @@ -1305,7 +1367,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils", "serde", "stratum-apps", "tokio", @@ -1317,14 +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", - "error_handling", + "framing_sv2 5.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "hashbrown 0.11.2", "hex", - "key-utils", + "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 5.0.0", + "rpc_sv2", "serde", "serde_json", "stratum-apps", @@ -1336,7 +1407,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]] @@ -1362,18 +1442,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" @@ -1445,12 +1513,21 @@ version = "0.1.3" dependencies = [ "async-channel", "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)", + "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)", "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", "sha2 0.10.9", "stratum-apps", "tokio", @@ -1462,7 +1539,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]] @@ -1507,10 +1593,23 @@ 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", ] +[[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" @@ -1529,6 +1628,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" @@ -1558,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" @@ -1650,12 +1753,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]] @@ -1757,8 +1874,6 @@ dependencies = [ "async-channel", "clap", "config", - "error_handling", - "key-utils", "rand 0.8.5", "secp256k1 0.28.2", "serde", @@ -1882,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]] @@ -1925,24 +2040,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", ] @@ -1958,6 +2097,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" @@ -1968,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" @@ -2232,17 +2381,15 @@ name = "stratum-apps" version = "0.1.0" dependencies = [ "async-channel", - "base64 0.21.7", + "bs58", "clap", "config", - "error_handling", "futures", - "hex", - "http-body-util", - "hyper", - "hyper-util", - "key-utils", + "generic-array", "miniscript", + "rand 0.8.5", + "rustversion", + "secp256k1 0.28.2", "serde", "serde_json", "stratum-core", @@ -2252,35 +2399,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", ] @@ -2301,7 +2456,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", @@ -2385,7 +2540,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]] @@ -2428,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", @@ -2627,7 +2788,6 @@ dependencies = [ "async-channel", "clap", "config", - "key-utils", "serde", "serde_json", "stratum-apps", @@ -2732,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/Cargo.toml b/test/integration-tests/Cargo.toml index 9c066267b6..884ec26136 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" } @@ -31,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..56d8a3cfa0 100644 --- a/test/integration-tests/lib/message_aggregator.rs +++ b/test/integration-tests/lib/message_aggregator.rs @@ -1,5 +1,5 @@ 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, 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 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..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" @@ -196,24 +193,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" @@ -447,7 +426,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", - "rand_core", "typenum", ] @@ -488,15 +466,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 +478,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" @@ -536,7 +501,6 @@ name = "framing_sv2" version = "5.0.1" dependencies = [ "binary_sv2", - "buffer_sv2", "noise_sv2", ] @@ -642,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,19 +689,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" @@ -778,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" @@ -1052,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" @@ -1146,7 +1061,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", - "serde_derive", ] [[package]] @@ -1192,19 +1106,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" @@ -1233,7 +1134,6 @@ dependencies = [ "mining_sv2", "noise_sv2", "parsers_sv2", - "roles_logic_sv2", "template_distribution_sv2", ] 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() {}