Skip to content

Commit

Permalink
roles_logic doc nits
Browse files Browse the repository at this point in the history
  • Loading branch information
Shourya742 authored and plebhash committed Dec 11, 2024
1 parent 4de3901 commit 02ca199
Show file tree
Hide file tree
Showing 13 changed files with 249 additions and 241 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub enum OnNewShare {
/// Used when the received is malformed, is for an inexistent channel or do not meet downstream
/// target.
SendErrorDownstream(SubmitSharesError<'static>),
/// Used when an exteded channel in a proxy receive a share, and the share meet upstream
/// Used when an extended channel in a proxy receive a share, and the share meet upstream
/// target, in this case a new share must be sent upstream. Also an optional template id is
/// returned, when a job declarator want to send a valid share upstream could use the
/// template for get the up job id.
Expand All @@ -71,7 +71,7 @@ pub enum OnNewShare {
/// (share, template id, coinbase,complete extranonce)
ShareMeetBitcoinTarget((Share, Option<u64>, Vec<u8>, Vec<u8>)),
/// Indicate that the share meet downstream target, in the case we could send a success
/// response dowmstream.
/// response downstream.
ShareMeetDownstreamTarget,
}

Expand Down Expand Up @@ -266,7 +266,7 @@ impl ChannelFactory {
let max_extranonce_size = self.extranonces.get_range2_len() as u16;
if min_extranonce_size <= max_extranonce_size {
// SECURITY is very unlikely to finish the ids btw this unwrap could be used by an
// attaccher that want to dirsrupt the service maybe we should have a method
// attacker that want to disrupt the service maybe we should have a method
// to reuse ids that are no longer connected?
let channel_id = self
.ids
Expand Down Expand Up @@ -404,7 +404,7 @@ impl ChannelFactory {
}

/// This function is called when downstream have a group channel
/// Shouldnt all standard channel's be non HOM??
/// should not all standard channel's be non HOM??
fn new_standard_channel_for_non_hom_downstream(
&mut self,
request_id: u32,
Expand Down Expand Up @@ -472,7 +472,7 @@ impl ChannelFactory {
.get(&channel_id)
.unwrap();
// OPTIMIZATION this could be memoized somewhere cause is very likely that we will receive a
// lot od OpenStandardMiningChannel requests consequtevely
// lot od OpenStandardMiningChannel requests consecutively
let job_id = self.job_ids.next();
let future_jobs: Option<Vec<NewMiningJob<'static>>> = self
.future_jobs
Expand Down Expand Up @@ -568,11 +568,11 @@ impl ChannelFactory {
}

// When a new non HOM downstream opens a channel, we use this function to prepare all the
// extended jobs (future and non) and the prev hash that we need to send dowmstream
// extended jobs (future and non) and the prev hash that we need to send downstream
fn prepare_jobs_and_p_hash(&mut self, result: &mut Vec<Mining>, complete_id: u64) {
// If group is 0 it means that we are preparing jobs and p hash for a non HOM downstream
// that want to open a new extended channel in that case we want to use the channel id
// TODO verify that this is true also for the case where the channle factory is in a proxy
// TODO verify that this is true also for the case where the channel factory is in a proxy
// and not in a pool.
let group_id = match GroupId::into_group_id(complete_id) {
0 => GroupId::into_channel_id(complete_id),
Expand Down Expand Up @@ -1178,7 +1178,7 @@ impl PoolChannelFactory {
let target = self.job_creator.last_target();
// When downstream set a custom mining job we add the job to the negotiated job
// hashmap, with the extended channel id as a key. Whenever the pool receive a share must
// first check if the channel have a negotiated job if so we can not retreive the template
// first check if the channel have a negotiated job if so we can not retrieve the template
// via the job creator but we create a new one from the set custom job.
if self.negotiated_jobs.contains_key(&m.channel_id) {
let referenced_job = self.negotiated_jobs.get(&m.channel_id).unwrap();
Expand Down Expand Up @@ -1318,7 +1318,7 @@ impl PoolChannelFactory {
}
}

/// Used by proxies that want to open extended channls with upstream. If the proxy has job
/// Used by proxies that want to open extended channels with upstream. If the proxy has job
/// declaration capabilities, we set the job creator and the coinbase outs.
#[derive(Debug)]
pub struct ProxyExtendedChannelFactory {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ impl GroupChannel {
last_received_job: None,
}
}
/// Called when a channel is successfully opened for header only mining on standard channels.
/// Here we store the new channel, and update state for jobs and return relevant SV2 messages
/// (NewMiningJob and SNPH)
// Called when a channel is successfully opened for header only mining(HOM) on standard
// channels. Here, we store the new channel, and update state for jobs and return relevant
// SV2 messages (NewMiningJob and SNPH)
fn on_channel_success_for_hom_downtream(
&mut self,
m: OpenStandardMiningChannelSuccess,
Expand Down Expand Up @@ -151,9 +151,10 @@ impl GroupChannel {

Ok(res)
}
/// If a matching job is already in the future job queue,
/// we set a new valid job, otherwise we clear the future jobs
/// queue and stage a prev hash to be used when the job arrives

// If a matching job is already in the future job queue,
// we set a new valid job, otherwise we clear the future jobs
// queue and stage a prev hash to be used when the job arrives
fn update_new_prev_hash(&mut self, m: &SetNewPrevHash) {
while let Some(job) = self.future_jobs.pop() {
if job.job_id == m.job_id {
Expand All @@ -171,8 +172,9 @@ impl GroupChannel {
};
self.last_prev_hash = Some(cloned.clone());
}
/// Pushes new job to future_job queue if it is future,
/// otherwise we set it as the valid job

// Pushes new job to future_job queue if it is future,
// otherwise we set it as the valid job
fn on_new_extended_mining_job(&mut self, m: NewExtendedMiningJob<'static>) {
self.last_received_job = Some(m.clone());
if m.is_future() {
Expand All @@ -181,7 +183,8 @@ impl GroupChannel {
self.last_valid_job = Some(m)
}
}
/// Returns most recent job

// Returns most recent job
fn last_received_job_to_standard_job(
&mut self,
channel_id: u32,
Expand Down
14 changes: 7 additions & 7 deletions protocols/v2/roles-logic-sv2/src/common_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct PairSettings {
pub trait IsUpstream<Down: IsDownstream, Sel: DownstreamSelector<Down> + ?Sized> {
/// Used to bitcoin protocol version for the channel.
fn get_version(&self) -> u16;
// Used to get flags for the defined sv2 message protocol
/// Used to get flags for the defined sv2 message protocol
fn get_flags(&self) -> u32;
/// Used to check if the upstream supports the protocol that the downstream wants to use
fn get_supported_protocols(&self) -> Vec<Protocol>;
Expand All @@ -55,7 +55,7 @@ pub trait IsUpstream<Down: IsDownstream, Sel: DownstreamSelector<Down> + ?Sized>
/// Channel to be opened with the upstream nodes.
#[derive(Debug, Clone, Copy)]
pub enum UpstreamChannel {
// nominal hash rate
/// nominal hash rate
Standard(f32),
Group,
Extended,
Expand Down Expand Up @@ -108,7 +108,7 @@ pub trait IsMiningDownstream: IsDownstream {
}
}

/// Implemented for the NullDownstreamMiningSelector
// Implemented for the NullDownstreamMiningSelector
impl<Down: IsDownstream + D> IsUpstream<Down, NullDownstreamMiningSelector> for () {
fn get_version(&self) -> u16 {
unreachable!("Null upstream do not have a version");
Expand All @@ -134,7 +134,7 @@ impl<Down: IsDownstream + D> IsUpstream<Down, NullDownstreamMiningSelector> for
}
}

/// Implemented for the NullDownstreamMiningSelector
// Implemented for the NullDownstreamMiningSelector
impl IsDownstream for () {
fn get_downstream_mining_data(&self) -> CommonDownstreamData {
unreachable!("Null downstream do not have mining data");
Expand All @@ -160,11 +160,11 @@ impl<Down: IsMiningDownstream + D> IsMiningUpstream<Down, NullDownstreamMiningSe

impl IsMiningDownstream for () {}

/// Proxies likely need to change the request ids of the downsteam's messages. They also need to
/// Proxies likely need to change the request ids of the downstream's messages. They also need to
/// remember the original id to patch the upstream's response with it.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RequestIdMapper {
/// Mapping of upstream id -> downstream ids
// Mapping of upstream id -> downstream ids
request_ids_map: HashMap<u32, u32, BuildNoHashHasher<u32>>,
next_id: u32,
}
Expand All @@ -188,7 +188,7 @@ impl RequestIdMapper {
new_id
}

/// Removes a upstream/downstream mapping from the `RequsetIdMapper`.
/// Removes a upstream/downstream mapping from the `RequestIdMapper`.
pub fn remove(&mut self, upstream_id: u32) -> Option<u32> {
self.request_ids_map.remove(&upstream_id)
}
Expand Down
17 changes: 9 additions & 8 deletions protocols/v2/roles-logic-sv2/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{
use binary_sv2::Error as BinarySv2Error;
use std::fmt::{self, Display, Formatter};

/// Error enum
#[derive(Debug)]
pub enum Error {
/// Payload size is too big to fit into a frame
Expand All @@ -29,7 +30,7 @@ pub enum Error {
NoCompatibleUpstream(CommonDownstreamData),
/// Error if the hashmap `future_jobs` field in the `GroupChannelJobDispatcher` is empty.
NoFutureJobs,
/// No Downstreams connected
/// No Downstream's connected
NoDownstreamsConnected,
/// PrevHash requires non-existent Job Id
PrevHashRequireNonExistentJobId(u32),
Expand Down Expand Up @@ -61,7 +62,7 @@ pub enum Error {
GroupIdNotFound,
/// A share has been received but no job for it exist
ShareDoNotMatchAnyJob,
/// A share has been recived but no channel for it exist
/// A share has been received but no channel for it exist
ShareDoNotMatchAnyChannel,
/// Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase
InvalidCoinbase,
Expand Down Expand Up @@ -124,7 +125,7 @@ impl Display for Error {
BadPayloadSize => write!(f, "Payload is too big to fit into the frame"),
BinarySv2Error(v) => write!(
f,
"BinarySv2Error: error in serializing/deserilizing binary format {:?}",
"BinarySv2Error: error in serializing/deserializing binary format {:?}",
v
),
DownstreamDown => {
Expand Down Expand Up @@ -174,12 +175,12 @@ impl Display for Error {
},
NoMoreExtranonces => write!(f, "No more extranonces"),
JobIsNotFutureButPrevHashNotPresent => write!(f, "A non future job always expect a previous new prev hash"),
ChannelIsNeitherExtendedNeitherInAPool => write!(f, "If a channel is neither extended neither is part of a pool the only thing to do when a OpenStandardChannle is received is to relay it upstream with and updated request id"),
ExtranonceSpaceEnded => write!(f, "No more avaible extranonces for downstream"),
ChannelIsNeitherExtendedNeitherInAPool => write!(f, "If a channel is neither extended neither is part of a pool the only thing to do when a OpenStandardChannel is received is to relay it upstream with and updated request id"),
ExtranonceSpaceEnded => write!(f, "No more available extranonces for downstream"),
ImpossibleToCalculateMerkleRoot => write!(f, "Impossible to calculate merkle root"),
GroupIdNotFound => write!(f, "Group id not found"),
ShareDoNotMatchAnyJob => write!(f, "A share has been recived but no job for it exist"),
ShareDoNotMatchAnyChannel => write!(f, "A share has been recived but no channel for it exist"),
ShareDoNotMatchAnyJob => write!(f, "A share has been received but no job for it exist"),
ShareDoNotMatchAnyChannel => write!(f, "A share has been received but no channel for it exist"),
InvalidCoinbase => write!(f, "Coinbase prefix + extranonce + coinbase suffix is not a valid coinbase"),
ValueRemainingNotUpdated => write!(f, "Value remaining in coinbase output was not correctly updated (it's equal to 0)"),
UnknownOutputScriptType => write!(f, "Unknown script type in config"),
Expand All @@ -189,7 +190,7 @@ impl Display for Error {
TxVersionTooBig => write!(f, "Tx version can not be greater than i32::MAX"),
TxVersionTooLow => write!(f, "Tx version can not be lower than 1"),
TxDecodingError(e) => write!(f, "Impossible to decode tx: {:?}", e),
NotFoundChannelId => write!(f, "No downstream has been registred for this channel id"),
NotFoundChannelId => write!(f, "No downstream has been registered for this channel id"),
NoValidJob => write!(f, "Impossible to create a standard job for channelA cause no valid job has been received from upstream yet"),
NoValidTranslatorJob => write!(f, "Impossible to create a extended job for channel cause no valid job has been received from upstream yet"),
NoTemplateForId => write!(f, "Impossible to retrieve a template for the required job id"),
Expand Down
2 changes: 2 additions & 0 deletions protocols/v2/roles-logic-sv2/src/handlers/job_declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
use crate::{parsers::JobDeclaration, utils::Mutex};
use std::sync::Arc;

/// see [`SendTo_`]
pub type SendTo = SendTo_<JobDeclaration<'static>, ()>;
use super::SendTo_;
use crate::errors::Error;
Expand Down
1 change: 1 addition & 0 deletions protocols/v2/roles-logic-sv2/src/handlers/mining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ use const_sv2::*;
use std::{fmt::Debug as D, sync::Arc};
use tracing::{debug, error, info, trace};

/// see [`SendTo_`]
pub type SendTo<Remote> = SendTo_<Mining<'static>, Remote>;

/// Represents supported channel types in a mining connection.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use template_distribution_sv2::{
RequestTransactionDataSuccess, SetNewPrevHash, SubmitSolution,
};

/// see [`SendTo_`]
pub type SendTo = SendTo_<TemplateDistribution<'static>, ()>;
use const_sv2::*;
use core::convert::TryInto;
Expand Down
Loading

0 comments on commit 02ca199

Please sign in to comment.