Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestions for 813-standardize-cli #61

Merged
merged 16 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion roles/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion roles/jd-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ error_handling = { version = "1.0.0", path = "../../utils/error-handling" }
nohash-hasher = "0.2.0"
key-utils = { version = "^1.0.0", path = "../../utils/key-utils" }
clap = { version = "^4.5.4", features = ["derive"] }
config = { version = "0.14.0", features = ["toml"] }
ext-config = { version = "0.14.0", features = ["toml"], package = "config" }
21 changes: 9 additions & 12 deletions roles/jd-client/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::lib::{error::JdcResult, jdc_config::JdcConfig};
use crate::{JdcConfig, JdcResult};

use clap::Parser;

Expand All @@ -12,18 +12,15 @@ struct Args {
#[allow(clippy::result_large_err)]
pub fn process_cli_args<'a>() -> JdcResult<'a, JdcConfig> {
let args = Args::parse();
let config = match config::Config::builder()
.add_source(config::File::with_name(&args.config_path))
let config = ext_config::Config::builder()
.add_source(ext_config::File::with_name(&args.config_path))
.build()
{
Ok(cfg) => cfg,
Err(e) => {
tracing::error!("{:?}", e);
std::process::exit(1)
}
};
.unwrap_or_else(|e| {
tracing::error!("{}", e);
std::process::exit(1);
});

let jdc_config: JdcConfig = config.try_deserialize()?;
let config = config.try_deserialize::<JdcConfig>()?;

Ok(jdc_config)
Ok(config)
}
43 changes: 21 additions & 22 deletions roles/jd-client/src/lib/downstream.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use super::{
job_declarator::JobDeclarator,
status::{self, State},
upstream_sv2::Upstream as UpstreamMiningNode,
use crate::{
job_declarator::JobDeclarator, status, upstream_sv2::Upstream as UpstreamMiningNode,
IS_NEW_TEMPLATE_HANDLED,
};
use async_channel::{Receiver, SendError, Sender};
use roles_logic_sv2::{
channel_logic::channel_factory::{OnNewShare, PoolChannelFactory, Share},
common_messages_sv2::{SetupConnection, SetupConnectionSuccess},
common_properties::{CommonDownstreamData, IsDownstream, IsMiningDownstream},
errors::Error,
handlers::{
common::{ParseDownstreamCommonMessages, SendTo as SendToCommon},
mining::{ParseDownstreamMiningMessages, SendTo, SupportedChannelTypes},
Expand All @@ -18,6 +16,7 @@ use roles_logic_sv2::{
parsers::{Mining, MiningDeviceMessages, PoolMessages},
template_distribution_sv2::{NewTemplate, SubmitSolution},
utils::Mutex,
Error as RolesLogicSv2Error,
};
use tracing::{debug, error, info, warn};

Expand Down Expand Up @@ -211,9 +210,9 @@ impl DownstreamMiningNode {
Self::next(self_mutex, incoming).await;
}
let tx_status = self_mutex.safe_lock(|s| s.tx_status.clone()).unwrap();
let err = Error::DownstreamDown;
let err = RolesLogicSv2Error::DownstreamDown;
let status = status::Status {
state: State::DownstreamShutdown(err.into()),
state: status::State::DownstreamShutdown(err.into()),
};
tx_status.send(status).await.unwrap();
} else {
Expand Down Expand Up @@ -269,7 +268,7 @@ impl DownstreamMiningNode {
#[async_recursion::async_recursion]
async fn match_send_to(
self_mutex: Arc<Mutex<Self>>,
next_message_to_send: Result<SendTo<UpstreamMiningNode>, Error>,
next_message_to_send: Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error>,
incoming: Option<StdFrame>,
) {
match next_message_to_send {
Expand Down Expand Up @@ -355,9 +354,9 @@ impl DownstreamMiningNode {
self_mutex: &Arc<Mutex<Self>>,
mut new_template: NewTemplate<'static>,
pool_output: &[u8],
) -> Result<(), Error> {
) -> Result<(), RolesLogicSv2Error> {
if !self_mutex.safe_lock(|s| s.status.have_channel()).unwrap() {
super::IS_NEW_TEMPLATE_HANDLED.store(true, std::sync::atomic::Ordering::Release);
IS_NEW_TEMPLATE_HANDLED.store(true, std::sync::atomic::Ordering::Release);
return Ok(());
}
let mut pool_out = &pool_output[0..];
Expand Down Expand Up @@ -392,14 +391,14 @@ impl DownstreamMiningNode {
}
// See coment on the definition of the global for memory
// ordering
super::IS_NEW_TEMPLATE_HANDLED.store(true, std::sync::atomic::Ordering::Release);
IS_NEW_TEMPLATE_HANDLED.store(true, std::sync::atomic::Ordering::Release);
Ok(())
}

pub async fn on_set_new_prev_hash(
self_mutex: &Arc<Mutex<Self>>,
new_prev_hash: roles_logic_sv2::template_distribution_sv2::SetNewPrevHash<'static>,
) -> Result<(), Error> {
) -> Result<(), RolesLogicSv2Error> {
if !self_mutex.safe_lock(|s| s.status.have_channel()).unwrap() {
return Ok(());
}
Expand Down Expand Up @@ -452,15 +451,15 @@ impl
&mut self,
_: OpenStandardMiningChannel,
_: Option<Arc<Mutex<UpstreamMiningNode>>>,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
warn!("Ignoring OpenStandardMiningChannel");
Ok(SendTo::None(None))
}

fn handle_open_extended_mining_channel(
&mut self,
m: OpenExtendedMiningChannel,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
if !self.status.is_solo_miner() {
// Safe unwrap alreay checked if it cointains upstream with is_solo_miner
Ok(SendTo::RelaySameMessageToRemote(
Expand Down Expand Up @@ -507,15 +506,15 @@ impl
let messages = messages.into_iter().map(SendTo::Respond).collect();
Ok(SendTo::Multiple(messages))
}
Err(_) => Err(roles_logic_sv2::Error::ChannelIsNeitherExtendedNeitherInAPool),
Err(_) => Err(RolesLogicSv2Error::ChannelIsNeitherExtendedNeitherInAPool),
}
}
}

fn handle_update_channel(
&mut self,
_: UpdateChannel,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
if !self.status.is_solo_miner() {
// Safe unwrap alreay checked if it cointains upstream with is_solo_miner
Ok(SendTo::RelaySameMessageToRemote(
Expand All @@ -529,15 +528,15 @@ impl
fn handle_submit_shares_standard(
&mut self,
_: SubmitSharesStandard,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
warn!("Ignoring SubmitSharesStandard");
Ok(SendTo::None(None))
}

fn handle_submit_shares_extended(
&mut self,
m: SubmitSharesExtended,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
match self
.status
.get_channel()
Expand Down Expand Up @@ -618,7 +617,7 @@ impl
fn handle_set_custom_mining_job(
&mut self,
_: SetCustomMiningJob,
) -> Result<SendTo<UpstreamMiningNode>, Error> {
) -> Result<SendTo<UpstreamMiningNode>, RolesLogicSv2Error> {
warn!("Ignoring SetCustomMiningJob");
Ok(SendTo::None(None))
}
Expand All @@ -630,8 +629,8 @@ impl ParseDownstreamCommonMessages<roles_logic_sv2::routing_logic::NoRouting>
fn handle_setup_connection(
&mut self,
_: SetupConnection,
_: Option<Result<(CommonDownstreamData, SetupConnectionSuccess), Error>>,
) -> Result<roles_logic_sv2::handlers::common::SendTo, Error> {
_: Option<Result<(CommonDownstreamData, SetupConnectionSuccess), RolesLogicSv2Error>>,
) -> Result<roles_logic_sv2::handlers::common::SendTo, RolesLogicSv2Error> {
let response = SetupConnectionSuccess {
used_version: 2,
// require extended channels
Expand Down Expand Up @@ -669,7 +668,7 @@ pub async fn listen_for_downstream_mining(
tx_status: status::Sender,
miner_coinbase_output: Vec<TxOut>,
jd: Option<Arc<Mutex<JobDeclarator>>>,
) -> Result<Arc<Mutex<DownstreamMiningNode>>, Error> {
) -> Result<Arc<Mutex<DownstreamMiningNode>>, RolesLogicSv2Error> {
info!("Listening for downstream mining connections on {}", address);
let listner = TcpListener::bind(address).await.unwrap();

Expand Down
18 changes: 9 additions & 9 deletions roles/jd-client/src/lib/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub enum ChannelSendError<'a> {
#[derive(Debug)]
pub enum JdcError<'a> {
VecToSlice32(Vec<u8>),
ConfigError(config::ConfigError),
ConfigError(ext_config::ConfigError),
/// Errors from `binary_sv2` crate.
BinarySv2(binary_sv2::Error),
/// Errors on bad noise handshake.
Expand All @@ -40,8 +40,8 @@ pub enum JdcError<'a> {
/// 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),
RolesLogicSv2(roles_logic_sv2::Error),
UpstreamIncoming(roles_logic_sv2::Error),
#[allow(dead_code)]
SubprotocolMining(String),
// Locking Errors
Expand All @@ -65,7 +65,7 @@ impl<'a> fmt::Display for JdcError<'a> {
FramingSv2(ref e) => write!(f, "Framing SV2 error: `{:?}`", e),
Io(ref e) => write!(f, "I/O error: `{:?}", e),
ParseInt(ref e) => write!(f, "Bad convert from `String` to `int`: `{:?}`", e),
RolesSv2Logic(ref e) => write!(f, "Roles SV2 Logic Error: `{:?}`", e),
RolesLogicSv2(ref e) => write!(f, "Roles SV2 Logic Error: `{:?}`", e),
SubprotocolMining(ref e) => write!(f, "Subprotocol Mining Error: `{:?}`", e),
UpstreamIncoming(ref e) => write!(f, "Upstream parse incoming error: `{:?}`", e),
PoisonLock => write!(f, "Poison Lock error"),
Expand All @@ -79,8 +79,8 @@ impl<'a> fmt::Display for JdcError<'a> {
}
}

impl<'a> From<config::ConfigError> for JdcError<'a> {
fn from(e: config::ConfigError) -> JdcError<'a> {
impl<'a> From<ext_config::ConfigError> for JdcError<'a> {
fn from(e: ext_config::ConfigError) -> JdcError<'a> {
JdcError::ConfigError(e)
}
}
Expand Down Expand Up @@ -115,9 +115,9 @@ impl<'a> From<std::num::ParseIntError> for JdcError<'a> {
}
}

impl<'a> From<roles_logic_sv2::errors::Error> for JdcError<'a> {
fn from(e: roles_logic_sv2::errors::Error) -> Self {
JdcError::RolesSv2Logic(e)
impl<'a> From<roles_logic_sv2::Error> for JdcError<'a> {
fn from(e: roles_logic_sv2::Error) -> Self {
JdcError::RolesLogicSv2(e)
}
}

Expand Down
17 changes: 11 additions & 6 deletions roles/jd-client/src/lib/jdc_config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::{JdcError, JdcResult};
use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey};
use roles_logic_sv2::{errors::Error, utils::CoinbaseOutput as CoinbaseOutput_};
use roles_logic_sv2::{
errors::Error as RolesLogicSv2Error, utils::CoinbaseOutput as CoinbaseOutput_,
};
use serde::Deserialize;
use std::time::Duration;
use stratum_common::bitcoin::TxOut;
Expand All @@ -11,15 +14,15 @@ pub struct CoinbaseOutput {
}

impl TryFrom<&CoinbaseOutput> for CoinbaseOutput_ {
type Error = Error;
type Error = RolesLogicSv2Error;

fn try_from(pool_output: &CoinbaseOutput) -> Result<Self, Self::Error> {
fn try_from(pool_output: &CoinbaseOutput) -> Result<Self, RolesLogicSv2Error> {
match pool_output.output_script_type.as_str() {
"P2PK" | "P2PKH" | "P2WPKH" | "P2SH" | "P2WSH" | "P2TR" => Ok(CoinbaseOutput_ {
output_script_type: pool_output.clone().output_script_type,
output_script_value: pool_output.clone().output_script_value,
}),
_ => Err(Error::UnknownOutputScriptType),
_ => Err(RolesLogicSv2Error::UnknownOutputScriptType),
}
}
}
Expand Down Expand Up @@ -82,7 +85,7 @@ where
}
}

pub fn get_coinbase_output(config: &JdcConfig) -> Result<Vec<TxOut>, Error> {
pub fn get_coinbase_output(config: &JdcConfig) -> JdcResult<'static, Vec<TxOut>> {
let mut result = Vec::new();
for coinbase_output_pool in &config.coinbase_outputs {
let coinbase_output: CoinbaseOutput_ = coinbase_output_pool.try_into()?;
Expand All @@ -93,7 +96,9 @@ pub fn get_coinbase_output(config: &JdcConfig) -> Result<Vec<TxOut>, Error> {
});
}
match result.is_empty() {
true => Err(Error::EmptyCoinbaseOutputs),
true => Err(JdcError::RolesLogicSv2(
RolesLogicSv2Error::EmptyCoinbaseOutputs,
)),
_ => Ok(result),
}
}
14 changes: 7 additions & 7 deletions roles/jd-client/src/lib/job_declarator/message_handler.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::JobDeclarator;
use crate::job_declarator::JobDeclarator;
use roles_logic_sv2::{
handlers::{job_declaration::ParseServerJobDeclarationMessages, SendTo_},
job_declaration_sv2::{
Expand All @@ -7,15 +7,15 @@ use roles_logic_sv2::{
ProvideMissingTransactionsSuccess,
},
parsers::JobDeclaration,
Error as RolesLogicSv2Error,
};
pub type SendTo = SendTo_<JobDeclaration<'static>, ()>;
use roles_logic_sv2::errors::Error;

impl ParseServerJobDeclarationMessages for JobDeclarator {
fn handle_allocate_mining_job_token_success(
&mut self,
message: AllocateMiningJobTokenSuccess,
) -> Result<SendTo, Error> {
) -> Result<SendTo, RolesLogicSv2Error> {
self.allocated_tokens.push(message.into_static());

Ok(SendTo::None(None))
Expand All @@ -24,22 +24,22 @@ impl ParseServerJobDeclarationMessages for JobDeclarator {
fn handle_declare_mining_job_success(
&mut self,
message: DeclareMiningJobSuccess,
) -> Result<SendTo, Error> {
) -> Result<SendTo, RolesLogicSv2Error> {
let message = JobDeclaration::DeclareMiningJobSuccess(message.into_static());
Ok(SendTo::None(Some(message)))
}

fn handle_declare_mining_job_error(
&mut self,
_message: DeclareMiningJobError,
) -> Result<SendTo, Error> {
) -> Result<SendTo, RolesLogicSv2Error> {
Ok(SendTo::None(None))
}

fn handle_identify_transactions(
&mut self,
message: IdentifyTransactions,
) -> Result<SendTo, Error> {
) -> Result<SendTo, RolesLogicSv2Error> {
let message_identify_transactions = IdentifyTransactionsSuccess {
request_id: message.request_id,
tx_data_hashes: Vec::new().into(),
Expand All @@ -52,7 +52,7 @@ impl ParseServerJobDeclarationMessages for JobDeclarator {
fn handle_provide_missing_transactions(
&mut self,
message: ProvideMissingTransactions,
) -> Result<SendTo, Error> {
) -> Result<SendTo, RolesLogicSv2Error> {
let tx_list = self
.last_declare_mining_jobs_sent
.get(&message.request_id)
Expand Down
4 changes: 2 additions & 2 deletions roles/jd-client/src/lib/job_declarator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub type StdFrame = StandardSv2Frame<Message>;
mod setup_connection;
use setup_connection::SetupConnectionHandler;

use super::{error::JdcError, jdc_config::JdcConfig, upstream_sv2::Upstream};
use crate::{upstream_sv2::Upstream, JdcConfig, JdcResult};

#[derive(Debug, Clone)]
pub struct LastDeclareJob {
Expand Down Expand Up @@ -83,7 +83,7 @@ impl JobDeclarator {
config: JdcConfig,
up: Arc<Mutex<Upstream>>,
task_collector: Arc<Mutex<Vec<AbortHandle>>>,
) -> Result<Arc<Mutex<Self>>, JdcError<'static>> {
) -> JdcResult<'static, Arc<Mutex<Self>>> {
let stream = tokio::net::TcpStream::connect(address).await?;
let initiator = Initiator::from_raw_k(authority_public_key)?;
let (mut receiver, mut sender, _, _) =
Expand Down
Loading