Skip to content

Commit

Permalink
feat: add miner input processing (#6016)
Browse files Browse the repository at this point in the history
Description
---
Added miner input processing to the minotari miner and merge mining
proxy. The miner wallet address, base node gRPC address and basic gRPC
connection will be verified.

Motivation and Context
---
Users did not have a good user experience
See #5929

How Has This Been Tested?
---
System-level testing

What process can a PR reviewer use to test or verify this change?
---
Code walk-through
System-level testing

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->

Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->

---------

Co-authored-by: SW van Heerden <swvheerden@gmail.com>
  • Loading branch information
hansieodendaal and SWvheerden committed Dec 8, 2023
1 parent 3129ce8 commit 26f5b60
Show file tree
Hide file tree
Showing 14 changed files with 387 additions and 153 deletions.
21 changes: 21 additions & 0 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions applications/minotari_app_utilities/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ tari_common_types = { path = "../../base_layer/common_types" }
tari_comms = { path = "../../comms/core" }
tari_features = { path = "../../common/tari_features"}
tari_utilities = { version = "0.7" }
minotari_app_grpc = { path = "../minotari_app_grpc" }

clap = { version = "3.2", features = ["derive", "env"] }
futures = { version = "^0.3.16", default-features = false, features = ["alloc"] }
Expand All @@ -20,6 +21,9 @@ rand = "0.8"
tokio = { version = "1.23", features = ["signal"] }
serde = "1.0.126"
thiserror = "^1.0.26"
dialoguer = { version = "0.10" }
tonic = "0.6.2"


[build-dependencies]
tari_common = { path = "../../common", features = ["build", "static-application-info"] }
Expand Down
1 change: 1 addition & 0 deletions applications/minotari_app_utilities/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
pub mod common_cli_args;
pub mod identity_management;
pub mod network_check;
pub mod parse_miner_input;
pub mod utilities;

pub mod consts {
Expand Down
195 changes: 195 additions & 0 deletions applications/minotari_app_utilities/src/parse_miner_input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// Copyright 2021. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::{net::SocketAddr, str::FromStr};

use dialoguer::Input as InputPrompt;
use minotari_app_grpc::{
authentication::ClientAuthenticationInterceptor,
tari_rpc::{base_node_client::BaseNodeClient, Block, NewBlockTemplate, NewBlockTemplateRequest},
};
use tari_common::configuration::{
bootstrap::{grpc_default_port, ApplicationType},
Network,
};
use tari_common_types::tari_address::TariAddress;
use tari_comms::{multiaddr::Multiaddr, utils::multiaddr::multiaddr_to_socketaddr};
use thiserror::Error;
use tonic::{codegen::InterceptedService, transport::Channel, Code};

/// Error parsing input
#[derive(Debug, Error)]
pub enum ParseInputError {
#[error("Could not convert data:{0}")]
WalletPaymentAddress(String),
#[error("Could not convert data:{0}")]
BaseNodeSocketAddress(String),
}

/// Read base_node_socket_address arg or prompt for input
pub fn base_node_socket_address(
base_node_grpc_address: Option<Multiaddr>,
network: Network,
) -> Result<SocketAddr, ParseInputError> {
match base_node_grpc_address {
Some(address) => {
println!("Base node gRPC address: '{}'", address);
match multiaddr_to_socketaddr(&address) {
Ok(val) => Ok(val),
Err(e) => Err(ParseInputError::BaseNodeSocketAddress(format!(
"Error - base node socket address '{}' not valid ({:?})",
address, e
))),
}
},
None => {
println!();
// Get it on the command line
loop {
let mut address = InputPrompt::<String>::new()
.with_prompt("Please enter 'base-node-grpc-address' ('quit' or 'exit' to quit) ")
.default(format!(
"/ip4/127.0.0.1/tcp/{}",
grpc_default_port(ApplicationType::BaseNode, network)
))
.interact()
.unwrap();
process_quit(&address);
// Remove leading and trailing whitespace
address = address.trim().to_string();
let base_node_multi_address: Result<Multiaddr, String> =
address.parse().map_err(|e| format!("{:?}", e));
match base_node_multi_address {
Ok(val) => match multiaddr_to_socketaddr(&val) {
Ok(val) => {
println!();
return Ok(val);
},
Err(e) => println!(" Error - base node socket address '{}' not valid ({:?})", val, e),
},
Err(e) => println!(" Error - base node gRPC address '{}' not valid ({:?})", address, e),
}
}
},
}
}

/// Read wallet_payment_address arg or prompt for input
pub fn wallet_payment_address(
config_wallet_payment_address: String,
network: Network,
) -> Result<TariAddress, ParseInputError> {
// Verify config setting
return match TariAddress::from_str(&config_wallet_payment_address) {
Ok(address) => {
if address == TariAddress::default() {
println!();
// Get it on the command line
loop {
let mut address = InputPrompt::<String>::new()
.with_prompt("Please enter 'wallet-payment-address' ('quit' or 'exit' to quit) ")
.interact()
.unwrap();
process_quit(&address);
// Remove leading and trailing whitespace
address = address.trim().to_string();
let wallet_address: Result<TariAddress, String> = address.parse().map_err(|e| format!("{:?}", e));
match wallet_address {
Ok(val) => {
if val.network() == network {
return Ok(val);
} else {
println!(
" Error - wallet payment address '{}' does not match miner network '{}'",
address, network
);
}
},
Err(e) => println!(" Error - wallet payment address '{}' not valid ({})", address, e),
}
}
}
if address.network() != network {
return Err(ParseInputError::WalletPaymentAddress(format!(
"Wallet payment address '{}' does not match miner network '{}'",
config_wallet_payment_address, network
)));
}
Ok(address)
},
Err(err) => Err(ParseInputError::WalletPaymentAddress(format!(
"Wallet payment address '{}' not valid ({})",
config_wallet_payment_address, err
))),
};
}

/// User requested quit
pub fn process_quit(command: &str) {
if command.to_uppercase() == "QUIT" || command.to_uppercase() == "EXIT" {
println!("\nUser requested quit (Press 'Enter')");
wait_for_keypress();
std::process::exit(0);
}
}

/// Wait for a keypress before continuing
pub fn wait_for_keypress() {
use std::io::{stdin, Read};
let mut stdin = stdin();
let buf: &mut [u8] = &mut [0; 2];
let _unused = stdin.read(buf).expect("Error reading keypress");
}

/// Base node gRPC client
pub type BaseNodeGrpcClient = BaseNodeClient<InterceptedService<Channel, ClientAuthenticationInterceptor>>;

/// Verify that the base node is responding to the mining gRPC requests
pub async fn verify_base_node_grpc_mining_responses(
node_conn: &mut BaseNodeGrpcClient,
pow_algo_request: NewBlockTemplateRequest,
) -> Result<(), String> {
let get_new_block_template = node_conn.get_new_block_template(pow_algo_request).await;
if let Err(e) = get_new_block_template {
if e.code() == Code::PermissionDenied {
return Err("'get_new_block_template'".to_string());
}
};
let get_tip_info = node_conn.get_tip_info(minotari_app_grpc::tari_rpc::Empty {}).await;
if let Err(e) = get_tip_info {
if e.code() == Code::PermissionDenied {
return Err("'get_tip_info'".to_string());
}
}
let block_result = node_conn.get_new_block(NewBlockTemplate::default()).await;
if let Err(e) = block_result {
if e.code() == Code::PermissionDenied {
return Err("'get_new_block'".to_string());
}
}
if let Err(e) = node_conn.submit_block(Block::default()).await {
if e.code() == Code::PermissionDenied {
return Err("'submit_block'".to_string());
}
}
Ok(())
}
2 changes: 1 addition & 1 deletion applications/minotari_merge_mining_proxy/log4rs_sample.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ appenders:
pattern: "{d(%H:%M)} {h({l}):5} {m}{n}"
filters:
- kind: threshold
level: warn
level: info

# An appender named "proxy" that writes to a file with a custom pattern encoder
proxy:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! Methods for seting up a new block.
use std::{cmp, convert::TryFrom, str::FromStr, sync::Arc};
use std::{cmp, convert::TryFrom, sync::Arc};

use log::*;
use minotari_app_grpc::{authentication::ClientAuthenticationInterceptor, tari_rpc::base_node_client::BaseNodeClient};
use minotari_app_utilities::parse_miner_input::BaseNodeGrpcClient;
use minotari_node_grpc_client::grpc;
use tari_common_types::{tari_address::TariAddress, types::FixedHash};
use tari_core::{
Expand All @@ -36,7 +36,6 @@ use tari_core::{
transaction_components::{TransactionKernel, TransactionOutput},
},
};
use tonic::{codegen::InterceptedService, transport::Channel};

use crate::{
block_template_data::{BlockTemplateData, BlockTemplateDataBuilder},
Expand All @@ -50,21 +49,20 @@ const LOG_TARGET: &str = "minotari_mm_proxy::proxy::block_template_protocol";
/// Structure holding grpc connections.
pub struct BlockTemplateProtocol<'a> {
config: Arc<MergeMiningProxyConfig>,
base_node_client: &'a mut BaseNodeClient<InterceptedService<Channel, ClientAuthenticationInterceptor>>,
base_node_client: &'a mut BaseNodeGrpcClient,
key_manager: MemoryDbKeyManager,
wallet_payment_address: TariAddress,
consensus_manager: ConsensusManager,
}

impl<'a> BlockTemplateProtocol<'a> {
pub async fn new(
base_node_client: &'a mut BaseNodeClient<InterceptedService<Channel, ClientAuthenticationInterceptor>>,
base_node_client: &'a mut BaseNodeGrpcClient,
config: Arc<MergeMiningProxyConfig>,
consensus_manager: ConsensusManager,
wallet_payment_address: TariAddress,
) -> Result<BlockTemplateProtocol<'a>, MmProxyError> {
let key_manager = create_memory_db_key_manager();
let wallet_payment_address = TariAddress::from_str(&config.wallet_payment_address)
.map_err(|err| MmProxyError::WalletPaymentAddress(err.to_string()))?;
Ok(Self {
config,
base_node_client,
Expand Down
7 changes: 5 additions & 2 deletions applications/minotari_merge_mining_proxy/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use std::io;

use hex::FromHexError;
use hyper::header::InvalidHeaderValue;
use minotari_app_utilities::parse_miner_input::ParseInputError;
use minotari_wallet_grpc_client::BasicAuthError;
use tari_common::{ConfigError, ConfigurationError};
use tari_core::{
Expand Down Expand Up @@ -106,8 +107,10 @@ pub enum MmProxyError {
CoreKeyManagerError(#[from] CoreKeyManagerError),
#[error("Consensus build error: {0}")]
ConsensusBuilderError(#[from] ConsensusBuilderError),
#[error("Could not convert data:{0}")]
WalletPaymentAddress(String),
#[error("Consensus build error: {0}")]
ParseInputError(#[from] ParseInputError),
#[error("Base node not responding to gRPC requests: {0}")]
BaseNodeNotResponding(String),
}

impl From<tonic::Status> for MmProxyError {
Expand Down
11 changes: 10 additions & 1 deletion applications/minotari_merge_mining_proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ use std::io::stdout;

use clap::Parser;
use crossterm::{execute, terminal::SetTitle};
use log::*;
use minotari_app_utilities::consts;
use tari_common::initialize_logging;

const LOG_TARGET: &str = "minotari_mm_proxy::proxy";

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let terminal_title = format!("Minotari Merge Mining Proxy - Version {}", consts::APP_VERSION);
Expand All @@ -55,5 +58,11 @@ async fn main() -> Result<(), anyhow::Error> {
&cli.common.get_base_path(),
include_str!("../log4rs_sample.yml"),
)?;
run_merge_miner::start_merge_miner(cli).await
match run_merge_miner::start_merge_miner(cli).await {
Ok(_) => Ok(()),
Err(err) => {
error!(target: LOG_TARGET, "Fatal error: {:?}", err);
Err(err)
},
}
}
Loading

0 comments on commit 26f5b60

Please sign in to comment.