forked from elichai/kaspa-miner
-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.rs
167 lines (150 loc) · 5.62 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#![cfg_attr(all(test, feature = "bench"), feature(test))]
use std::env::consts::DLL_EXTENSION;
use std::env::current_exe;
use std::error::Error as StdError;
use std::ffi::OsStr;
use clap::{App, FromArgMatches, IntoApp};
use kaspa_miner::PluginManager;
use log::{error, info};
use rand::{thread_rng, RngCore};
use std::fs;
use std::sync::atomic::AtomicU16;
use std::sync::Arc;
use std::thread::sleep;
use std::time::Duration;
use crate::cli::Opt;
use crate::client::grpc::KaspadHandler;
use crate::client::stratum::StratumHandler;
use crate::client::Client;
use crate::miner::MinerManager;
use crate::target::Uint256;
mod cli;
mod client;
mod kaspad_messages;
mod miner;
mod pow;
mod target;
mod watch;
const WHITELIST: [&str; 4] = ["libkaspacuda", "libkaspaopencl", "kaspacuda", "kaspaopencl"];
pub mod proto {
#![allow(clippy::derive_partial_eq_without_eq)]
tonic::include_proto!("protowire");
// include!("protowire.rs"); // FIXME: https://github.com/intellij-rust/intellij-rust/issues/6579
}
pub type Error = Box<dyn StdError Send Sync 'static>;
type Hash = Uint256;
#[cfg(target_os = "windows")]
fn adjust_console() -> Result<(), Error> {
let console = win32console::console::WinConsole::input();
let mut mode = console.get_mode()?;
mode = (mode & !win32console::console::ConsoleMode::ENABLE_QUICK_EDIT_MODE)
| win32console::console::ConsoleMode::ENABLE_EXTENDED_FLAGS;
console.set_mode(mode)?;
Ok(())
}
fn filter_plugins(dirname: &str) -> Vec<String> {
match fs::read_dir(dirname) {
Ok(readdir) => readdir
.map(|entry| entry.unwrap().path())
.filter(|fname| {
fname.is_file()
&& fname.extension().is_some()
&& fname.extension().and_then(OsStr::to_str).unwrap_or_default().starts_with(DLL_EXTENSION)
})
.filter(|fname| WHITELIST.iter().any(|lib| *lib == fname.file_stem().and_then(OsStr::to_str).unwrap()))
.map(|path| path.to_str().unwrap().to_string())
.collect::<Vec<String>>(),
_ => Vec::<String>::new(),
}
}
async fn get_client(
kaspad_address: String,
mining_address: String,
mine_when_not_synced: bool,
block_template_ctr: Arc<AtomicU16>,
) -> Result<Box<dyn Client 'static>, Error> {
if kaspad_address.starts_with("stratum tcp://") {
let (_schema, address) = kaspad_address.split_once("://").unwrap();
Ok(StratumHandler::connect(
address.to_string().clone(),
mining_address.clone(),
mine_when_not_synced,
Some(block_template_ctr.clone()),
)
.await?)
} else if kaspad_address.starts_with("grpc://") {
Ok(KaspadHandler::connect(
kaspad_address.clone(),
mining_address.clone(),
mine_when_not_synced,
Some(block_template_ctr.clone()),
)
.await?)
} else {
Err("Did not recognize pool/grpc address schema".into())
}
}
async fn client_main(
opt: &Opt,
block_template_ctr: Arc<AtomicU16>,
plugin_manager: &PluginManager,
) -> Result<(), Error> {
let mut client = get_client(
opt.kaspad_address.clone(),
opt.mining_address.clone(),
opt.mine_when_not_synced,
block_template_ctr.clone(),
)
.await?;
if opt.devfund_percent > 0 {
client.add_devfund(opt.devfund_address.clone(), opt.devfund_percent);
}
client.register().await?;
let mut miner_manager = MinerManager::new(client.get_block_channel(), opt.num_threads, plugin_manager);
client.listen(&mut miner_manager).await?;
drop(miner_manager);
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Error> {
#[cfg(target_os = "windows")]
adjust_console().unwrap_or_else(|e| {
eprintln!("WARNING: Failed to protect console ({}). Any selection in console will freeze the miner.", e)
});
let mut path = current_exe().unwrap_or_default();
path.pop(); // Getting the parent directory
let plugins = filter_plugins(path.to_str().unwrap_or("."));
let (app, mut plugin_manager): (App, PluginManager) = kaspa_miner::load_plugins(Opt::into_app(), &plugins)?;
let matches = app.get_matches();
let worker_count = plugin_manager.process_options(&matches)?;
let mut opt: Opt = Opt::from_arg_matches(&matches)?;
opt.process()?;
env_logger::builder().filter_level(opt.log_level()).parse_default_env().init();
info!("=================================================================================");
info!(" Kaspa-Miner GPU {}", env!("CARGO_PKG_VERSION"));
info!(" Mining for: {}", opt.mining_address);
info!("=================================================================================");
info!("Found plugins: {:?}", plugins);
info!("Plugins found {} workers", worker_count);
if worker_count == 0 && opt.num_threads.unwrap_or(0) == 0 {
error!("No workers specified");
return Err("No workers specified".into());
}
let block_template_ctr = Arc::new(AtomicU16::new((thread_rng().next_u64() % 10_000u64) as u16));
if opt.devfund_percent > 0 {
info!(
"devfund enabled, mining {}.{}% of the time to devfund address: {} ",
opt.devfund_percent / 100,
opt.devfund_percent % 100,
opt.devfund_address
);
}
loop {
match client_main(&opt, block_template_ctr.clone(), &plugin_manager).await {
Ok(_) => info!("Client closed gracefully"),
Err(e) => error!("Client closed with error {:?}", e),
}
info!("Client closed, reconnecting");
sleep(Duration::from_millis(100));
}
}