diff --git a/protocols/v2/roles-logic-sv2/src/channel_logic/channel_factory.rs b/protocols/v2/roles-logic-sv2/src/channel_logic/channel_factory.rs index 040adb097d..d3abdae1e9 100644 --- a/protocols/v2/roles-logic-sv2/src/channel_logic/channel_factory.rs +++ b/protocols/v2/roles-logic-sv2/src/channel_logic/channel_factory.rs @@ -1,4 +1,6 @@ -//! Contains logic for creating channels. +//! # Channel Factory +//! +//! This module contains logic for creating and managing channels. use super::extended_to_standard_job; use crate::{ @@ -76,7 +78,7 @@ pub enum OnNewShare { } impl OnNewShare { - /// Convert standard share into extended share + /// Converts standard share into extended share pub fn into_extended(&mut self, extranonce: Vec, up_id: u32) { match self { OnNewShare::SendErrorDownstream(_) => (), @@ -139,7 +141,7 @@ pub struct StagedPhash { } impl StagedPhash { - /// converts a Staged PrevHash into a SetNewPrevHash message + /// Converts a Staged PrevHash into a SetNewPrevHash message pub fn into_set_p_hash( &self, channel_id: u32, @@ -156,7 +158,7 @@ impl StagedPhash { } impl Share { - /// get share sequence number + /// Get share sequence number pub fn get_sequence_number(&self) -> u32 { match self { Share::Extended(s) => s.sequence_number, @@ -164,7 +166,7 @@ impl Share { } } - /// get share channel id + /// Get share channel id pub fn get_channel_id(&self) -> u32 { match self { Share::Extended(s) => s.channel_id, @@ -172,7 +174,7 @@ impl Share { } } - /// get share timestamp + /// Get share timestamp pub fn get_n_time(&self) -> u32 { match self { Share::Extended(s) => s.ntime, @@ -180,7 +182,7 @@ impl Share { } } - /// get share nonce + /// Get share nonce pub fn get_nonce(&self) -> u32 { match self { Share::Extended(s) => s.nonce, @@ -188,7 +190,7 @@ impl Share { } } - /// get share job id + /// Get share job id pub fn get_job_id(&self) -> u32 { match self { Share::Extended(s) => s.job_id, @@ -196,7 +198,7 @@ impl Share { } } - /// get share version + /// Get share version pub fn get_version(&self) -> u32 { match self { Share::Extended(s) => s.version, @@ -976,7 +978,7 @@ impl ChannelFactory { }, } } - /// updates the downstream target for the given channel_id + /// Updates the downstream target for the given channel_id fn update_target_for_channel(&mut self, channel_id: u32, new_target: Target) -> Option { let channel = self.extended_channels.get_mut(&channel_id)?; channel.target = new_target.into(); @@ -1292,12 +1294,12 @@ impl PoolChannelFactory { true } - /// get extended channel ids + /// Get extended channel ids pub fn get_extended_channels_ids(&self) -> Vec { self.inner.extended_channels.keys().copied().collect() } - /// update coinbase outputs + /// Update coinbase outputs pub fn update_pool_outputs(&mut self, outs: Vec) { self.pool_coinbase_outputs = outs; } @@ -1331,7 +1333,7 @@ pub struct ProxyExtendedChannelFactory { } impl ProxyExtendedChannelFactory { - /// constructor + /// Constructor #[allow(clippy::too_many_arguments)] pub fn new( ids: Arc>, @@ -1520,7 +1522,7 @@ impl ProxyExtendedChannelFactory { /// Called when a `SubmitSharesStandard` message is received from the downstream. We check the /// shares against the channel's respective target and return `OnNewShare` to let us know if - /// and where the the shares should be relayed + /// and where the shares should be relayed pub fn on_submit_shares_extended( &mut self, m: SubmitSharesExtended<'static>, @@ -1723,12 +1725,12 @@ impl ProxyExtendedChannelFactory { self.inner.on_new_extended_mining_job(m) } - /// set new target + /// Set new target pub fn set_target(&mut self, new_target: &mut Target) { self.inner.kind.set_target(new_target); } - /// get last valid job version + /// Get last valid job version pub fn last_valid_job_version(&self) -> Option { self.inner.last_valid_job.as_ref().map(|j| j.0.version) } @@ -1752,44 +1754,44 @@ impl ProxyExtendedChannelFactory { .map(|f| f.0.prev_hash.clone()) } - /// last min ntime + /// Get last min ntime pub fn last_min_ntime(&self) -> Option { self.inner.last_prev_hash.as_ref().map(|f| f.0.min_ntime) } - /// last nbits + /// Get last nbits pub fn last_nbits(&self) -> Option { self.inner.last_prev_hash.as_ref().map(|f| f.0.nbits) } - /// extranonce_size + /// Get extranonce_size pub fn extranonce_size(&self) -> usize { self.inner.extranonces.get_len() } - /// extranonce_2 size + /// Get extranonce_2 size pub fn channel_extranonce2_size(&self) -> usize { self.inner.extranonces.get_len() - self.inner.extranonces.get_range0_len() } // Only used when the proxy is using Job Declaration - /// update pool outputs + /// Updates pool outputs pub fn update_pool_outputs(&mut self, outs: Vec) { self.pool_coinbase_outputs = Some(outs); } - /// get this channel id + /// Get this channel id pub fn get_this_channel_id(&self) -> u32 { self.extended_channel_id } - /// returns the extranonce1 len of the upstream. For a proxy, this would + /// Returns the extranonce1 len of the upstream. For a proxy, this would /// be the extranonce_prefix len pub fn get_upstream_extranonce1_len(&self) -> usize { self.inner.extranonces.get_range0_len() } - /// calls [`ChannelFactory::update_target_for_channel`] + /// Calls [`ChannelFactory::update_target_for_channel`] pub fn update_target_for_channel( &mut self, channel_id: u32, @@ -1807,7 +1809,7 @@ pub enum ExtendedChannelKind { Pool, } impl ExtendedChannelKind { - /// set target + /// Set target pub fn set_target(&mut self, new_target: &mut Target) { match self { ExtendedChannelKind::Proxy { upstream_target } diff --git a/protocols/v2/roles-logic-sv2/src/channel_logic/mod.rs b/protocols/v2/roles-logic-sv2/src/channel_logic/mod.rs index 05dbb3d125..18653124a4 100644 --- a/protocols/v2/roles-logic-sv2/src/channel_logic/mod.rs +++ b/protocols/v2/roles-logic-sv2/src/channel_logic/mod.rs @@ -1,3 +1,5 @@ +//! # Channel Logic +//! //! A module for managing channels on applications. //! //! Divided in two submodules: @@ -10,7 +12,7 @@ pub mod proxy_group_channel; use mining_sv2::{NewExtendedMiningJob, NewMiningJob}; use std::convert::TryInto; -/// convert extended to standard job by calculating the merkle root +/// Convert extended to standard job by calculating the merkle root pub fn extended_to_standard_job<'a>( extended: &NewExtendedMiningJob, coinbase_script: &[u8], diff --git a/protocols/v2/roles-logic-sv2/src/channel_logic/proxy_group_channel.rs b/protocols/v2/roles-logic-sv2/src/channel_logic/proxy_group_channel.rs index 73068fb8e2..50a59d175b 100644 --- a/protocols/v2/roles-logic-sv2/src/channel_logic/proxy_group_channel.rs +++ b/protocols/v2/roles-logic-sv2/src/channel_logic/proxy_group_channel.rs @@ -1,4 +1,6 @@ -//! Contains logic for managing Standard Channels via Group Channels. +//! # Proxy Group Channel +//! +//! This module contains logic for managing Standard Channels via Group Channels. use crate::{common_properties::StandardChannel, parsers::Mining, Error}; @@ -10,13 +12,13 @@ use super::extended_to_standard_job; use nohash_hasher::BuildNoHashHasher; use std::collections::HashMap; -/// wrapper around `GroupChannel` for managing multiple group channels +/// Wrapper around `GroupChannel` for managing multiple group channels #[derive(Debug, Clone, Default)] pub struct GroupChannels { channels: HashMap, } impl GroupChannels { - /// constructor + /// Constructor pub fn new() -> Self { Self { channels: HashMap::new(), @@ -74,7 +76,7 @@ impl GroupChannels { } } - /// get group channel ids + /// Get group channel ids pub fn ids(&self) -> Vec { self.channels.keys().copied().collect() } diff --git a/protocols/v2/roles-logic-sv2/src/common_properties.rs b/protocols/v2/roles-logic-sv2/src/common_properties.rs index 9198fcdecd..047aa8ca91 100644 --- a/protocols/v2/roles-logic-sv2/src/common_properties.rs +++ b/protocols/v2/roles-logic-sv2/src/common_properties.rs @@ -18,32 +18,28 @@ use std::{collections::HashMap, fmt::Debug as D}; pub struct CommonDownstreamData { /// Header-only mining flag. /// - /// Enables the processing of block headers only, leaving transaction management and template - /// construction to the upstream node. It reduces the amount of data processed and transmitted - /// by the downstream node, making it useful when bandwidth is limited and transmitting full - /// block templates is costly. + /// Enables the processing of standard jobs only, leaving merkle root manipulation to the + /// upstream node. /// - /// - `true`: The downstream node only processes block headers, relying on the upstream for - /// transaction management. - /// - `false`: The downstream node handles full blocks. + /// - `true`: The downstream node only processes standard jobs, relying on the upstream for + /// merkle root manipulation. + /// - `false`: The downstream node handles extended jobs and merkle root manipulation. pub header_only: bool, /// Work selection flag. /// - /// Enables the selection of which transactions or templates the node will work on. It allows - /// for more autonomy for downstream nodes to define specific version bits to roll, adjust the - /// difficulty target, apply `timestamp` range constraints, etc. + /// Enables the selection of which transactions or templates the node will work on. /// - /// - `true`: The downstream node can modify or customize the mining job, such as choosing - /// specific transactions to include in a block template. - /// - `false`: The downstream node strictly follows the work provided by the upstream, such as - /// pre-constructed templates from a pool. + /// - `true`: The downstream node works on a custom block template, using the Job Declaration + /// Protocol. + /// - `false`: The downstream node strictly follows the work provided by the upstream, based on + /// pre-constructed templates from the upstream (e.g. Pool). pub work_selection: bool, /// Version rolling flag. /// /// Enables rolling the block header version bits which allows for more unique hash generation - /// on the same block template by expanding the nonce-space. Used when other fields (e.g. + /// on the same mining job by expanding the nonce-space. Used when other fields (e.g. /// `nonce` or `extranonce`) are fully exhausted. /// /// - `true`: The downstream supports version rolling and can modify specific bits in the @@ -60,7 +56,7 @@ pub struct CommonDownstreamData { /// range, and flag settings. #[derive(Debug, Copy, Clone)] pub struct PairSettings { - /// Role the settings apply to. + /// Protocol the settings apply to. pub protocol: Protocol, /// Minimum protocol version the node supports. @@ -70,7 +66,7 @@ pub struct PairSettings { pub max_v: u16, /// Flags indicating optional protocol features the node supports (e.g. header-only mining, - /// Noise protocol support, job configuration parameters, etc.). Each protocol field as its own + /// work selection, version-rolling, etc.). Each protocol field as its own /// flags. pub flags: u32, } @@ -122,8 +118,9 @@ pub enum UpstreamChannel { /// A grouped channel for aggregated mining. /// - /// Aggregates mining work for multiple devices or clients under a single channel, enabling the - /// upstream to manage work distribution and result aggregation for an entire group of miners. + /// Aggregates mining work for multiple standard channels under a single group channel, + /// enabling the upstream to manage work distribution and result aggregation for an entire + /// group of channels. /// /// Typically used by a mining proxy managing multiple downstream miners. Group, @@ -138,7 +135,7 @@ pub enum UpstreamChannel { /// Properties of a standard mining channel. /// /// Standard channels are intended to be used by end mining devices with a nominal hashrate, where -/// each device operates on an independent connection to its upstream. +/// each device operates on an independent channel to its upstream. #[derive(Debug, Clone)] pub struct StandardChannel { /// Identifies a specific channel, unique to each mining connection. @@ -148,7 +145,7 @@ pub struct StandardChannel { /// the same upstream node. The identifier remains stable for the whole lifetime of the /// connection. /// - /// Used for broadcasting new jobs by [`mining_sv2::NewExtendedMiningJob`]. + /// Used for broadcasting new jobs by [`mining_sv2::NewMiningJob`]. pub channel_id: u32, /// Identifies a specific group in which the standard channel belongs. diff --git a/protocols/v2/roles-logic-sv2/src/errors.rs b/protocols/v2/roles-logic-sv2/src/errors.rs index 47369a4831..bd18eebc20 100644 --- a/protocols/v2/roles-logic-sv2/src/errors.rs +++ b/protocols/v2/roles-logic-sv2/src/errors.rs @@ -1,4 +1,7 @@ -//! Errors specific to this crate +//! # Error Handling +//! +//! This module defines error types and utilities for handling errors in the `roles_logic_sv2` +//! module. It includes the [`Error`] enum for representing various errors. use crate::{ common_properties::CommonDownstreamData, parsers::PoolMessages as AllMessages, diff --git a/protocols/v2/roles-logic-sv2/src/handlers/common.rs b/protocols/v2/roles-logic-sv2/src/handlers/common.rs index a520b8ca7e..c36c3a9a1a 100644 --- a/protocols/v2/roles-logic-sv2/src/handlers/common.rs +++ b/protocols/v2/roles-logic-sv2/src/handlers/common.rs @@ -3,13 +3,6 @@ //! This module defines traits and implementations for handling common Stratum V2 messages exchanged //! between upstream and downstream nodes. //! -//! ## Core Traits -//! -//! - `ParseUpstreamCommonMessages`: Implemented by downstream nodes to handle common messages -//! received from upstream nodes, such as setup connection results or channel endpoint changes. -//! - `ParseDownstreamCommonMessages`: Implemented by upstream nodes to process setup connection -//! messages received from downstream nodes. -//! //! ## Message Handling //! //! Handlers in this module are responsible for: @@ -58,10 +51,6 @@ where { /// Takes a message type and a payload, and if the message type is a /// [`crate::parsers::CommonMessages`], it calls the appropriate handler function - /// - /// Arguments: - /// - /// * `message_type`: See [`const_sv2`]. fn handle_message_common( self_: Arc>, message_type: u8, @@ -76,10 +65,6 @@ where } /// Takes a message and it calls the appropriate handler function - /// - /// Arguments: - /// - /// * `message_type`: See [`const_sv2`]. fn handle_message_common_deserilized( self_: Arc>, message: Result, Error>, @@ -124,12 +109,6 @@ where /// /// This method processes a `SetupConnectionSuccess` message and handles it /// by delegating to the appropriate handler. - /// - /// # Arguments - /// - `message`: The `SetupConnectionSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_setup_connection_success( &mut self, m: SetupConnectionSuccess, @@ -139,24 +118,12 @@ where /// /// This method processes a `SetupConnectionError` message and handles it /// by delegating to the appropriate handler. - /// - /// # Arguments - /// - `message`: The `SetupConnectionError` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. 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. - /// - /// # Arguments - /// - `message`: The `ChannelEndpointChanged` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_channel_endpoint_changed( &mut self, m: ChannelEndpointChanged, @@ -191,10 +158,6 @@ where /// 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 - /// - /// Arguments: - /// - /// * `message_type`: See [`const_sv2`]. fn handle_message_common( self_: Arc>, message_type: u8, @@ -255,13 +218,6 @@ where /// /// This method processes a `SetupConnection` message and handles it /// by delegating to the appropriate handler in the routing logic. - /// - /// # Arguments - /// - `message`: The `SetupConnection` message. - /// - `result`: The result of the `on_setup_connection` call, if available. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_setup_connection( &mut self, m: SetupConnection, diff --git a/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs b/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs index a2ec2aea1c..1a6d56e42d 100644 --- a/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs +++ b/protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs @@ -4,17 +4,6 @@ //! Stratum V2 protocol. The job declaration process is integral to managing mining tasks and //! transactions between server and client components. //! -//! ## Core Traits -//! -//! - `ParseServerJobDeclarationMessages`: This trait is implemented by downstream nodes to process -//! job declaration messages received from upstream nodes. The trait includes methods for handling -//! job-related events such as mining job token allocation, job declaration successes or errors, -//! and transaction identification or provisioning. -//! - `ParseClientJobDeclarationMessages`: This trait is implemented by upstream nodes to manage job -//! declaration messages received from downstream nodes. It facilitates the handling of job -//! declarations, mining job token allocation, and transaction solutions submitted by downstream -//! nodes. -//! //! ## Message Handling //! //! The handlers are responsible for the following tasks: @@ -60,15 +49,6 @@ where Self: Sized, { /// Routes an incoming job declaration message to the appropriate handler function. - /// - /// # Parameters - /// - `self_`: An `Arc>` instance to ensure thread-safe access to the implementor. - /// - `message_type`: The type identifier of the incoming message. - /// - `payload`: A mutable slice containing the message payload. - /// - /// # Returns - /// - `Ok(SendTo)`: Indicates the message was successfully handled. - /// - `Err(Error)`: Indicates an error occurred during message parsing or handling. fn handle_message_job_declaration( self_: Arc>, message_type: u8, @@ -78,15 +58,6 @@ where } /// Routes a deserialized job declaration message to the appropriate handler function. - /// - /// # Parameters - /// - `self_`: An `Arc>` instance to ensure thread-safe access to the implementor. - /// - `message`: A `Result` containing either the parsed message or an - /// error. - /// - /// # Returns - /// - `Ok(SendTo)`: Indicates the message was successfully handled. - /// - `Err(Error)`: Indicates an error occurred during message parsing or handling. fn handle_message_job_declaration_deserialized( self_: Arc>, message: Result, Error>, @@ -151,12 +122,6 @@ where /// Handles an `AllocateMiningJobTokenSuccess` message. /// /// This method processes a message indicating a successful job token allocation. - /// - /// # Arguments - /// - `message`: The `AllocateMiningJobTokenSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_allocate_mining_job_token_success( &mut self, message: AllocateMiningJobTokenSuccess, @@ -165,12 +130,6 @@ where /// Handles a `DeclareMiningJobSuccess` message. /// /// This method processes a message indicating a successful mining job declaration. - /// - /// # Arguments - /// - `message`: The `DeclareMiningJobSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_declare_mining_job_success( &mut self, message: DeclareMiningJobSuccess, @@ -179,12 +138,6 @@ where /// Handles a `DeclareMiningJobError` message. /// /// This method processes a message indicating an error in the mining job declaration process. - /// - /// # Arguments - /// - `message`: The `DeclareMiningJobError` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_declare_mining_job_error( &mut self, message: DeclareMiningJobError, @@ -193,12 +146,6 @@ where /// Handles an `IdentifyTransactions` message. /// /// This method processes a message that provides transaction identification data. - /// - /// # Arguments - /// - `message`: The `IdentifyTransactions` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_identify_transactions( &mut self, message: IdentifyTransactions, @@ -207,12 +154,6 @@ where /// Handles a `ProvideMissingTransactions` message. /// /// This method processes a message that supplies missing transaction data. - /// - /// # Arguments - /// - `message`: The `ProvideMissingTransactions` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_provide_missing_transactions( &mut self, message: ProvideMissingTransactions, @@ -227,15 +168,6 @@ where Self: Sized, { /// Routes an incoming job declaration message to the appropriate handler function. - /// - /// # Parameters - /// - `self_`: An `Arc>` instance to ensure thread-safe access to the implementor. - /// - `message_type`: The type identifier of the incoming message. - /// - `payload`: A mutable slice containing the message payload. - /// - /// # Returns - /// - `Ok(SendTo)`: Indicates the message was successfully handled. - /// - `Err(Error)`: Indicates an error occurred during message parsing or handling. fn handle_message_job_declaration( self_: Arc>, message_type: u8, @@ -245,15 +177,6 @@ where } /// Routes a deserialized job declaration message to the appropriate handler function. - /// - /// # Parameters - /// - `self_`: An `Arc>` instance to ensure thread-safe access to the implementor. - /// - `message`: A `Result` containing either the parsed message or an - /// error. - /// - /// # Returns - /// - `Ok(SendTo)`: Indicates the message was successfully handled. - /// - `Err(Error)`: Indicates an error occurred during message parsing or handling. fn handle_message_job_declaration_deserialized( self_: Arc>, message: Result, Error>, @@ -309,14 +232,6 @@ where } /// Handles an `AllocateMiningJobToken` message. - /// - /// This method processes a message that allocates a mining job token. - /// - /// # Arguments - /// - `message`: The `AllocateMiningJobToken` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_allocate_mining_job_token( &mut self, message: AllocateMiningJobToken, @@ -325,23 +240,11 @@ where /// Handles a `DeclareMiningJob` message. /// /// This method processes a message that declares a new mining job. - /// - /// # Arguments - /// - `message`: The `DeclareMiningJob` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_declare_mining_job(&mut self, message: DeclareMiningJob) -> Result; /// Handles an `IdentifyTransactionsSuccess` message. /// /// This method processes a message that confirms the identification of transactions. - /// - /// # Arguments - /// - `message`: The `IdentifyTransactionsSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_identify_transactions_success( &mut self, message: IdentifyTransactionsSuccess, @@ -350,12 +253,6 @@ where /// Handles a `ProvideMissingTransactionsSuccess` message. /// /// This method processes a message that confirms the receipt of missing transactions. - /// - /// # Arguments - /// - `message`: The `ProvideMissingTransactionsSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_provide_missing_transactions_success( &mut self, message: ProvideMissingTransactionsSuccess, @@ -364,11 +261,5 @@ where /// Handles a `SubmitSolution` message. /// /// This method processes a message that submits a solution for the mining job. - /// - /// # Arguments - /// - `message`: The `SubmitSolutionJd` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_submit_solution(&mut self, message: SubmitSolutionJd) -> Result; } diff --git a/protocols/v2/roles-logic-sv2/src/handlers/mining.rs b/protocols/v2/roles-logic-sv2/src/handlers/mining.rs index 8edb439764..63d0a52e49 100644 --- a/protocols/v2/roles-logic-sv2/src/handlers/mining.rs +++ b/protocols/v2/roles-logic-sv2/src/handlers/mining.rs @@ -3,15 +3,6 @@ //! This module defines traits and functions for handling mining-related messages within the Stratum //! V2 protocol. //! -//! ## Core Traits -//! -//! - `ParseUpstreamMiningMessages`: Implemented by downstream nodes to process mining messages -//! received from upstream nodes. This trait provides methods for handling mining events like new -//! mining jobs, share submissions, extranonce prefix updates, and channel status updates. -//! - `ParseDownstreamMiningMessages`: Implemented by upstream nodes to manage mining messages -//! received from downstream nodes. This trait includes methods for managing tasks such as -//! submitting shares, opening mining channels, and handling mining job responses. -//! //! ## Message Handling //! //! Handlers in this module are responsible for: @@ -88,15 +79,6 @@ pub trait ParseDownstreamMiningMessages< fn get_channel_type(&self) -> SupportedChannelTypes; /// Handles a mining message from the downstream, given its type and payload. - /// - /// # Arguments - /// - `self_mutex`: The `Arc>` representing the downstream entity. - /// - `message_type`: The type of the mining message. - /// - `payload`: The raw payload of the message. - /// - `routing_logic`: The logic for routing the message to the appropriate upstream entity. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_message_mining( self_mutex: Arc>, message_type: u8, @@ -117,14 +99,6 @@ pub trait ParseDownstreamMiningMessages< } /// Deserializes and processes a mining message from the downstream. - /// - /// # Arguments - /// - `self_mutex`: The `Arc>` representing the downstream entity. - /// - `message`: The mining message to be processed. - /// - `routing_logic`: The logic for routing the message to the appropriate upstream entity. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_message_mining_deserialized( self_mutex: Arc>, message: Result, Error>, @@ -326,19 +300,9 @@ pub trait ParseDownstreamMiningMessages< } /// Checks if work selection is enabled for the downstream connection. - /// - /// # Returns - /// - `bool`: `true` if work selection is enabled, `false` otherwise. fn is_work_selection_enabled(&self) -> bool; /// Checks if the downstream user is authorized. - /// - /// # Arguments - /// - `_self_mutex`: The `Arc>` representing the downstream entity. - /// - `_user_identity`: The user's identity to be checked. - /// - /// # Returns - /// - `Result`: `true` if the user is authorized, `false` otherwise. fn is_downstream_authorized( _self_mutex: Arc>, _user_identity: &binary_sv2::Str0255, @@ -347,16 +311,6 @@ pub trait ParseDownstreamMiningMessages< } /// Handles an `OpenStandardMiningChannel` message. - /// - /// This method processes an `OpenStandardMiningChannel` message and initiates the - /// appropriate response. - /// - /// # Arguments - /// - `m`: The `OpenStandardMiningChannel` message. - /// - `up`: An optional upstream entity to which the message is forwarded. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_open_standard_mining_channel( &mut self, m: OpenStandardMiningChannel, @@ -364,15 +318,6 @@ pub trait ParseDownstreamMiningMessages< ) -> Result, Error>; /// Handles an `OpenExtendedMiningChannel` message. - /// - /// This method processes an `OpenExtendedMiningChannel` message and initiates the - /// appropriate response. - /// - /// # Arguments - /// - `m`: The `OpenExtendedMiningChannel` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_open_extended_mining_channel( &mut self, m: OpenExtendedMiningChannel, @@ -381,23 +326,11 @@ pub trait ParseDownstreamMiningMessages< /// Handles an `UpdateChannel` message. /// /// This method processes an `UpdateChannel` message and updates the channel settings. - /// - /// # Arguments - /// - `m`: The `UpdateChannel` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. 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. - /// - /// # Arguments - /// - `m`: The `SubmitSharesStandard` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_submit_shares_standard( &mut self, m: SubmitSharesStandard, @@ -406,12 +339,6 @@ pub trait ParseDownstreamMiningMessages< /// Handles a `SubmitSharesExtended` message. /// /// This method processes a `SubmitSharesExtended` message and validates the submitted shares. - /// - /// # Arguments - /// - `m`: The `SubmitSharesExtended` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_submit_shares_extended( &mut self, m: SubmitSharesExtended, @@ -421,12 +348,6 @@ pub trait ParseDownstreamMiningMessages< /// /// This method processes a `SetCustomMiningJob` message and applies the custom mining job /// settings. - /// - /// # Arguments - /// - `m`: The `SetCustomMiningJob` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_custom_mining_job(&mut self, m: SetCustomMiningJob) -> Result, Error>; } @@ -442,16 +363,9 @@ pub trait ParseUpstreamMiningMessages< Self: IsMiningUpstream + Sized + D, { /// Retrieves the type of the channel supported by this upstream parser. - /// - /// # Returns - /// - `SupportedChannelTypes`: The supported channel type for this upstream. fn get_channel_type(&self) -> SupportedChannelTypes; /// Retrieves an optional RequestIdMapper, used to manage request IDs across connections. - /// - /// # Returns - /// - `Option>>`: An optional RequestIdMapper for request ID - /// modification. fn get_request_id_mapper(&mut self) -> Option>> { None } @@ -460,16 +374,6 @@ pub trait ParseUpstreamMiningMessages< /// 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. - /// - /// # Arguments - /// - `self_mutex`: The `Arc>` representing the downstream entity. - /// - `message_type`: The type of the incoming message. - /// - `payload`: The payload containing the message data. - /// - `routing_logic`: The logic to handle the routing of the message based on the type. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message, either sending a - /// response or an error. fn handle_message_mining( self_mutex: Arc>, message_type: u8, @@ -488,15 +392,6 @@ pub trait ParseUpstreamMiningMessages< /// Handles the deserialized mining message from the upstream, processing it according to the /// routing logic. - /// - /// # Arguments - /// - `self_mutex`: The `Arc>` representing the downstream entity. - /// - `message`: The deserialized mining message, wrapped in a Result for error handling. - /// - `routing_logic`: The logic used to route the message based on the type. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message, either sending a - /// response or an error. fn handle_message_mining_deserialized( self_mutex: Arc>, message: Result, @@ -837,19 +732,9 @@ pub trait ParseUpstreamMiningMessages< } /// Determines whether work selection is enabled for this upstream. - /// - /// # Returns - /// - `bool`: A boolean indicating if work selection is enabled. fn is_work_selection_enabled(&self) -> bool; /// Handles a successful response for opening a standard mining channel. - /// - /// # Arguments - /// - `m`: The `OpenStandardMiningChannelSuccess` message. - /// - `remote`: An optional reference to the downstream, wrapped in an `Arc`. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_open_standard_mining_channel_success( &mut self, m: OpenStandardMiningChannelSuccess, @@ -857,160 +742,70 @@ pub trait ParseUpstreamMiningMessages< ) -> Result, Error>; /// Handles a successful response for opening an extended mining channel. - /// - /// # Arguments - /// - `m`: The `OpenExtendedMiningChannelSuccess` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_open_extended_mining_channel_success( &mut self, m: OpenExtendedMiningChannelSuccess, ) -> Result, Error>; /// Handles an error when opening a mining channel. - /// - /// # Arguments - /// - `m`: The `OpenMiningChannelError` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the error. fn handle_open_mining_channel_error( &mut self, m: OpenMiningChannelError, ) -> Result, Error>; /// Handles an error when updating a mining channel. - /// - /// # Arguments - /// - `m`: The `UpdateChannelError` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the error. fn handle_update_channel_error(&mut self, m: UpdateChannelError) -> Result, Error>; /// Handles a request to close a mining channel. - /// - /// # Arguments - /// - `m`: The `CloseChannel` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_close_channel(&mut self, m: CloseChannel) -> Result, Error>; /// Handles a request to set the extranonce prefix for mining. - /// - /// # Arguments - /// - `m`: The `SetExtranoncePrefix` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_extranonce_prefix( &mut self, m: SetExtranoncePrefix, ) -> Result, Error>; /// Handles a successful submission of shares. - /// - /// # Arguments - /// - `m`: The `SubmitSharesSuccess` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_submit_shares_success( &mut self, m: SubmitSharesSuccess, ) -> Result, Error>; /// Handles an error when submitting shares. - /// - /// # Arguments - /// - `m`: The `SubmitSharesError` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the error. fn handle_submit_shares_error(&mut self, m: SubmitSharesError) -> Result, Error>; /// Handles a new mining job. - /// - /// # Arguments - /// - `m`: The `NewMiningJob` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_new_mining_job(&mut self, m: NewMiningJob) -> Result, Error>; /// Handles a new extended mining job. - /// - /// # Arguments - /// - `m`: The `NewExtendedMiningJob` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_new_extended_mining_job( &mut self, m: NewExtendedMiningJob, ) -> Result, Error>; /// Handles a request to set the new previous hash. - /// - /// # Arguments - /// - `m`: The `SetNewPrevHash` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_new_prev_hash(&mut self, m: SetNewPrevHash) -> Result, Error>; /// Handles a successful response for setting a custom mining job. - /// - /// # Arguments - /// - `m`: The `SetCustomMiningJobSuccess` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_custom_mining_job_success( &mut self, m: SetCustomMiningJobSuccess, ) -> Result, Error>; /// Handles an error when setting a custom mining job. - /// - /// # Arguments - /// - `m`: The `SetCustomMiningJobError` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the error. fn handle_set_custom_mining_job_error( &mut self, m: SetCustomMiningJobError, ) -> Result, Error>; /// Handles a request to set the target for mining. - /// - /// # Arguments - /// - `m`: The `SetTarget` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_target(&mut self, m: SetTarget) -> Result, Error>; /// Handles a request to reconnect the mining connection. - /// - /// # Arguments - /// - `m`: The `Reconnect` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_reconnect(&mut self, m: Reconnect) -> Result, Error>; /// Handles a request to set the group channel for mining. - /// - /// # Arguments - /// - `_m`: The `SetGroupChannel` message. - /// - /// # Returns - /// - `Result, Error>`: The result of processing the message. fn handle_set_group_channel(&mut self, _m: SetGroupChannel) -> Result, Error> { Ok(SendTo::None(None)) } diff --git a/protocols/v2/roles-logic-sv2/src/handlers/mod.rs b/protocols/v2/roles-logic-sv2/src/handlers/mod.rs index b717eb34af..a00eac900d 100644 --- a/protocols/v2/roles-logic-sv2/src/handlers/mod.rs +++ b/protocols/v2/roles-logic-sv2/src/handlers/mod.rs @@ -1,4 +1,4 @@ -//! # Handlers Overview +//! # 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. @@ -16,10 +16,11 @@ //! - `ParseUpstream[Protocol]`: Handles messages from Upstream nodes. //! //! Supported subprotocols include: -//! - `common`: Shared messages across protocols. -//! - `job_declaration`: Job-related messages. -//! - `mining`: Mining-specific messages. -//! - `template_distribution`: Template distribution messages. +//! - `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 //! diff --git a/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs b/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs index 445a839221..307a0ed0e5 100644 --- a/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs +++ b/protocols/v2/roles-logic-sv2/src/handlers/template_distribution.rs @@ -3,16 +3,6 @@ //! This module defines traits and functions for handling template distribution messages within the //! Stratum V2 protocol. //! -//! ## Core Traits -//! -//! - `ParseServerTemplateDistributionMessages`: Implemented by downstream nodes to process template -//! distribution messages received from upstream nodes. This trait includes methods for handling -//! template-related events like new templates, previous hash updates, and transaction data -//! requests. -//! - `ParseClientTemplateDistributionMessages`: Implemented by upstream nodes to manage template -//! distribution messages received from downstream nodes. This trait handles coinbase output size, -//! transaction data requests, and solution submissions. -//! //! ## Message Handling //! //! Handlers are responsible for: @@ -61,16 +51,6 @@ where /// 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. - /// - /// # Arguments - /// - `self_`: An `Arc>` representing the instance of the object implementing this - /// trait. - /// - `message_type`: The type of the incoming message. - /// - `payload`: The raw payload data of the message. - /// - /// # Returns - /// - `Result`: The result of processing the message, where `SendTo` indicates - /// the next step in message handling. fn handle_message_template_distribution( self_: Arc>, message_type: u8, @@ -86,14 +66,6 @@ where /// /// This function takes the deserialized message and processes it according to the specific /// message type, invoking the appropriate handler function. - /// - /// # Arguments - /// - `self_`: An `Arc>` representing the instance of the object implementing this - /// trait. - /// - `message`: The deserialized `TemplateDistribution` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_message_template_distribution_desrialized( self_: Arc>, message: Result, Error>, @@ -154,35 +126,17 @@ where /// /// This method processes the `NewTemplate` message, which contains information about a newly /// generated template. - /// - /// # Arguments - /// - `m`: The `NewTemplate` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. 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. - /// - /// # Arguments - /// - `m`: The `SetNewPrevHash` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. 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. - /// - /// # Arguments - /// - `m`: The `RequestTransactionDataSuccess` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_request_tx_data_success( &mut self, m: RequestTransactionDataSuccess, @@ -191,12 +145,6 @@ where /// Handles a `RequestTransactionDataError` message. /// /// This method processes an error response for a requested transaction data message. - /// - /// # Arguments - /// - `m`: The `RequestTransactionDataError` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_request_tx_data_error( &mut self, m: RequestTransactionDataError, @@ -215,16 +163,6 @@ where /// 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. - /// - /// # Arguments - /// - `self_`: An `Arc>` representing the instance of the object implementing this - /// trait. - /// - `message_type`: The type of the incoming message. - /// - `payload`: The raw payload data of the message. - /// - /// # Returns - /// - `Result`: The result of processing the message, where `SendTo` indicates - /// the next step in message handling. fn handle_message_template_distribution( self_: Arc>, message_type: u8, @@ -240,14 +178,6 @@ where /// /// This function takes the deserialized message and processes it according to the specific /// message type, invoking the appropriate handler function. - /// - /// # Arguments - /// - `self_`: An `Arc>` representing the instance of the object implementing this - /// trait. - /// - `message`: The deserialized `TemplateDistribution` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_message_template_distribution_desrialized( self_: Arc>, message: Result, Error>, @@ -282,34 +212,16 @@ where /// Handles a `CoinbaseOutputDataSize` message. /// /// This method processes a message that includes the coinbase output data size. - /// - /// # Arguments - /// - `m`: The `CoinbaseOutputDataSize` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_coinbase_out_data_size(&mut self, m: CoinbaseOutputDataSize) -> Result; /// Handles a `RequestTransactionData` message. /// /// This method processes a message requesting transaction data. - /// - /// # Arguments - /// - `m`: The `RequestTransactionData` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_request_tx_data(&mut self, m: RequestTransactionData) -> Result; /// Handles a `SubmitSolution` message. /// /// This method processes a solution submission message. - /// - /// # Arguments - /// - `m`: The `SubmitSolution` message. - /// - /// # Returns - /// - `Result`: The result of processing the message. fn handle_request_submit_solution(&mut self, m: SubmitSolution) -> Result; } diff --git a/protocols/v2/roles-logic-sv2/src/job_creator.rs b/protocols/v2/roles-logic-sv2/src/job_creator.rs index 0156f2119d..20777495c9 100644 --- a/protocols/v2/roles-logic-sv2/src/job_creator.rs +++ b/protocols/v2/roles-logic-sv2/src/job_creator.rs @@ -1,5 +1,7 @@ -//! The job creator module provides logic to create extended mining jobs given a template from -//! a template provider as well as logic to clean up old templates when new blocks are mined +//! # Job Creator +//! +//! This module provides logic to create extended mining jobs given a template from +//! a template provider as well as logic to clean up old templates when new blocks are mined. use crate::{errors, utils::Id, Error}; use binary_sv2::B064K; use mining_sv2::NewExtendedMiningJob; @@ -30,7 +32,7 @@ pub struct JobsCreators { extranonce_len: u8, } -/// Transform the byte array `coinbase_outputs` in a vector of TxOut +/// Transforms the byte array `coinbase_outputs` in a vector of TxOut /// It assumes the data to be valid data and does not do any kind of check pub fn tx_outputs_to_costum_scripts(tx_outputs: &[u8]) -> Vec { let mut txs = vec![]; @@ -49,7 +51,7 @@ pub fn tx_outputs_to_costum_scripts(tx_outputs: &[u8]) -> Vec { } impl JobsCreators { - /// constructor + /// Constructor pub fn new(extranonce_len: u8) -> Self { Self { lasts_new_template: Vec::new(), @@ -61,12 +63,12 @@ impl JobsCreators { } } - /// get template id from job + /// Get template id from job pub fn get_template_id_from_job(&self, job_id: u32) -> Option { self.job_to_template_id.get(&job_id).map(|x| x - 1) } - /// used to create new jobs when a new template arrives + /// Used to create new jobs when a new template arrives pub fn on_new_template( &mut self, template: &mut NewTemplate, @@ -131,13 +133,13 @@ impl JobsCreators { } } - /// returns the latest mining target + /// Returns the latest mining target pub fn last_target(&self) -> mining_sv2::Target { self.last_target.clone() } } -/// convert custom job into extended job +/// Converts custom job into extended job pub fn extended_job_from_custom_job( referenced_job: &mining_sv2::SetCustomMiningJob, pool_signature: String, @@ -168,7 +170,7 @@ pub fn extended_job_from_custom_job( ) } -// returns an extended job given the provided template from the Template Provider and other +// Returns an extended job given the provided template from the Template Provider and other // Pool role related fields. // // Pool related arguments: @@ -237,7 +239,7 @@ fn new_extended_job( Ok(new_extended_mining_job) } -// used to extract the coinbase transaction prefix for extended jobs +// Used to extract the coinbase transaction prefix for extended jobs // so the extranonce search space can be introduced fn coinbase_tx_prefix( coinbase: &Transaction, @@ -261,7 +263,7 @@ fn coinbase_tx_prefix( r.try_into().map_err(Error::BinarySv2Error) } -// used to extract the coinbase transaction suffix for extended jobs +// Used to extract the coinbase transaction suffix for extended jobs // so the extranonce search space can be introduced fn coinbase_tx_suffix( coinbase: &Transaction, @@ -423,7 +425,7 @@ impl StrippedCoinbaseTx { }) } - // the coinbase tx prefix is the LE bytes concatenation of the tx version and all + // The coinbase tx prefix is the LE bytes concatenation of the tx version and all // of the tx inputs minus the 32 bytes after the bip34 bytes in the script // and the last input's sequence (used as the first entry in the coinbase tx suffix). // The last 32 bytes after the bip34 bytes in the script will be used to allow extranonce diff --git a/protocols/v2/roles-logic-sv2/src/job_dispatcher.rs b/protocols/v2/roles-logic-sv2/src/job_dispatcher.rs index e0589c526e..c9a0a9f9ea 100644 --- a/protocols/v2/roles-logic-sv2/src/job_dispatcher.rs +++ b/protocols/v2/roles-logic-sv2/src/job_dispatcher.rs @@ -1,4 +1,6 @@ -//! The Job Dispatcher contains relevant logic to maintain group channels in proxy roles such as: +//! Job Dispatcher +//! +//! This module contains relevant logic to maintain group channels in proxy roles such as: //! - converting extended jobs to standard jobs //! - handling updates to jobs when new templates and prev hashes arrive, as well as cleaning up old //! jobs diff --git a/protocols/v2/roles-logic-sv2/src/lib.rs b/protocols/v2/roles-logic-sv2/src/lib.rs index c6ffe67bc2..d560f01b03 100644 --- a/protocols/v2/roles-logic-sv2/src/lib.rs +++ b/protocols/v2/roles-logic-sv2/src/lib.rs @@ -1,39 +1,27 @@ -//! Provides all relevant types, traits and functions to implement a valid SV2 role. +//! # Stratum V2 Roles-Logic Library //! -//! - For channel and job management, see [`channel_logic`], which utilizes [`job_creator`] and -//! [`job_dispatcher`] -//! - For message handling, the traits in [`handlers`] should be implemented -//! - For basic traits every implementation should use, see [`common_properties`] -//! - Routers in [`routing_logic`] are used by the traits in `handlers` to decide which -//! downstream/upstream to relay/send by using [`selectors`] -//! - For serializing/deserializing messages, see [`parsers`] -//! - see [`utils`] for helpers such as safe locking, target and merkle root calculations +//! 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. //! -//!```txt -//! MiningDevice: -//! common_properties::IsUpstream + -//! common_properties::IsMiningUpstream + -//! handlers::common::ParseUpstreamCommonMessages + -//! handlers::mining::ParseUpstreamMiningMessages + +//! ## Usage //! -//! Pool: -//! common_properties::IsDownstream + -//! common_properties::IsMiningDownstream + -//! handlers::common::ParseDownstreamCommonMessages + -//! handlers::mining::ParseDownstreamMiningMessages + +//! To include this crate in your project, run: +//! ```bash +//! $ cargo add roles_logic_sv2 +//! ``` //! -//! ProxyDownstreamConnection: -//! common_properties::IsDownstream + -//! common_properties::IsMiningDownstream + -//! handlers::common::ParseDownstreamCommonMessages + -//! handlers::mining::ParseDownstreamMiningMessages + +//! ## Build Options //! -//! ProxyUpstreamConnection: -//! common_properties::IsUpstream + -//! common_properties::IsMiningUpstream + -//! handlers::common::ParseUpstreamCommonMessages + -//! handlers::mining::ParseUpstreamMiningMessages + -//! ``` +//! This crate can be built with the following features: +//! +//! - `with_serde`: builds [`framing_sv2`], [`binary_sv2`], [`common_messages_sv2`], +//! [`template_distribution_sv2`], [`job_declaration_sv2`], and [`mining_sv2`] crates with +//! `serde`-based encoding and decoding. Note that this feature flag is only used for the Message +//! Generator, and deprecated for any other kind of usage. It will likely be fully deprecated in +//! the future. +//! - `prop_test`: Enables support for property testing in [`template_distribution_sv2`] crate. pub mod channel_logic; pub mod common_properties; pub mod errors; diff --git a/protocols/v2/roles-logic-sv2/src/parsers.rs b/protocols/v2/roles-logic-sv2/src/parsers.rs index 54e7ef0fa4..aac4022937 100644 --- a/protocols/v2/roles-logic-sv2/src/parsers.rs +++ b/protocols/v2/roles-logic-sv2/src/parsers.rs @@ -15,9 +15,10 @@ //! //! ## Supported Subprotocols //! - **Common Messages**: Shared across all Sv2 roles. -//! - **Template Distribution**: Handles block templates and transaction data. -//! - **Job Declaration**: Manages mining job assignments and solutions. -//! - **Mining Protocol**: Manages standard mining communication (e.g., job dispatch, shares). +//! - **Template Distribution**: Handles block templates updates and transaction data. +//! - **Job Declaration**: Manages custom mining job declarations, transactions, and solutions. +//! - **Mining Protocol**: Manages standard mining communication (e.g., job dispatch, shares +//! submission). use crate::Error; diff --git a/protocols/v2/roles-logic-sv2/src/routing_logic.rs b/protocols/v2/roles-logic-sv2/src/routing_logic.rs index 37ddbb7fad..4da60bf745 100644 --- a/protocols/v2/roles-logic-sv2/src/routing_logic.rs +++ b/protocols/v2/roles-logic-sv2/src/routing_logic.rs @@ -1,8 +1,8 @@ +//! # Routing Logic +//! //! This module contains the routing logic used by handlers to determine where a message should be //! relayed or responded to. //! -//! ## Overview -//! //! The routing logic defines a set of traits and structures to manage message routing in Stratum //! V2. The following components are included: //! @@ -17,29 +17,6 @@ //! - **`MiningProxyRoutingLogic`**: Routing logic valid for a standard Sv2 mining proxy, //! implementing both `CommonRouter` and `MiningRouter`. //! -//! ## Details -//! -//! ### Traits -//! -//! - **`CommonRouter`**: Defines routing behavior for common protocol messages. -//! - **`MiningRouter`**: Defines routing behavior for mining protocol messages. Requires -//! `DownstreamMiningSelector` for downstream selection. -//! -//! ### Enums -//! -//! - **`CommonRoutingLogic`**: Represents possible routing logics for the common protocol, such as -//! proxy-based routing or no routing. -//! - **`MiningRoutingLogic`**: Represents possible routing logics for the mining protocol, -//! supporting additional parameters such as selectors and marker traits. -//! -//! ### Structures -//! -//! - **`NoRouting`**: A minimal implementation of `CommonRouter` and `MiningRouter` that panics -//! when used. Its primary purpose is to serve as a placeholder for cases where no routing logic -//! is applied. -//! - **`MiningProxyRoutingLogic`**: Implements routing logic for a standard Sv2 proxy, including -//! upstream selection and message transformation. -//! //! ## Future Work //! //! - Consider hiding all traits from the public API and exporting only marker traits. @@ -67,12 +44,6 @@ use std::{collections::HashMap, fmt::Debug as D, marker::PhantomData, sync::Arc} /// protocol routing. pub trait CommonRouter: std::fmt::Debug { /// Handles a `SetupConnection` message for the common protocol. - /// - /// # Arguments - /// - `message`: The `SetupConnection` message received. - /// - /// # Returns - /// - `Result<(CommonDownstreamData, SetupConnectionSuccess), Error>`: The routing result. fn on_setup_connection( &mut self, message: &SetupConnection, @@ -91,14 +62,6 @@ pub trait MiningRouter< >: CommonRouter { /// Handles an `OpenStandardMiningChannel` message from a downstream. - /// - /// # Arguments - /// - `downstream`: The downstream mining entity. - /// - `request`: The mining channel request message. - /// - `downstream_mining_data`: Associated downstream mining data. - /// - /// # Returns - /// - `Result>, Error>`: The upstream mining entity. fn on_open_standard_channel( &mut self, downstream: Arc>, @@ -107,13 +70,6 @@ pub trait MiningRouter< ) -> Result>, Error>; /// Handles an `OpenStandardMiningChannelSuccess` message from an upstream. - /// - /// # Arguments - /// - `upstream`: The upstream mining entity. - /// - `request`: The successful channel opening message. - /// - /// # Returns - /// - `Result>, Error>`: The downstream mining entity. fn on_open_standard_channel_success( &mut self, upstream: Arc>, @@ -235,14 +191,6 @@ impl< /// /// This method initializes the connection between a downstream and an upstream by determining /// the appropriate upstream based on the provided protocol, versions, and flags. - /// - /// # Arguments - /// - `message`: A reference to the `SetupConnection` message containing the connection details. - /// - /// # Returns - /// - `Result<(CommonDownstreamData, SetupConnectionSuccess), Error>`: On success, returns the - /// downstream connection data and the corresponding setup success message. Returns an error - /// otherwise. fn on_setup_connection( &mut self, message: &SetupConnection, @@ -279,15 +227,6 @@ impl< // This method processes the request to open a standard mining channel. It selects a suitable // upstream, updates the request ID to ensure uniqueness, and then delegates to // `on_open_standard_channel_request_header_only` to finalize the process. - // - // # Arguments - // - `downstream`: The downstream requesting the channel opening. - // - `request`: A mutable reference to the `OpenStandardMiningChannel` message. - // - `downstream_mining_data`: Common data about the downstream mining setup. - // - // # Returns - // - `Result>, Error>`: Returns the selected upstream for the downstream or an - // error. fn on_open_standard_channel( &mut self, downstream: Arc>, @@ -315,14 +254,6 @@ impl< // This method processes the success message received from an upstream when a standard mining // channel is opened. It maps the request ID back to the original ID from the downstream and // updates the associated group and channel IDs in the upstream. - // - // # Arguments - // - `upstream`: The upstream involved in the channel opening. - // - `request`: A mutable reference to the `OpenStandardMiningChannelSuccess` message. - // - // # Returns - // - `Result>, Error>`: Returns the downstream corresponding to the request or - // an error. fn on_open_standard_channel_success( &mut self, upstream: Arc>, @@ -353,13 +284,6 @@ impl< } // Selects the upstream with the lowest total hash rate. -// -// # Arguments -// - `ups`: A mutable slice of upstream mining entities. -// -// # Returns -// - `Arc>`: The upstream entity with the lowest total hash rate. -// // # Panics // This function panics if the slice is empty, as it is internally guaranteed that this function // will only be called with non-empty vectors. @@ -385,12 +309,6 @@ where } // Filters upstream entities that are not configured for header-only mining. -// -// # Arguments -// - `ups`: A mutable slice of upstream mining entities. -// -// # Returns -// - `Vec>>`: A vector of upstream entities that are not header-only. fn filter_header_only(ups: &mut [Arc>]) -> Vec>> where Down: IsMiningDownstream + D, @@ -414,12 +332,6 @@ where // - If only one upstream is available, it is selected. // - If multiple upstreams exist, preference is given to those not configured as header-only. // - Among the remaining upstreams, the one with the lowest total hash rate is selected. -// -// # Arguments -// - `ups`: A mutable slice of upstream mining entities. -// -// # Returns -// - `Option>>`: The selected upstream entity, or `None` if none are available. fn select_upstream(ups: &mut [Arc>]) -> Option>> where Down: IsMiningDownstream + D, @@ -444,12 +356,6 @@ impl< > MiningProxyRoutingLogic { // Selects an upstream entity from a list of available upstreams. - // - // # Arguments - // - `ups`: A mutable slice of upstream mining entities. - // - // # Returns - // - `Option>>`: The selected upstream entity, or `None` if none are available. fn select_upstreams(ups: &mut [Arc>]) -> Option>> { select_upstream(ups) } @@ -458,12 +364,6 @@ impl< /// /// This method selects compatible upstreams, assigns connection flags, and maps the /// downstream to the selected upstreams. - /// - /// # Arguments - /// - `pair_settings`: The pairing settings for the connection. - /// - /// # Returns - /// - `Result<(CommonDownstreamData, SetupConnectionSuccess), Error>`: The connection result. pub fn on_setup_connection_mining_header_only( &mut self, pair_settings: &PairSettings, @@ -487,14 +387,7 @@ impl< Ok((downstream_data, message)) } - /// Handles a standard channel opening request for header-only mining downstream's. - /// - /// # Arguments - /// - `downstream`: The downstream mining entity. - /// - `request`: The standard mining channel request message. - /// - /// # Returns - /// - `Result>, Error>`: The selected upstream mining entity. + /// Handles a standard channel opening request for header-only mining downstreams. pub fn on_open_standard_channel_request_header_only( &mut self, downstream: Arc>, diff --git a/protocols/v2/roles-logic-sv2/src/utils.rs b/protocols/v2/roles-logic-sv2/src/utils.rs index 42e3053e2e..467979d0a1 100644 --- a/protocols/v2/roles-logic-sv2/src/utils.rs +++ b/protocols/v2/roles-logic-sv2/src/utils.rs @@ -87,7 +87,7 @@ pub struct Mutex(Mutex_); impl Mutex { /// Mutex safe lock. /// - /// Safely locks the `Mutex` and executes a closer (`thunk`) with a mutable reference to to the + /// Safely locks the `Mutex` and executes a closer (`thunk`) with a mutable reference to the /// inner value. This ensures that the lock is automatically released after the closure /// completes, preventing deadlocks. It explicitly returns a [`PoisonError`] containing a /// [`MutexGuard`] to the inner value in cases where the lock is poisoned. @@ -212,7 +212,7 @@ pub fn merkle_root_from_path_>(coinbase_id: [u8; 32], path: &[T]) } } -// Computes the Merkle root by iteratively combines the coinbase transaction hash with each +// Computes the Merkle root by iteratively combining the coinbase transaction hash with each // transaction hash in the `path`. // // Handles the core logic of combining hashes using the Bitcoin double-SHA256 hashing algorithm. @@ -430,13 +430,13 @@ pub fn hash_rate_to_target( /// /// ## Formula /// ```text -/// h = (2^256 - target) / (s * (t + 1)) +/// h = (2^256 - t) / (s * (t + 1)) /// ``` /// /// Where: /// - `h`: Mining device hashrate (H/s). /// - `t`: Target threshold. -/// - `s`: Shares per second `60 / shares/min`. +/// - `s`: Shares per minute. pub fn hash_rate_from_target(target: U256<'static>, share_per_min: f64) -> Result { // checks that we are not dividing by zero if share_per_min == 0.0 {