- #1 Update must not rewrite the bootloader: start_install refuses a tier-3 (bootloader-writing) .afw when the dialog is an in-place Update, enforcing the "BOOT.bin is never written" guarantee. - #2 post-install verify could stick forever when auto-scan is off: tick() now re-probes awaiting boards on a fixed 10 s cadence until they answer as alkane or the give-up window expires. - #3 board-health no longer greys a genuinely-mining miner whose backend omits per-board active/working_chips: (None,None) reads green when the miner is hashing, grey only when idle (the bare S17 case). - #5 install docs/comments no longer describe the removed typed-FLASH step. - #6 the flash-plan checklist verifies against the install target board, so a file for another board surfaces as an error instead of a misleading plan. - #7 install board is taken from the selected row's board_family, not a fixed default (correct once more boards are supported). - #4 (verify on the UI thread) accepted: .afw bundles are ~7 MB, so the manifest read is a sub-100 ms hash, not a user-visible freeze. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2715 lines
107 KiB
Rust
2715 lines
107 KiB
Rust
//! Scan engine: drives vendored asic-rs over the configured subnets and
|
|
//! streams MinerRow snapshots to the UI thread via a std channel.
|
|
|
|
use crate::model::{MinerCaps, MinerRow};
|
|
use asic_rs::core::data::firmware::FirmwareImage;
|
|
use asic_rs::core::traits::miner::Miner;
|
|
use futures_util::{FutureExt, StreamExt};
|
|
use measurements::Power;
|
|
use std::collections::HashSet;
|
|
use std::net::Ipv4Addr;
|
|
use std::path::PathBuf;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::sync::mpsc::{channel, Receiver};
|
|
use std::sync::Arc;
|
|
|
|
// `Row` is the common variant (one per miner) while `Started`/`Done` are sent
|
|
// once each, so boxing the large row to shrink the rare variants would add an
|
|
// allocation on the hot path for no real gain -- the message is moved straight
|
|
// through an mpsc channel and dropped.
|
|
#[allow(clippy::large_enum_variant)]
|
|
pub enum ScanMsg {
|
|
/// A new scan started: `total` addresses to probe, and the exact set of
|
|
/// target IPs (as strings) so the UI can drop miners no longer in range.
|
|
Started {
|
|
total: usize,
|
|
targets: HashSet<String>,
|
|
},
|
|
/// Progress update: `done` of `total` addresses probed; `ip` is the most
|
|
/// recently probed address (activity indicator).
|
|
Progress {
|
|
done: usize,
|
|
total: usize,
|
|
ip: String,
|
|
},
|
|
/// A miner was identified.
|
|
Row(MinerRow),
|
|
/// The scan finished (label is informational).
|
|
Done(String),
|
|
/// The scan could not run.
|
|
Failed(String),
|
|
}
|
|
|
|
pub const RANGES_FILE: &str = "scan-ranges.txt";
|
|
pub const AUTO_FILE: &str = "auto-rescan-secs.txt";
|
|
pub const SCAN_TIMEOUT_FILE: &str = "scan-timeout-secs.txt";
|
|
/// Default per-miner scan timeout (matches asic-rs' identification timeout).
|
|
pub const DEFAULT_SCAN_TIMEOUT_SECS: u64 = 10;
|
|
/// Default in-flight address probes during a scan. asic-rs would otherwise use
|
|
/// 1000 for any range up to /22, saturating a real link and starving the
|
|
/// per-responder get_data (Braiins miners drop most values under that burst).
|
|
/// 128 was the highest cap that stayed fully reliable on the live fleet; it is
|
|
/// now the default of a user-adjustable setting (round 19 #25).
|
|
pub const SCAN_CONCURRENCY_LIMIT: usize = 128;
|
|
/// The user-configurable scan concurrency is clamped to this range: a floor so a
|
|
/// scan is never effectively serial, and a ceiling so a large range can't open
|
|
/// hundreds of connections and saturate the network (round 19 #25). Higher
|
|
/// values scan faster but can starve per-responder telemetry (see above).
|
|
pub const MIN_SCAN_CONCURRENCY: usize = 8;
|
|
// Ceiling kept at 256: the code below documents that 128 is fully reliable and 192
|
|
// already dropped responders, and identification + telemetry run concurrently so
|
|
// the peak socket count is ~2x this. 256 gives headroom for a fast sweep without
|
|
// inviting the mass value-drops (which read as phantom faults) that higher caps
|
|
// caused on the live fleet (round 19 review).
|
|
pub const MAX_SCAN_CONCURRENCY: usize = 256;
|
|
pub const SCAN_CONCURRENCY_FILE: &str = "scan-concurrency.txt";
|
|
|
|
/// Load the saved scan concurrency (in-flight probes), clamped to
|
|
/// [MIN_SCAN_CONCURRENCY, MAX_SCAN_CONCURRENCY].
|
|
pub fn load_scan_concurrency() -> usize {
|
|
std::fs::read_to_string(config_path(SCAN_CONCURRENCY_FILE))
|
|
.ok()
|
|
.and_then(|s| s.trim().parse::<usize>().ok())
|
|
.map(|n| n.clamp(MIN_SCAN_CONCURRENCY, MAX_SCAN_CONCURRENCY))
|
|
.unwrap_or(SCAN_CONCURRENCY_LIMIT)
|
|
}
|
|
|
|
/// Save the scan concurrency, clamped to the allowed range.
|
|
pub fn save_scan_concurrency(n: usize) -> std::io::Result<()> {
|
|
let p = config_path(SCAN_CONCURRENCY_FILE);
|
|
if let Some(dir) = p.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
std::fs::write(
|
|
p,
|
|
n.clamp(MIN_SCAN_CONCURRENCY, MAX_SCAN_CONCURRENCY)
|
|
.to_string(),
|
|
)
|
|
}
|
|
/// The usual home/site router subnet. Host bits are masked off, so this scans
|
|
/// 192.168.1.0/24.
|
|
pub const DEFAULT_RANGE: &str = "192.168.1.1/24";
|
|
/// Default seconds between automatic rescans.
|
|
pub const DEFAULT_AUTO_SECS: u64 = 300;
|
|
|
|
/// Load the auto-rescan interval in seconds (0 = disabled).
|
|
pub fn load_auto_secs() -> u64 {
|
|
std::fs::read_to_string(config_path(AUTO_FILE))
|
|
.ok()
|
|
.and_then(|s| s.trim().parse().ok())
|
|
.unwrap_or(DEFAULT_AUTO_SECS)
|
|
}
|
|
|
|
/// Save the auto-rescan interval in seconds.
|
|
pub fn save_auto_secs(secs: u64) -> std::io::Result<()> {
|
|
let p = config_path(AUTO_FILE);
|
|
if let Some(dir) = p.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
std::fs::write(p, secs.to_string())
|
|
}
|
|
|
|
/// Load the per-miner scan timeout in seconds (round 14 #2), clamped to at least
|
|
/// 1s. This is asic-rs' identification timeout: how long a responding miner is
|
|
/// given to identify + return data before the scan gives up on it.
|
|
pub fn load_scan_timeout() -> u64 {
|
|
std::fs::read_to_string(config_path(SCAN_TIMEOUT_FILE))
|
|
.ok()
|
|
.and_then(|s| s.trim().parse::<u64>().ok())
|
|
.map(|s| s.max(1))
|
|
.unwrap_or(DEFAULT_SCAN_TIMEOUT_SECS)
|
|
}
|
|
|
|
/// Save the per-miner scan timeout in seconds.
|
|
pub fn save_scan_timeout(secs: u64) -> std::io::Result<()> {
|
|
let p = config_path(SCAN_TIMEOUT_FILE);
|
|
if let Some(dir) = p.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
std::fs::write(p, secs.max(1).to_string())
|
|
}
|
|
|
|
/// `file` inside the per-user settings directory (`~/.config/alkane-toolkit`,
|
|
/// or `%APPDATA%\alkane-toolkit` on Windows; see `alkane_core::platform`).
|
|
pub fn config_path(file: &str) -> PathBuf {
|
|
alkane_core::platform::config_path(file)
|
|
}
|
|
|
|
pub fn load_ranges() -> Vec<String> {
|
|
let p = config_path(RANGES_FILE);
|
|
if let Ok(s) = std::fs::read_to_string(&p) {
|
|
let v: Vec<String> = s
|
|
.lines()
|
|
.map(|l| l.trim().to_string())
|
|
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
|
.collect();
|
|
if !v.is_empty() {
|
|
return v;
|
|
}
|
|
}
|
|
vec![DEFAULT_RANGE.to_string()]
|
|
}
|
|
|
|
pub fn save_ranges(ranges: &[String]) -> std::io::Result<()> {
|
|
let p = config_path(RANGES_FILE);
|
|
if let Some(dir) = p.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
std::fs::write(p, ranges.join("\n") + "\n")
|
|
}
|
|
|
|
/// Parse "a.b.c.d/p" (also accepts a bare address as /32).
|
|
pub fn parse_cidr(s: &str) -> Option<(Ipv4Addr, u8)> {
|
|
let s = s.trim();
|
|
match s.split_once('/') {
|
|
Some((addr, prefix)) => {
|
|
let addr: Ipv4Addr = addr.parse().ok()?;
|
|
let prefix: u8 = prefix.parse().ok()?;
|
|
if prefix > 32 {
|
|
return None;
|
|
}
|
|
Some((addr, prefix))
|
|
}
|
|
None => Some((s.parse().ok()?, 32)),
|
|
}
|
|
}
|
|
|
|
/// Upper bound on how many addresses a single line (or the whole target set)
|
|
/// may expand to, so a stray `10.0.0.0/8` can't allocate gigabytes / freeze the
|
|
/// app. A million addresses is already far more than any real miner LAN.
|
|
pub const MAX_ADDRS: u64 = 1_000_000;
|
|
|
|
/// Parse one scan-range line into its address list. Accepts:
|
|
/// - CIDR: `10.253.1.0/24`
|
|
/// - single IP: `10.253.1.5`
|
|
/// - full range: `10.253.1.3-10.253.1.234` (inclusive)
|
|
/// - short range: `10.253.1.3-234` (end = same /24, last octet)
|
|
pub fn parse_line(line: &str) -> Result<Vec<Ipv4Addr>, String> {
|
|
let line = line.trim();
|
|
if line.is_empty() {
|
|
return Ok(Vec::new());
|
|
}
|
|
if let Some((_a, _p)) = line.split_once('/') {
|
|
let (addr, prefix) = parse_cidr(line).ok_or_else(|| format!("bad CIDR: {line}"))?;
|
|
let base = u32::from(addr) & prefix_mask(prefix);
|
|
let count = 1u64 << (32 - prefix as u32);
|
|
if count > MAX_ADDRS {
|
|
return Err(format!("CIDR too large (> {MAX_ADDRS} addresses): {line}"));
|
|
}
|
|
return Ok((0..count)
|
|
.map(|i| Ipv4Addr::from(base + i as u32))
|
|
.collect());
|
|
}
|
|
// Per-octet ranges: each of the four octets may be a single number or an
|
|
// inclusive `a-b` range, e.g. "10.1-9.1.1-255" scans the cartesian product
|
|
// (the 9 /24s: 10.1.1.x .. 10.9.1.x). This also subsumes a plain single
|
|
// address and a bare last-octet range like "10.253.1.3-234".
|
|
let parts: Vec<&str> = line.split('.').collect();
|
|
if parts.len() == 4 && parts.iter().all(|p| is_octet_spec(p)) {
|
|
let r: Vec<(u8, u8)> = parts
|
|
.iter()
|
|
.map(|p| parse_octet_spec(p))
|
|
.collect::<Result<_, String>>()?;
|
|
let count: u64 = r
|
|
.iter()
|
|
.map(|(lo, hi)| *hi as u64 - *lo as u64 + 1)
|
|
.product();
|
|
if count > MAX_ADDRS {
|
|
return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}"));
|
|
}
|
|
let mut out = Vec::with_capacity(count as usize);
|
|
for a in r[0].0..=r[0].1 {
|
|
for b in r[1].0..=r[1].1 {
|
|
for c in r[2].0..=r[2].1 {
|
|
for d in r[3].0..=r[3].1 {
|
|
out.push(Ipv4Addr::new(a, b, c, d));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return Ok(out);
|
|
}
|
|
// Full A-B range across two dotted addresses (e.g. "10.0.0.1-10.7.255.254"),
|
|
// which the per-octet form above cannot express.
|
|
if let Some((start_s, end_s)) = line.split_once('-') {
|
|
let start: Ipv4Addr = start_s
|
|
.trim()
|
|
.parse()
|
|
.map_err(|_| format!("bad start address: {start_s}"))?;
|
|
let end_s = end_s.trim();
|
|
// full end address, or a bare last-octet sharing the start's /24
|
|
let end: Ipv4Addr = if end_s.contains('.') {
|
|
end_s
|
|
.parse()
|
|
.map_err(|_| format!("bad end address: {end_s}"))?
|
|
} else {
|
|
let o: u8 = end_s
|
|
.parse()
|
|
.map_err(|_| format!("bad range end: {end_s}"))?;
|
|
let s = start.octets();
|
|
Ipv4Addr::new(s[0], s[1], s[2], o)
|
|
};
|
|
let (s, e) = (u32::from(start), u32::from(end));
|
|
if s > e {
|
|
return Err(format!("range start after end: {line}"));
|
|
}
|
|
if (e - s) as u64 >= MAX_ADDRS {
|
|
return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}"));
|
|
}
|
|
return Ok((s..=e).map(Ipv4Addr::from).collect());
|
|
}
|
|
// single address
|
|
let addr: Ipv4Addr = line.parse().map_err(|_| format!("bad address: {line}"))?;
|
|
Ok(vec![addr])
|
|
}
|
|
|
|
/// Parse one octet spec: `"n"` -> `(n, n)`, or `"a-b"` -> `(a, b)` inclusive
|
|
/// (rejecting `a > b`). Used by the per-octet range form in `parse_line`.
|
|
fn parse_octet_spec(s: &str) -> Result<(u8, u8), String> {
|
|
let s = s.trim();
|
|
if let Some((lo, hi)) = s.split_once('-') {
|
|
let lo: u8 = lo
|
|
.trim()
|
|
.parse()
|
|
.map_err(|_| format!("bad octet range: {s}"))?;
|
|
let hi: u8 = hi
|
|
.trim()
|
|
.parse()
|
|
.map_err(|_| format!("bad octet range: {s}"))?;
|
|
if lo > hi {
|
|
return Err(format!("octet range start after end: {s}"));
|
|
}
|
|
Ok((lo, hi))
|
|
} else {
|
|
let n: u8 = s.parse().map_err(|_| format!("bad octet: {s}"))?;
|
|
Ok((n, n))
|
|
}
|
|
}
|
|
|
|
fn is_octet_spec(s: &str) -> bool {
|
|
parse_octet_spec(s).is_ok()
|
|
}
|
|
|
|
fn prefix_mask(prefix: u8) -> u32 {
|
|
if prefix == 0 {
|
|
0
|
|
} else {
|
|
u32::MAX << (32 - prefix as u32)
|
|
}
|
|
}
|
|
|
|
/// Parse and de-duplicate all scan-range lines into a sorted target list.
|
|
pub fn parse_targets(lines: &[String]) -> Result<Vec<Ipv4Addr>, String> {
|
|
let mut set = std::collections::BTreeSet::new();
|
|
for line in lines {
|
|
for ip in parse_line(line)? {
|
|
set.insert(u32::from(ip));
|
|
}
|
|
if set.len() as u64 > MAX_ADDRS {
|
|
return Err(format!("too many addresses across ranges (> {MAX_ADDRS})"));
|
|
}
|
|
}
|
|
Ok(set.into_iter().map(Ipv4Addr::from).collect())
|
|
}
|
|
|
|
/// Validate scan-range lines; returns an error message if any line is bad or
|
|
/// the set is empty.
|
|
pub fn validate_ranges(lines: &[String]) -> Result<(), String> {
|
|
let ips = parse_targets(lines)?;
|
|
if ips.is_empty() {
|
|
return Err("no addresses in the given ranges".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Aggregate a sorted, de-duplicated address list into the minimal set of CIDR
|
|
/// blocks that cover exactly those addresses (used to load the asic-rs factory).
|
|
fn targets_to_cidrs(ips: &[Ipv4Addr]) -> Vec<(Ipv4Addr, u8)> {
|
|
let mut out = Vec::new();
|
|
let vals: Vec<u32> = ips.iter().map(|ip| u32::from(*ip)).collect();
|
|
let mut i = 0usize;
|
|
while i < vals.len() {
|
|
// extend a contiguous run [start, end]
|
|
let start = vals[i];
|
|
let mut end = start;
|
|
while i + 1 < vals.len() && vals[i + 1] == end + 1 {
|
|
end = vals[i + 1];
|
|
i += 1;
|
|
}
|
|
out.extend(range_to_cidrs(start, end));
|
|
i += 1;
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Cover the inclusive [start, end] u32 range with aligned CIDR blocks.
|
|
fn range_to_cidrs(start: u32, end: u32) -> Vec<(Ipv4Addr, u8)> {
|
|
let mut cidrs = Vec::new();
|
|
let mut cur = start as u64;
|
|
let end = end as u64;
|
|
while cur <= end {
|
|
let align = if cur == 0 {
|
|
32
|
|
} else {
|
|
(cur as u32).trailing_zeros()
|
|
};
|
|
let mut bits = align.min(32);
|
|
let remaining = end - cur + 1;
|
|
while bits > 0 && (1u64 << bits) > remaining {
|
|
bits -= 1;
|
|
}
|
|
cidrs.push((Ipv4Addr::from(cur as u32), (32 - bits) as u8));
|
|
cur += 1u64 << bits;
|
|
}
|
|
cidrs
|
|
}
|
|
|
|
/// Env var that swaps the live network scan for the built-in bench-fleet
|
|
/// fixtures. Set it to render/test the UI offline and deterministically.
|
|
pub const FAKE_SCAN_ENV: &str = "ALKANE_FAKE_SCAN";
|
|
|
|
/// True when the app should feed fixtures instead of scanning the network.
|
|
pub fn fake_scan_enabled() -> bool {
|
|
std::env::var_os(FAKE_SCAN_ENV).is_some()
|
|
}
|
|
|
|
/// Spawn the scan thread. It parses the range lines into an exact target set,
|
|
/// tells the UI which addresses are in range (so out-of-range miners can be
|
|
/// dropped), then streams identified miners plus progress updates. In fake-scan
|
|
/// mode it streams the bench-fleet fixtures instead, needing no network.
|
|
///
|
|
/// The returned [`ScanHandle`] carries the message stream plus a cancel flag the
|
|
/// background thread checks each iteration, so Stop / re-scan can end a scan
|
|
/// promptly instead of leaving a thread probing dead hosts (each probe waits out
|
|
/// an asic-rs per-host timeout).
|
|
pub struct ScanHandle {
|
|
pub rx: Receiver<ScanMsg>,
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl ScanHandle {
|
|
/// Signal the scan thread to stop at its next loop iteration. Idempotent;
|
|
/// dropping the handle's `rx` alone does NOT stop the thread.
|
|
pub fn stop(&self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
|
|
if fake_scan_enabled() {
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-scan".into())
|
|
.spawn(move || {
|
|
let rows = crate::fixtures::bench_fleet();
|
|
let targets: HashSet<String> = rows.iter().map(|r| r.ip.clone()).collect();
|
|
let total = rows.len();
|
|
let _ = tx.send(ScanMsg::Started { total, targets });
|
|
for (i, row) in rows.into_iter().enumerate() {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
return;
|
|
}
|
|
if tx.send(ScanMsg::Row(row)).is_err() {
|
|
return;
|
|
}
|
|
let _ = tx.send(ScanMsg::Progress {
|
|
done: i + 1,
|
|
total,
|
|
ip: String::new(),
|
|
});
|
|
}
|
|
let _ = tx.send(ScanMsg::Done("fixtures".into()));
|
|
});
|
|
if let Err(e) = res {
|
|
let _ = err_tx.send(ScanMsg::Failed(format!("spawn fake-scan thread: {e}")));
|
|
}
|
|
return ScanHandle { rx, cancel };
|
|
}
|
|
|
|
// Resolve the target addresses up front so we can report total + membership.
|
|
let targets = match parse_targets(&lines) {
|
|
Ok(t) if !t.is_empty() => t,
|
|
Ok(_) => {
|
|
let _ = tx.send(ScanMsg::Failed("no addresses in the given ranges".into()));
|
|
return ScanHandle { rx, cancel };
|
|
}
|
|
Err(e) => {
|
|
let _ = tx.send(ScanMsg::Failed(e));
|
|
return ScanHandle { rx, cancel };
|
|
}
|
|
};
|
|
let total = targets.len();
|
|
let target_set: HashSet<String> = targets.iter().map(|ip| ip.to_string()).collect();
|
|
let _ = tx.send(ScanMsg::Started {
|
|
total,
|
|
targets: target_set,
|
|
});
|
|
let cidrs = targets_to_cidrs(&targets);
|
|
// User-adjustable in-flight probe cap (round 19 #25).
|
|
let concurrency = load_scan_concurrency();
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("asic-rs-scan".into())
|
|
.spawn(move || {
|
|
let rt = match tokio::runtime::Runtime::new() {
|
|
Ok(rt) => rt,
|
|
Err(e) => {
|
|
let _ = tx.send(ScanMsg::Failed(format!("tokio runtime: {e}")));
|
|
return;
|
|
}
|
|
};
|
|
rt.block_on(async move {
|
|
let mut factory = crate::credentials::configured_factory()
|
|
.with_identification_timeout_secs(timeout_secs.max(1))
|
|
// Cap identification concurrency. asic-rs defaults to 1000 for any
|
|
// range up to /22, so a /24 fires all 254 probes at once. Over a
|
|
// real link (VPN, or a subnet full of dead IPs whose TCP connects
|
|
// sit open for the whole identification timeout) that burst starves
|
|
// the per-responder get_data -- a Braiins miner fans out ~12
|
|
// authenticated REST calls and drops most of its values (watts=0,
|
|
// no best-share/temps), and some responders are missed entirely.
|
|
// 128 is the highest cap that stayed fully reliable on the live
|
|
// fleet (192 already dropped responders); a /24 still finishes in
|
|
// ~35s. Larger ranges just take proportionally longer, still correct.
|
|
// The cap is now user-adjustable (round 19 #25); the default is 128.
|
|
.with_concurrent_limit(concurrency);
|
|
for (ip, prefix) in &cidrs {
|
|
factory = match factory.with_subnet(&format!("{ip}/{prefix}")) {
|
|
Ok(f) => f,
|
|
Err(e) => {
|
|
let _ = tx.send(ScanMsg::Failed(format!("{ip}/{prefix}: {e}")));
|
|
return;
|
|
}
|
|
};
|
|
}
|
|
// scan_stream_with_ip yields one item per probed address (identification
|
|
// is already concurrent up to SCAN_CONCURRENCY_LIMIT). Each responder's
|
|
// telemetry (to_row -> get_data + presets: several REST calls) is then
|
|
// run concurrently via buffer_unordered instead of awaited one at a time
|
|
// -- otherwise the telemetry serialises and dominates the scan wall-clock
|
|
// (round 18 #12). buffer_unordered polls the underlying stream on its own,
|
|
// so identification concurrency is unaffected, and telemetry only ever
|
|
// targets responders (live miners), so the same cap is safe.
|
|
let mut done = 0usize;
|
|
// Emit progress per address for a smoothly-climbing counter; only a
|
|
// very large scan (> 5000 addresses) is throttled, to bound channel
|
|
// traffic. The UI coalesces these to one gauge update per refresh.
|
|
let step = (total / 5000).max(1);
|
|
let ptx = tx.clone();
|
|
let mut results = factory
|
|
.scan_stream_with_ip()
|
|
.map(|(ip, miner)| {
|
|
let ptx = ptx.clone();
|
|
async move {
|
|
match miner {
|
|
// Only surface a row for an address that actually has a
|
|
// miner behind it; a non-responding address is never a
|
|
// phantom row.
|
|
Some(m) => {
|
|
// Fast path (round 19 #18): emit a lightweight identity
|
|
// row from identification alone the instant the miner
|
|
// is found, so it shows immediately; the full telemetry
|
|
// row (get_data) upserts over it when it completes. The
|
|
// ordering holds because the partial is sent before this
|
|
// future awaits get_data and returns the full row.
|
|
let _ = ptx.send(ScanMsg::Row(partial_row(&*m, ip)));
|
|
// Isolate one miner's telemetry: asic-rs backends
|
|
// parse miner-controlled data, so a panic (a stray
|
|
// unwrap/index on a malformed field) must not unwind
|
|
// the whole sweep and abort every other miner (round
|
|
// 19 review). On panic the miner keeps its partial
|
|
// identity row and the scan continues.
|
|
let row = std::panic::AssertUnwindSafe(to_row(&*m))
|
|
.catch_unwind()
|
|
.await
|
|
.ok();
|
|
(ip, row)
|
|
}
|
|
// asic-rs does not recognise a board running Alkane
|
|
// OS (no cgminer socket or vendor web UI exposed);
|
|
// the toolkit's own probe finds it.
|
|
None => (ip, crate::alkane_detect::detect(ip).await),
|
|
}
|
|
}
|
|
})
|
|
.buffer_unordered(concurrency);
|
|
while let Some((ip, row)) = results.next().await {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
return; // Stop / re-scan requested
|
|
}
|
|
done += 1;
|
|
if let Some(row) = row {
|
|
if tx.send(ScanMsg::Row(row)).is_err() {
|
|
return; // UI gone
|
|
}
|
|
}
|
|
if done.is_multiple_of(step) || done == total {
|
|
let _ = tx.send(ScanMsg::Progress {
|
|
done,
|
|
total,
|
|
ip: ip.to_string(),
|
|
});
|
|
}
|
|
}
|
|
let _ = tx.send(ScanMsg::Done(format!("{total} addresses")));
|
|
});
|
|
});
|
|
if let Err(e) = res {
|
|
let _ = err_tx.send(ScanMsg::Failed(format!("spawn scan thread: {e}")));
|
|
}
|
|
ScanHandle { rx, cancel }
|
|
}
|
|
|
|
/// Flatten a miner's structured messages into concise display lines for the
|
|
/// Errors column's hover tooltip (the column cell itself shows only the count).
|
|
/// Only actionable messages (Error + Warning) are kept -- Info is dropped as
|
|
/// noise. Each line is just "message (component)" (no repetitive "[Error]"
|
|
/// prefix), duplicates are collapsed, and errors sort before warnings.
|
|
fn summarize_messages(messages: &[asic_rs::core::data::message::MinerMessage]) -> Vec<String> {
|
|
use asic_rs::core::data::message::MessageSeverity;
|
|
let mut ranked: Vec<(u8, String)> = messages
|
|
.iter()
|
|
.filter_map(|m| {
|
|
let rank = match m.severity {
|
|
MessageSeverity::Error => 0u8,
|
|
MessageSeverity::Warning => 1,
|
|
MessageSeverity::Info => return None, // informational, not an error/warning
|
|
};
|
|
let text = m.message.trim();
|
|
if text.is_empty() {
|
|
return None;
|
|
}
|
|
let line = match m.component.as_ref().map(|c| c.to_string()) {
|
|
Some(c) if !c.trim().is_empty() => format!("{text} ({})", c.trim()),
|
|
_ => text.to_string(),
|
|
};
|
|
Some((rank, line))
|
|
})
|
|
.collect();
|
|
// Stable sort keeps discovery order within a severity; errors before warnings.
|
|
ranked.sort_by_key(|(r, _)| *r);
|
|
// Collapse exact duplicates (asic-rs sometimes repeats the same fault per board).
|
|
let mut seen = HashSet::new();
|
|
ranked.retain(|(_, s)| seen.insert(s.clone()));
|
|
ranked.into_iter().map(|(_, s)| s).collect()
|
|
}
|
|
|
|
/// Convert a miner's structured messages into `Fault`s with their attributed
|
|
/// component (round 16 #1/#2/#3), so the Health column can colour and describe
|
|
/// each icon from the actual per-component faults. Info-severity messages are
|
|
/// dropped; Error and Warning are kept (only Error drives colour).
|
|
/// Best-effort hashboard index from a fault message that names a board (round 18
|
|
/// #5). Only WhatsMiner's asic-rs backends attribute a message to a specific
|
|
/// `HashBoard { idx }`; every Antminer-hardware firmware (stock, VNish, Braiins,
|
|
/// LuxOS) builds messages with no component, so a real per-board fault would
|
|
/// otherwise land on the control-board (brain) tooltip instead of the board it
|
|
/// names. The message text is self-describing (e.g. "Chain 2 ... temperature"),
|
|
/// so pull the first integer after a board keyword and attribute the fault to that
|
|
/// board. Returns None when no board keyword is present.
|
|
fn board_index_from_text(text: &str) -> Option<usize> {
|
|
let lower = text.to_ascii_lowercase();
|
|
// Longest/most-specific keywords first so "hashboard" wins over "board".
|
|
for kw in ["hashboard", "hash board", "chain", "slot", "board"] {
|
|
let mut from = 0;
|
|
while let Some(rel) = lower[from..].find(kw) {
|
|
let after = &lower[from + rel + kw.len()..];
|
|
// The number must IMMEDIATELY follow the keyword (after only separators
|
|
// like " #-:._="), so "Chain 2 ..." -> 2 but "hashboard error, temp 65"
|
|
// does not grab the temperature 65 far past the keyword (round 18 #12).
|
|
let rest = after.trim_start_matches(|c: char| {
|
|
c.is_whitespace() || matches!(c, ':' | '#' | '-' | '_' | '.' | '=' | '(')
|
|
});
|
|
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
|
|
if let Ok(n) = digits.parse::<usize>() {
|
|
return Some(n);
|
|
}
|
|
from += rel + kw.len();
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn messages_to_faults(
|
|
messages: &[asic_rs::core::data::message::MinerMessage],
|
|
) -> Vec<crate::model::Fault> {
|
|
use crate::model::{Fault, FaultComponent};
|
|
use asic_rs::core::data::message::{MessageSeverity, MinerComponent};
|
|
messages
|
|
.iter()
|
|
.filter_map(|m| {
|
|
let is_error = match m.severity {
|
|
MessageSeverity::Error => true,
|
|
MessageSeverity::Warning => false,
|
|
MessageSeverity::Info => return None,
|
|
};
|
|
let text = m.message.trim();
|
|
if text.is_empty() {
|
|
return None;
|
|
}
|
|
let component = match &m.component {
|
|
Some(MinerComponent::PowerSupply { .. }) => FaultComponent::Power,
|
|
Some(MinerComponent::ControlBoard {}) => FaultComponent::Control,
|
|
Some(MinerComponent::Fan { idx }) => FaultComponent::Fan(*idx as usize),
|
|
Some(MinerComponent::HashBoard { idx, .. }) => FaultComponent::Board(*idx as usize),
|
|
// Unattributed (every Antminer-hardware firmware): recover a board
|
|
// index from the message text so hashboard faults show on the board
|
|
// they name, not the control-board tooltip (round 18 #5).
|
|
None => board_index_from_text(text)
|
|
.map(FaultComponent::Board)
|
|
.unwrap_or(FaultComponent::Other),
|
|
};
|
|
Some(Fault {
|
|
component,
|
|
message: text.to_string(),
|
|
code: m.code,
|
|
is_error,
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// A hashboard's health dot from its reported activity. `active` is the firmware's
|
|
/// active flag; `working_chips` its working-chip count. Green needs positive
|
|
/// evidence (active, or a nonzero chip count); a board with neither flag nor count
|
|
/// reads grey ("not detected") rather than green (issue #39: an S17 control board
|
|
/// with no hashboards attached showed its boards green). A board that is present
|
|
/// but idle or has zero working chips reads as a fault (red).
|
|
fn board_health(
|
|
active: Option<bool>,
|
|
working_chips: Option<u16>,
|
|
miner_active: bool,
|
|
) -> crate::model::BoardHealth {
|
|
use crate::model::BoardHealth;
|
|
match (active, working_chips) {
|
|
(Some(true), _) => BoardHealth::Ok,
|
|
(Some(false), _) => BoardHealth::Fault,
|
|
(None, Some(c)) if c > 0 => BoardHealth::Ok,
|
|
(None, Some(_)) => BoardHealth::Fault,
|
|
// No per-board evidence. If the miner shows overall activity (hashing),
|
|
// the board is clearly present and working -> green; only an idle miner
|
|
// with no board telemetry reads grey (issue #39: bare S17; review #3: do
|
|
// not grey a genuinely-mining miner whose backend omits per-board fields).
|
|
(None, None) => {
|
|
if miner_active {
|
|
BoardHealth::Ok
|
|
} else {
|
|
BoardHealth::Missing
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod board_health_tests {
|
|
use super::board_health;
|
|
use crate::model::BoardHealth;
|
|
|
|
#[test]
|
|
fn no_activity_evidence_reads_grey_not_green() {
|
|
// Issue #39: the firmware lists a board but reports no active flag and no
|
|
// working-chip count -> not detected (grey), not green.
|
|
// Idle miner, no per-board evidence -> not detected (grey).
|
|
assert_eq!(board_health(None, None, false), BoardHealth::Missing);
|
|
// Mining miner, no per-board evidence -> still green (review #3).
|
|
assert_eq!(board_health(None, None, true), BoardHealth::Ok);
|
|
// Positive evidence still greens regardless of miner activity.
|
|
assert_eq!(board_health(Some(true), None, false), BoardHealth::Ok);
|
|
assert_eq!(board_health(None, Some(63), false), BoardHealth::Ok);
|
|
// Present but idle / zero working chips -> fault (red).
|
|
assert_eq!(board_health(Some(false), Some(63), false), BoardHealth::Fault);
|
|
assert_eq!(board_health(None, Some(0), false), BoardHealth::Fault);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod board_index_tests {
|
|
use super::board_index_from_text;
|
|
#[test]
|
|
fn extracts_board_index_from_common_fault_texts() {
|
|
assert_eq!(
|
|
board_index_from_text("Chain 2 temperature sensor error"),
|
|
Some(2)
|
|
);
|
|
assert_eq!(
|
|
board_index_from_text("hashboard 0 loss of balance"),
|
|
Some(0)
|
|
);
|
|
assert_eq!(
|
|
board_index_from_text("Slot 1 error reading chip id."),
|
|
Some(1)
|
|
);
|
|
assert_eq!(board_index_from_text("Board #3 not responding"), Some(3));
|
|
// No board keyword -> not attributed to a board.
|
|
assert_eq!(
|
|
board_index_from_text("Environment temperature is too high."),
|
|
None
|
|
);
|
|
assert_eq!(board_index_from_text("Power current error."), None);
|
|
}
|
|
|
|
#[test]
|
|
fn does_not_grab_an_unrelated_number_far_past_the_keyword() {
|
|
// The number must immediately follow the keyword: a later temperature/count
|
|
// must not be mistaken for the board index (round 18 #12).
|
|
assert_eq!(
|
|
board_index_from_text("hashboard error, chip temp 65C"),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
board_index_from_text("board voltage low, 12 chips offline"),
|
|
None
|
|
);
|
|
// A real "board <n>" still resolves even with trailing numbers.
|
|
assert_eq!(board_index_from_text("Chain 2 has 3 dead chips"), Some(2));
|
|
}
|
|
}
|
|
|
|
/// Infer whether an Antminer's hashboards carry a per-board PIC MCU from the
|
|
/// model string (round 14 #2). No firmware (stock cgminer, Vnish, LuxOS, Braiins)
|
|
/// exposes a PIC flag over the network; PIC-vs-noPIC is fixed by the hashboard
|
|
/// type, so a model map is the only network-only method:
|
|
/// - noPIC: an explicit "noPIC" model, the S19k Pro board, and the BM1368+
|
|
/// generation (S21 family, T21), where Bitmain dropped the per-board PIC.
|
|
/// - PIC: the rest of the S19 line (BM1362/BM1366, PIC16F1704/1542).
|
|
/// - unknown: everything else (older Antminers, non-Antminer makes).
|
|
///
|
|
/// The one genuinely ambiguous model is the plain "S19j Pro" (both PIC and noPIC
|
|
/// revisions exist); it is assumed PIC unless the model string says noPIC.
|
|
pub(crate) fn infer_pic(model: &str) -> Option<bool> {
|
|
let m = model.to_lowercase();
|
|
if m.contains("nopic") {
|
|
return Some(false);
|
|
}
|
|
if m.contains("s21") || m.contains("t21") {
|
|
return Some(false);
|
|
}
|
|
if m.contains("s19k") {
|
|
return Some(false);
|
|
}
|
|
if m.contains("s19") {
|
|
return Some(true);
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Bixbit and Hiveon are aftermarket firmwares that keep the stock Antminer web
|
|
/// API, so asic-rs identifies them as "AntMiner Stock". Distinguish them from real
|
|
/// stock via the cgminer `version` reply (port 4028): Bixbit tags it with
|
|
/// `BixFirmware`/`BixMiner`; Hiveon carries a "hiveon" marker. Returns the display
|
|
/// family to relabel with, or None (round 17). Best-effort + fast: a short probe
|
|
/// only run for Antminer miners that first identified as stock.
|
|
async fn detect_aftermarket_antminer(ip: std::net::IpAddr) -> Option<&'static str> {
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
let connect = tokio::net::TcpStream::connect((ip, 4028));
|
|
let mut stream = tokio::time::timeout(std::time::Duration::from_secs(3), connect)
|
|
.await
|
|
.ok()?
|
|
.ok()?;
|
|
stream.write_all(b"{\"command\":\"version\"}").await.ok()?;
|
|
let mut buf = Vec::new();
|
|
let _ = tokio::time::timeout(
|
|
std::time::Duration::from_secs(3),
|
|
stream.read_to_end(&mut buf),
|
|
)
|
|
.await;
|
|
let text = String::from_utf8_lossy(&buf);
|
|
if text.contains("BixFirmware") || text.contains("BixMiner") || text.contains("BixAPIVersion") {
|
|
Some("Bixbit")
|
|
} else if text.to_ascii_lowercase().contains("hiveon") {
|
|
Some("Hiveon")
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// A lightweight row built from identification alone (no `get_data`), emitted the
|
|
/// instant a miner is identified so it appears in the fleet immediately; the full
|
|
/// telemetry row upserts over it when `get_data` completes (round 19 #18). Only
|
|
/// the cheap, synchronous identity + capability accessors are read here -- no
|
|
/// network I/O beyond what identification already did.
|
|
fn partial_row(miner: &dyn Miner, ip: std::net::IpAddr) -> MinerRow {
|
|
let di = miner.get_device_info();
|
|
let (firmware, _fw_vendor) = crate::naming::firmware_family(&di.firmware);
|
|
let brand = crate::naming::brand(&di.make);
|
|
let model = crate::naming::clean_model(&di.make, &di.model);
|
|
let submodel = crate::naming::submodel(&di.make, &di.model);
|
|
// Same VNish power-limit masking as the full row (round 9 #3).
|
|
let power_limit =
|
|
miner.supports_set_power_limit() && !di.firmware.eq_ignore_ascii_case("VNish");
|
|
let caps = MinerCaps {
|
|
fault_light: miner.supports_set_fault_light(),
|
|
restart: miner.supports_restart(),
|
|
pause: miner.supports_pause(),
|
|
resume: miner.supports_resume(),
|
|
power_limit,
|
|
tuning: miner.supports_set_tuning_percent(),
|
|
// hashrate_target needs the tuning envelope from get_data; the full row
|
|
// fills it in a moment later.
|
|
hashrate_target: false,
|
|
supports_presets: miner.supports_presets(),
|
|
firmware_flash: miner.supports_upgrade_firmware(),
|
|
pools: miner.supports_pools_config(),
|
|
timezone: miner.supports_timezone_config(),
|
|
change_password: miner.supports_change_password(),
|
|
factory_reset: miner.supports_factory_reset(),
|
|
};
|
|
MinerRow {
|
|
ip: ip.to_string(),
|
|
brand,
|
|
model,
|
|
submodel,
|
|
firmware,
|
|
algorithm: di.algo.to_string(),
|
|
write_locked: Some(!caps.any_control()),
|
|
caps,
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
async fn to_row(miner: &dyn Miner) -> MinerRow {
|
|
let data = miner.get_data().await;
|
|
// Whether the firmware reported a current hashrate at all: a reported 0 renders
|
|
// "0.00T", an absent one the "-" dash (round 19 follow-up).
|
|
let hashrate_known = data.hashrate.is_some();
|
|
let hashrate_ths = data
|
|
.hashrate
|
|
.as_ref()
|
|
.map(|h| {
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
})
|
|
.unwrap_or(0.0);
|
|
// Rolling average windows in TH/s (round 19 #10, T2); 0.0 = window not reported.
|
|
let (hashrate_1m_ths, hashrate_5m_ths, hashrate_15m_ths, hashrate_24h_ths) = {
|
|
let to_ths = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
|
|
h.as_ref()
|
|
.map(|h| {
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
})
|
|
.unwrap_or(0.0)
|
|
};
|
|
match data.hashrate_averages.as_ref() {
|
|
Some(a) => (
|
|
to_ths(&a.avg_1m),
|
|
to_ths(&a.avg_5m),
|
|
to_ths(&a.avg_15m),
|
|
to_ths(&a.avg_24h),
|
|
),
|
|
None => (0.0, 0.0, 0.0, 0.0),
|
|
}
|
|
};
|
|
let mut expected_ths = data
|
|
.expected_hashrate
|
|
.as_ref()
|
|
.map(|h| {
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
})
|
|
.unwrap_or(0.0);
|
|
let power_w = data.wattage.as_ref().map(|p| p.as_watts()).unwrap_or(0.0);
|
|
let chip_temp_c = data
|
|
.average_temperature
|
|
.as_ref()
|
|
.map(|t| t.as_celsius())
|
|
.unwrap_or(0.0);
|
|
// Per-hashboard temperature for the "77 / 64 / 74" Chip-temp cell. Prefer the
|
|
// board/PCB temperature over the hottest-chip (outlet) reading: WhatsMiner's
|
|
// outlet_chip is the max chip temp (~100C on the hottest board), which read
|
|
// alarmingly high and didn't match the temperature the miner itself reports;
|
|
// the board temperature (~60-79C) is the figure the miner's own UI shows
|
|
// (round 12 #3). Falls back to the chip temp when no board temp is reported.
|
|
// Index-aligned with the hashboards (index i == board i): a board with no
|
|
// reading is 0.0, NOT dropped, so a missing middle board can't shift the
|
|
// others left in the "77 / - / 74" Chip-temp cell (round 18 #12). Collapsed
|
|
// to empty when NO board reports a temperature, so the cell falls back to the
|
|
// fleet average instead of showing "- / - / -".
|
|
let board_temps: Vec<f64> = {
|
|
let v: Vec<f64> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| {
|
|
b.board_temperature
|
|
.as_ref()
|
|
.or(b.outlet_chip_temperature.as_ref())
|
|
.map(|t| t.as_celsius())
|
|
.filter(|&t| t > 0.0)
|
|
.unwrap_or(0.0)
|
|
})
|
|
.collect();
|
|
if v.iter().all(|&t| t <= 0.0) {
|
|
Vec::new()
|
|
} else {
|
|
v
|
|
}
|
|
};
|
|
// Per-board hashrate (TH/s), index-aligned with the hashboards, for the
|
|
// per-board Health tooltip (round 17 R2). Unlike board_temps this is NOT
|
|
// filtered/compacted -- index i must stay board i so the tooltip numbering
|
|
// lines up.
|
|
let board_hashrates: Vec<f64> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| {
|
|
b.hashrate
|
|
.as_ref()
|
|
.map(|h| {
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
})
|
|
.unwrap_or(0.0)
|
|
})
|
|
.collect();
|
|
// Per-board expected hashrate (TH/s), index-aligned, for the actual/expected
|
|
// per-board tooltip (round 18 #3).
|
|
let board_expected_hashrates: Vec<f64> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| {
|
|
b.expected_hashrate
|
|
.as_ref()
|
|
.map(|h| {
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
})
|
|
.unwrap_or(0.0)
|
|
})
|
|
.collect();
|
|
// Per-board configured voltage (V) and frequency (MHz), index-aligned, for the
|
|
// per-board tooltip (round 18 / roadmap G7 read side). 0.0 where unreported.
|
|
let board_voltages: Vec<f64> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| b.voltage.as_ref().map(|v| v.as_volts()).unwrap_or(0.0))
|
|
.collect();
|
|
let board_frequencies: Vec<f64> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| {
|
|
b.frequency
|
|
.as_ref()
|
|
.map(|f| f.as_megahertz())
|
|
.unwrap_or(0.0)
|
|
})
|
|
.collect();
|
|
let fan_rpms: Vec<f64> = data
|
|
.fans
|
|
.iter()
|
|
.map(|f| f.rpm.as_ref().map(|r| r.as_rpm()).unwrap_or(0.0))
|
|
.collect();
|
|
let worker = data
|
|
.pools
|
|
.iter()
|
|
.flat_map(|g| g.pools.iter())
|
|
.find(|p| p.active == Some(true))
|
|
.or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next())
|
|
.and_then(|p| p.user.clone())
|
|
.unwrap_or_default();
|
|
let active_pool = data
|
|
.pools
|
|
.iter()
|
|
.flat_map(|g| g.pools.iter())
|
|
.find(|p| p.active == Some(true))
|
|
.or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next());
|
|
let pool_url = active_pool
|
|
.and_then(|p| p.url.as_ref().map(|u| u.to_string()))
|
|
.unwrap_or_default();
|
|
// Each configured pool's (url, worker), in order, across all pool groups.
|
|
let pools: Vec<(String, String)> = data
|
|
.pools
|
|
.iter()
|
|
.flat_map(|g| g.pools.iter())
|
|
.map(|p| {
|
|
(
|
|
p.url.as_ref().map(|u| u.to_string()).unwrap_or_default(),
|
|
p.user.clone().unwrap_or_default(),
|
|
)
|
|
})
|
|
.collect();
|
|
// Firmware family (coloured column) and version go in separate columns. Strip
|
|
// the vendor word asic-rs prepends on stock firmware ("AntMiner Stock" ->
|
|
// "Stock") and carry it into the version instead (round 11 #6).
|
|
let (mut firmware, mut fw_vendor) = crate::naming::firmware_family(&data.device_info.firmware);
|
|
// Bixbit/Hiveon masquerade as stock; relabel them from their cgminer signature
|
|
// so they get their own family + colour instead of "Stock" (round 17). This
|
|
// is one extra TCP probe per stock-labelled Antminer per scan (round 18 #12):
|
|
// deliberately re-run each scan rather than cached, because a miner's firmware
|
|
// can change under us between scans (a flash/restore), and the detection must
|
|
// stay current; it only fires for Antminers that still read as plain "Stock".
|
|
if data.device_info.make.eq_ignore_ascii_case("antminer")
|
|
&& firmware.eq_ignore_ascii_case("stock")
|
|
{
|
|
if let Some(fam) = detect_aftermarket_antminer(data.ip).await {
|
|
firmware = fam.to_string();
|
|
fw_vendor = None; // the aftermarket version stands alone, no "AntMiner" prefix
|
|
}
|
|
}
|
|
let raw_fw_version = data.firmware_version.clone().unwrap_or_default();
|
|
let fw_version = match (fw_vendor, raw_fw_version.is_empty()) {
|
|
(Some(vendor), false) => format!("{vendor} {raw_fw_version}"),
|
|
(Some(vendor), true) => vendor,
|
|
(None, _) => raw_fw_version,
|
|
};
|
|
// Split asic-rs's compact make/model identifiers into the human-facing
|
|
// Brand / Model / Submodel the table shows (see crate::naming). asic-rs hands
|
|
// us "Antminer"/"S19KPro"; we render brand "Antminer", model "S19k Pro".
|
|
let make = data.device_info.make.clone();
|
|
let model_id = data.device_info.model.clone();
|
|
let brand = crate::naming::brand(&make);
|
|
let model = crate::naming::clean_model(&make, &model_id);
|
|
let submodel = crate::naming::submodel(&make, &model_id);
|
|
let raw_board = data
|
|
.control_board_version
|
|
.as_ref()
|
|
.map(|c| c.to_string())
|
|
.unwrap_or_default();
|
|
let control_board = crate::naming::control_board_code(&make, &raw_board, &model);
|
|
let cpu = crate::naming::control_board_cpu(&make, &raw_board, &model);
|
|
let board_code = crate::naming::control_board_board(&make, &raw_board, &model);
|
|
// asic-rs has no cooling-type field and reports air-cooled miners' ambient
|
|
// reading in `fluid_temperature` (the WhatsMiner backends read the "Env
|
|
// Temp"/"environment-temperature" key). Route it to the Env-temp column for
|
|
// air-cooled models so it isn't mislabelled as a coolant temp (round 11 #17).
|
|
let reported_fluid = data
|
|
.fluid_temperature
|
|
.as_ref()
|
|
.map(|t| t.as_celsius())
|
|
.unwrap_or(0.0);
|
|
let (fluid_temp_c, env_temp_c) = if crate::naming::is_liquid_cooled(&model) {
|
|
(reported_fluid, 0.0)
|
|
} else {
|
|
(0.0, reported_fluid)
|
|
};
|
|
let outlet_temp_c = data
|
|
.outlet_fluid_temperature
|
|
.as_ref()
|
|
.map(|t| t.as_celsius())
|
|
.unwrap_or(0.0);
|
|
let psu_fan_rpm = data
|
|
.psu_fans
|
|
.iter()
|
|
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
|
|
.fold(0.0f64, f64::max);
|
|
let algorithm = data
|
|
.hashrate
|
|
.as_ref()
|
|
.map(|h| h.algo.to_string())
|
|
.unwrap_or_default();
|
|
// Equihash (Z15) fallback: plain Z15 firmware omits the expected hashrate, so
|
|
// fill it from the model nameplate (Sol/s -> the ths-normalised value) so the
|
|
// actual/expected column + colour work like every other miner (round 18 #6).
|
|
if expected_ths <= 0.0 && algorithm.eq_ignore_ascii_case("equihash") {
|
|
if let Some(sols) = crate::naming::equihash_expected_sols(&model) {
|
|
expected_ths = sols / 1e12;
|
|
}
|
|
}
|
|
let is_mining = data.is_mining;
|
|
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
|
|
let operating_state = data
|
|
.operating_state
|
|
.as_ref()
|
|
.map(|s| s.to_string())
|
|
.unwrap_or_default();
|
|
let paused = crate::model::is_paused(&operating_state, is_mining);
|
|
// asic-rs advertises supports_set_power_limit=true unconditionally for whole
|
|
// firmware families, VNish included -- where, per operator guidance, the
|
|
// power-limit control should not be offered (round-9 #3). Mask it off for
|
|
// VNish; Braiins and the rest keep asic-rs's answer.
|
|
let power_limit = miner.supports_set_power_limit()
|
|
&& !data.device_info.firmware.eq_ignore_ascii_case("VNish");
|
|
// Structured tuning (round 17 C). Extract the current target + the advertised
|
|
// envelope so the "Set performance target" prompt can show/validate bounds.
|
|
use asic_rs::core::data::miner::TuningTarget;
|
|
let target_watts = |t: &TuningTarget| match t {
|
|
TuningTarget::Power(p) => Some(p.as_watts()),
|
|
_ => None,
|
|
};
|
|
let target_ths = |t: &TuningTarget| match t {
|
|
TuningTarget::HashRate(h) => Some(
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value,
|
|
),
|
|
_ => None,
|
|
};
|
|
let (power_target_min_w, power_target_max_w, hashrate_target_min_ths, hashrate_target_max_ths) =
|
|
match &data.tuning_capabilities {
|
|
Some(c) => (
|
|
c.power
|
|
.as_ref()
|
|
.and_then(|p| p.minimum.as_ref())
|
|
.and_then(&target_watts),
|
|
c.power
|
|
.as_ref()
|
|
.and_then(|p| p.maximum.as_ref())
|
|
.and_then(&target_watts),
|
|
c.hashrate
|
|
.as_ref()
|
|
.and_then(|h| h.minimum.as_ref())
|
|
.and_then(&target_ths),
|
|
c.hashrate
|
|
.as_ref()
|
|
.and_then(|h| h.maximum.as_ref())
|
|
.and_then(&target_ths),
|
|
),
|
|
None => (None, None, None, None),
|
|
};
|
|
let tuning_target_label = data.tuning_target.as_ref().map(|t| match t {
|
|
TuningTarget::Power(p) => format!("{:.0} W", p.as_watts()),
|
|
TuningTarget::HashRate(h) => format!(
|
|
"{:.0} TH/s",
|
|
h.clone()
|
|
.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
|
.value
|
|
),
|
|
TuningTarget::MiningMode(m) => format!("mode {m}"),
|
|
TuningTarget::Preset(s) => format!("preset {s}"),
|
|
TuningTarget::Manual { .. } => "manual".to_string(),
|
|
});
|
|
// The configured power-limit setpoint in watts, when the target is a power
|
|
// target (WhatsMiner "Power Limit", VNish/Braiins power targets). Its own
|
|
// numeric column (round 21 #2), distinct from the mixed Target label.
|
|
let power_limit_w = data.tuning_target.as_ref().and_then(&target_watts);
|
|
// A hashrate target is offerable only where the firmware actively tunes by
|
|
// hashrate through set_tuning_config (ePIC); Braiins advertises a hashrate
|
|
// envelope but has no set_tuning_config wired, so it is excluded.
|
|
let tunes_by_hashrate = matches!(data.tuning_target, Some(TuningTarget::HashRate(_)))
|
|
|| data
|
|
.tuning_capabilities
|
|
.as_ref()
|
|
.map(|c| c.hashrate.is_some())
|
|
.unwrap_or(false);
|
|
let hashrate_target = miner.supports_tuning_config() && tunes_by_hashrate;
|
|
// Probe what this miner supports being told to do (sync, no extra I/O).
|
|
let caps = MinerCaps {
|
|
fault_light: miner.supports_set_fault_light(),
|
|
restart: miner.supports_restart(),
|
|
pause: miner.supports_pause(),
|
|
resume: miner.supports_resume(),
|
|
power_limit,
|
|
tuning: miner.supports_set_tuning_percent(),
|
|
hashrate_target,
|
|
supports_presets: miner.supports_presets(),
|
|
firmware_flash: miner.supports_upgrade_firmware(),
|
|
pools: miner.supports_pools_config(),
|
|
timezone: miner.supports_timezone_config(),
|
|
change_password: miner.supports_change_password(),
|
|
factory_reset: miner.supports_factory_reset(),
|
|
};
|
|
// The firmware's selectable named presets/profiles (round 18 / roadmap G3),
|
|
// read live only for miners that advertise them (LuxOS/VNish). One extra RPC
|
|
// at scan time for those miners; the default 300 s rescan makes it negligible.
|
|
let presets: Vec<crate::model::MinerPreset> = if caps.supports_presets {
|
|
miner
|
|
.get_presets()
|
|
.await
|
|
.into_iter()
|
|
.map(|p| crate::model::MinerPreset {
|
|
name: p.name,
|
|
pretty: p.pretty,
|
|
})
|
|
.collect()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
// PIC vs noPIC (round 14 #2 rework). No firmware exposes a PIC flag over the
|
|
// network -- it's a fixed hardware property of the hashboard type -- so infer
|
|
// it from the model, which every API reports. See `infer_pic`.
|
|
let pic_present = infer_pic(&model);
|
|
// Access: locked/view-only when the miner exposes no writable control at
|
|
// all, otherwise unlocked. Inferred from asic-rs capabilities (there is no
|
|
// direct lock-state field). This now covers WhatsMiner too: since round 12
|
|
// #8b gave the V1/V2/V3 backends their control commands, a WhatsMiner reports
|
|
// control caps and reads as unlocked here instead of a blank cell (round 14
|
|
// #6). The right-click access check (the :4028 token handshake) still refines
|
|
// this to "locked" for a unit whose API is in read-only mode.
|
|
let write_locked = Some(!caps.any_control());
|
|
// Per-hashboard health for the Boards status dots (round 11 #10): green =
|
|
// present & hashing, red = present but idle/faulty, grey = expected but not
|
|
// detected. Boards keep asic-rs's reported order (board 1 first); any boards
|
|
// expected beyond those reported are padded as Missing.
|
|
let mut board_status: Vec<crate::model::BoardHealth> = data
|
|
.hashboards
|
|
.iter()
|
|
.map(|b| board_health(b.active, b.working_chips, is_mining || hashrate_ths > 0.0))
|
|
.collect();
|
|
if let Some(exp) = data.expected_hashboards {
|
|
while board_status.len() < exp as usize {
|
|
board_status.push(crate::model::BoardHealth::Missing);
|
|
}
|
|
}
|
|
let errors = summarize_messages(&data.messages);
|
|
let faults = messages_to_faults(&data.messages);
|
|
MinerRow {
|
|
ip: data.ip.to_string(),
|
|
selected: false,
|
|
caps,
|
|
algorithm,
|
|
// ASIC chip type + hashboard model, from the first board that reports them
|
|
// (uniform across boards); empty where the firmware doesn't expose them
|
|
// (round 19 #10). When no board reports a chip type (VNish/stock
|
|
// Antminer/LuxOS never do), fall back to the fixed per-model chip for
|
|
// Antminer hardware (round 21 #3).
|
|
chip_type: data
|
|
.hashboards
|
|
.iter()
|
|
.find_map(|b| b.chip_type.clone())
|
|
.or_else(|| crate::naming::chip_type_for_model(&make, &model_id).map(str::to_string))
|
|
.unwrap_or_default(),
|
|
hashboard_model: data
|
|
.hashboards
|
|
.iter()
|
|
.find_map(|b| b.hashboard_model.clone())
|
|
.unwrap_or_default(),
|
|
pic_present,
|
|
write_locked,
|
|
// asic-rs identified this miner, so it is not running Alkane OS.
|
|
alkane_board: None,
|
|
errors,
|
|
faults,
|
|
model,
|
|
brand,
|
|
submodel,
|
|
presets,
|
|
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
|
|
hostname: data.hostname.clone().unwrap_or_default(),
|
|
serial: {
|
|
// Some miners report a placeholder serial ("N/A", "none", ...); show
|
|
// those as an empty cell rather than the literal placeholder (round 12).
|
|
let s = data.serial_number.clone().unwrap_or_default();
|
|
let t = s.trim();
|
|
if t.is_empty()
|
|
|| t.eq_ignore_ascii_case("n/a")
|
|
|| t.eq_ignore_ascii_case("na")
|
|
|| t.eq_ignore_ascii_case("none")
|
|
|| t.eq_ignore_ascii_case("null")
|
|
{
|
|
String::new()
|
|
} else {
|
|
s
|
|
}
|
|
},
|
|
firmware,
|
|
fw_version,
|
|
api_version: data.api_version.clone().unwrap_or_default(),
|
|
control_board,
|
|
cpu,
|
|
board_code,
|
|
hashrate_ths,
|
|
hashrate_known,
|
|
hashrate_1m_ths,
|
|
hashrate_5m_ths,
|
|
hashrate_15m_ths,
|
|
hashrate_24h_ths,
|
|
expected_ths,
|
|
board_hashrates,
|
|
board_expected_hashrates,
|
|
board_voltages,
|
|
board_frequencies,
|
|
efficiency: data.efficiency.unwrap_or(0.0),
|
|
power_w,
|
|
// PSU info (round 17 R5/G15; ePIC exposes it today). A reported-but-zero
|
|
// output current (ePIC leaves it 0) is treated as absent so the R2 tooltip
|
|
// shows just the voltage.
|
|
psu_out_voltage_v: data
|
|
.psu
|
|
.as_ref()
|
|
.and_then(|p| p.output_voltage)
|
|
.filter(|&v| v > 0.0),
|
|
psu_out_current_a: data
|
|
.psu
|
|
.as_ref()
|
|
.and_then(|p| p.output_current)
|
|
.filter(|&a| a > 0.0),
|
|
psu_version: data
|
|
.psu
|
|
.as_ref()
|
|
.map(|p| match (&p.model, &p.version) {
|
|
(Some(m), Some(v)) => format!("{v} ({m})"),
|
|
(None, Some(v)) => v.clone(),
|
|
(Some(m), None) => m.clone(),
|
|
(None, None) => String::new(),
|
|
})
|
|
.unwrap_or_default(),
|
|
psu_serial: data
|
|
.psu
|
|
.as_ref()
|
|
.and_then(|p| p.serial.clone())
|
|
.unwrap_or_default(),
|
|
psu_voltage_min_v: data.psu.as_ref().and_then(|p| p.voltage_min),
|
|
psu_voltage_max_v: data.psu.as_ref().and_then(|p| p.voltage_max),
|
|
tuning_target_label,
|
|
power_limit_w,
|
|
power_target_min_w,
|
|
power_target_max_w,
|
|
hashrate_target_min_ths,
|
|
hashrate_target_max_ths,
|
|
tuning_percent: data.tuning_percent,
|
|
chip_temp_c,
|
|
board_temps,
|
|
fluid_temp_c,
|
|
env_temp_c,
|
|
outlet_temp_c,
|
|
temp_target_c: data.temp_target,
|
|
temp_hot_c: data.temp_hot,
|
|
temp_dangerous_c: data.temp_dangerous,
|
|
fan_rpms,
|
|
fan_speed_percent: data.fan_speed_percent,
|
|
psu_fan_rpm,
|
|
fan_count: (!data.fans.is_empty()).then_some(data.fans.len() as u32),
|
|
expected_fans: data.expected_fans.map(|v| v as u32),
|
|
total_chips: data.total_chips.map(|v| v as u32),
|
|
expected_chips: data.expected_chips.map(|v| v as u32),
|
|
hashboards: (!data.hashboards.is_empty()).then_some(data.hashboards.len() as u32),
|
|
expected_hashboards: data.expected_hashboards.map(|v| v as u32),
|
|
board_status,
|
|
worker,
|
|
pool_url,
|
|
pools,
|
|
best_share: data.best_share,
|
|
session_best_share: data.session_best_share,
|
|
// Accepted / rejected shares summed across every configured pool (round 19
|
|
// #10); None when no pool reports the count.
|
|
accepted_shares: {
|
|
let mut total = 0u64;
|
|
let mut any = false;
|
|
for p in data.pools.iter().flat_map(|g| g.pools.iter()) {
|
|
if let Some(v) = p.accepted_shares {
|
|
total = total.saturating_add(v);
|
|
any = true;
|
|
}
|
|
}
|
|
any.then_some(total)
|
|
},
|
|
rejected_shares: {
|
|
let mut total = 0u64;
|
|
let mut any = false;
|
|
for p in data.pools.iter().flat_map(|g| g.pools.iter()) {
|
|
if let Some(v) = p.rejected_shares {
|
|
total = total.saturating_add(v);
|
|
any = true;
|
|
}
|
|
}
|
|
any.then_some(total)
|
|
},
|
|
// Cumulative share stats from the miner summary (round 19 #10, T2).
|
|
difficulty_accepted: data
|
|
.share_summary
|
|
.as_ref()
|
|
.and_then(|s| s.difficulty_accepted),
|
|
difficulty_rejected: data
|
|
.share_summary
|
|
.as_ref()
|
|
.and_then(|s| s.difficulty_rejected),
|
|
stale_shares: data.share_summary.as_ref().and_then(|s| s.stale_shares),
|
|
found_blocks: data.share_summary.as_ref().and_then(|s| s.found_blocks),
|
|
uptime_secs: data.uptime.map(|d| d.as_secs()).unwrap_or(0),
|
|
light_flashing: data.light_flashing,
|
|
operating_state,
|
|
tuner_status: data.tuner_status.clone().unwrap_or_default(),
|
|
is_mining,
|
|
slow,
|
|
paused,
|
|
}
|
|
}
|
|
|
|
/// A one-shot configuration action applied to a set of miners from the
|
|
/// right-click menu.
|
|
#[derive(Debug, Clone)]
|
|
pub enum ConfigAction {
|
|
FaultLight(bool),
|
|
Restart,
|
|
Pause,
|
|
Resume,
|
|
PowerLimit(f64), // watts
|
|
HashRateTarget(f64), // TH/s -- structured hashrate target (round 17 C)
|
|
Preset(String), // named firmware profile/preset (round 18 / G3)
|
|
TuningPercent(u8),
|
|
Timezone(String), // IANA zone, e.g. "America/Edmonton" (round 17 B / G10)
|
|
ChangePassword(String), // new web/API password (round 17 B / G11)
|
|
FactoryReset, // round 17 B / G12
|
|
}
|
|
|
|
impl ConfigAction {
|
|
/// Short label for status text and summaries.
|
|
pub fn label(&self) -> String {
|
|
match self {
|
|
ConfigAction::FaultLight(true) => "flash lights on".into(),
|
|
ConfigAction::FaultLight(false) => "flash lights off".into(),
|
|
ConfigAction::Restart => "restart".into(),
|
|
ConfigAction::Pause => "pause".into(),
|
|
ConfigAction::Resume => "resume".into(),
|
|
ConfigAction::PowerLimit(w) => format!("power target {w:.0} W"),
|
|
ConfigAction::HashRateTarget(t) => format!("hashrate target {t:.0} TH/s"),
|
|
ConfigAction::Preset(name) => format!("preset {name}"),
|
|
ConfigAction::TuningPercent(p) => format!("tuning {p}%"),
|
|
ConfigAction::Timezone(tz) => format!("timezone {tz}"),
|
|
ConfigAction::ChangePassword(_) => "change password".into(),
|
|
ConfigAction::FactoryReset => "factory reset".into(),
|
|
}
|
|
}
|
|
|
|
/// Short present-tense label shown in a miner's Health cell while the action
|
|
/// runs (round 14 #4).
|
|
pub fn progress_label(&self) -> String {
|
|
match self {
|
|
ConfigAction::FaultLight(true) => "light on...".into(),
|
|
ConfigAction::FaultLight(false) => "light off...".into(),
|
|
ConfigAction::Restart => "restarting...".into(),
|
|
ConfigAction::Pause => "pausing...".into(),
|
|
ConfigAction::Resume => "resuming...".into(),
|
|
ConfigAction::PowerLimit(_) => "setting power...".into(),
|
|
ConfigAction::HashRateTarget(_) => "setting hashrate...".into(),
|
|
ConfigAction::Preset(_) => "setting preset...".into(),
|
|
ConfigAction::TuningPercent(_) => "tuning...".into(),
|
|
ConfigAction::Timezone(_) => "setting timezone...".into(),
|
|
ConfigAction::ChangePassword(_) => "changing password...".into(),
|
|
ConfigAction::FactoryReset => "factory resetting...".into(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Progress/results from a running config action.
|
|
pub enum ActionMsg {
|
|
Started {
|
|
total: usize,
|
|
},
|
|
Result {
|
|
ip: String,
|
|
ok: bool,
|
|
detail: String,
|
|
},
|
|
Done {
|
|
ok: usize,
|
|
total: usize,
|
|
},
|
|
}
|
|
|
|
/// A running config action; `stop` cancels the remaining miners.
|
|
pub struct ActionHandle {
|
|
pub rx: Receiver<ActionMsg>,
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl ActionHandle {
|
|
pub fn stop(&self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result<bool, String> {
|
|
let result = match action {
|
|
ConfigAction::FaultLight(on) => miner.set_fault_light(*on).await,
|
|
ConfigAction::Restart => miner.restart().await,
|
|
ConfigAction::Pause => miner.pause(None).await,
|
|
ConfigAction::Resume => miner.resume(None).await,
|
|
ConfigAction::PowerLimit(w) => miner.set_power_limit(Power::from_watts(*w)).await,
|
|
ConfigAction::HashRateTarget(ths) => {
|
|
use asic_rs::core::config::tuning::TuningConfig;
|
|
use asic_rs::core::data::hashrate::HashRateUnit;
|
|
use asic_rs::core::data::miner::TuningTarget;
|
|
// Build a HashRate target by cloning the miner's current hashrate to
|
|
// inherit its algorithm (HashAlgorithm is not publicly nameable),
|
|
// overriding value + unit.
|
|
let data = miner.get_data().await;
|
|
let Some(mut hr) = data.hashrate.clone() else {
|
|
return Err(
|
|
"miner reports no current hashrate; cannot set a hashrate target".into(),
|
|
);
|
|
};
|
|
hr.value = *ths;
|
|
hr.unit = HashRateUnit::TeraHash;
|
|
let mut cfg = TuningConfig::new(TuningTarget::HashRate(hr));
|
|
// Preserve the firmware's current tuning algorithm + scaling (ePIC
|
|
// requires both for set_tuning_config; other firmware ignore them).
|
|
if let Some(algo) = miner
|
|
.get_tuning_config()
|
|
.await
|
|
.ok()
|
|
.and_then(|c| c.algorithm)
|
|
{
|
|
cfg = cfg.with_algorithm(algo);
|
|
}
|
|
let scaling = miner.get_scaling_config().await.ok();
|
|
miner.set_tuning_config(cfg, scaling).await
|
|
}
|
|
ConfigAction::Preset(name) => {
|
|
use asic_rs::core::config::tuning::TuningConfig;
|
|
use asic_rs::core::data::miner::TuningTarget;
|
|
miner
|
|
.set_tuning_config(TuningConfig::new(TuningTarget::Preset(name.clone())), None)
|
|
.await
|
|
}
|
|
ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await,
|
|
ConfigAction::Timezone(tz) => {
|
|
use asic_rs::core::config::timezone::{TimezoneConfig, Tz};
|
|
match tz.parse::<Tz>() {
|
|
Ok(zone) => {
|
|
miner
|
|
.set_timezone_config(TimezoneConfig {
|
|
timezone: Some(zone),
|
|
available: Vec::new(),
|
|
})
|
|
.await
|
|
}
|
|
Err(_) => return Err(format!("invalid IANA timezone '{tz}'")),
|
|
}
|
|
}
|
|
ConfigAction::FactoryReset => miner.factory_reset().await,
|
|
// ChangePassword takes &mut self; handled in the run loop, not here.
|
|
ConfigAction::ChangePassword(_) => {
|
|
return Err("internal: change-password handled separately".to_string());
|
|
}
|
|
};
|
|
result.map_err(|e| e.to_string())
|
|
}
|
|
|
|
/// Fetch one miner's log via asic-rs's per-backend `read_logs()` (round 19
|
|
/// #11-16). Runs synchronously on the caller's thread in a short-lived
|
|
/// current-thread runtime (mirroring `start_config_action`), so the GUI's
|
|
/// existing "log-fetch" worker thread can call it directly. `Err` when the IP is
|
|
/// unparseable, no miner answers, the backend has no log API (e.g. LuxOS,
|
|
/// WhatsMiner), or the fetch fails/times out.
|
|
pub fn fetch_log(ip: &str, timeout_secs: u64) -> Result<String, String> {
|
|
let addr: std::net::IpAddr = ip.parse().map_err(|_| "bad IP".to_string())?;
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
.map_err(|e| format!("runtime: {e}"))?;
|
|
rt.block_on(async move {
|
|
let factory = crate::credentials::configured_factory()
|
|
.with_identification_timeout_secs(timeout_secs.max(1));
|
|
let miner = match factory.scan_miner(addr).await {
|
|
Ok(Some(m)) => m,
|
|
Ok(None) => return Err("no miner answered at this IP".to_string()),
|
|
Err(e) => return Err(format!("{e}")),
|
|
};
|
|
if !miner.supports_read_logs() {
|
|
return Err("this firmware's backend does not expose logs over its API".to_string());
|
|
}
|
|
match tokio::time::timeout(std::time::Duration::from_secs(25), miner.read_logs()).await {
|
|
Ok(Ok(text)) => Ok(text),
|
|
Ok(Err(e)) => Err(format!("read logs: {e}")),
|
|
Err(_) => Err("log fetch timed out".to_string()),
|
|
}
|
|
})
|
|
}
|
|
|
|
/// Apply `action` to each miner in `ips` on a background thread: re-discover the
|
|
/// miner (asic-rs `scan_miner`), run the setter, and report per-IP results. In
|
|
/// fake-scan mode it reports simulated successes so the flow works offline.
|
|
pub fn start_config_action(ips: Vec<String>, action: ConfigAction) -> ActionHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
let total = ips.len();
|
|
let _ = tx.send(ActionMsg::Started { total });
|
|
|
|
if fake_scan_enabled() {
|
|
let err_tx = tx.clone();
|
|
let thread_cancel = cancel.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-action".into())
|
|
.spawn(move || {
|
|
let mut ok = 0usize;
|
|
for ip in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let _ = tx.send(ActionMsg::Result {
|
|
ip,
|
|
ok: true,
|
|
detail: "simulated".into(),
|
|
});
|
|
ok += 1;
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
return ActionHandle { rx, cancel };
|
|
}
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("config-action".into())
|
|
.spawn(move || {
|
|
// A single-threaded runtime: the loop applies to one miner at a time, so
|
|
// a worker-per-CPU pool would be wasted.
|
|
let rt = match tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
{
|
|
Ok(rt) => rt,
|
|
Err(_) => {
|
|
let _ = tx.send(ActionMsg::Done { ok: 0, total });
|
|
return;
|
|
}
|
|
};
|
|
rt.block_on(async move {
|
|
let factory = crate::credentials::configured_factory();
|
|
let mut ok = 0usize;
|
|
for ip_s in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let (success, detail) = match ip_s.parse::<std::net::IpAddr>() {
|
|
Err(_) => (false, "bad IP".to_string()),
|
|
Ok(ip) => match factory.scan_miner(ip).await {
|
|
Ok(Some(mut miner)) => {
|
|
// change_password takes &mut self, so it can't go through
|
|
// apply_action(&dyn Miner); run it on the owned miner here.
|
|
let outcome = match &action {
|
|
ConfigAction::ChangePassword(p) => {
|
|
miner.change_password(p).await.map_err(|e| e.to_string())
|
|
}
|
|
other => apply_action(&*miner, other).await,
|
|
};
|
|
match outcome {
|
|
Ok(true) => (true, "ok".to_string()),
|
|
Ok(false) => (false, "refused".to_string()),
|
|
Err(e) => (false, e.to_string()),
|
|
}
|
|
}
|
|
Ok(None) => (false, "no miner at IP".to_string()),
|
|
Err(e) => (false, format!("{e}")),
|
|
},
|
|
};
|
|
if success {
|
|
ok += 1;
|
|
}
|
|
if tx
|
|
.send(ActionMsg::Result {
|
|
ip: ip_s,
|
|
ok: success,
|
|
detail,
|
|
})
|
|
.is_err()
|
|
{
|
|
return; // UI gone
|
|
}
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
ActionHandle { rx, cancel }
|
|
}
|
|
|
|
/// One resolved pool endpoint (worker already expanded from the template).
|
|
pub struct PoolEntry {
|
|
pub url: String,
|
|
pub username: String,
|
|
pub password: String,
|
|
}
|
|
|
|
/// One miner's pool config to write (round 14 #7, round 15 #1): up to three
|
|
/// pools (primary + backups), each already worker-expanded in the UI.
|
|
pub struct PoolTarget {
|
|
pub ip: String,
|
|
pub pools: Vec<PoolEntry>,
|
|
}
|
|
|
|
/// Apply a single "default" pool group to each target miner on a background
|
|
/// thread (round 14 #7). Reuses the ActionMsg/ActionHandle plumbing so the
|
|
/// existing drain_action + status handling covers it. Miners whose backend does
|
|
/// not support pool configuration report "not supported" rather than failing the
|
|
/// batch.
|
|
pub fn start_pools_action(targets: Vec<PoolTarget>) -> ActionHandle {
|
|
use asic_rs::core::config::pools::{PoolConfig, PoolGroupConfig};
|
|
use asic_rs::core::data::pool::PoolURL;
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
let total = targets.len();
|
|
let _ = tx.send(ActionMsg::Started { total });
|
|
|
|
if fake_scan_enabled() {
|
|
let err_tx = tx.clone();
|
|
let thread_cancel = cancel.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-pools".into())
|
|
.spawn(move || {
|
|
let mut ok = 0usize;
|
|
for t in targets {
|
|
// Honour cancellation between miners, like every sibling background
|
|
// action's fake branch (round 18 #12).
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let first = t
|
|
.pools
|
|
.first()
|
|
.map(|p| p.username.clone())
|
|
.unwrap_or_default();
|
|
let _ = tx.send(ActionMsg::Result {
|
|
ip: t.ip,
|
|
ok: true,
|
|
detail: format!("simulated ({} pool(s), {first})", t.pools.len()),
|
|
});
|
|
ok += 1;
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
return ActionHandle { rx, cancel };
|
|
}
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("pools-action".into())
|
|
.spawn(move || {
|
|
let rt = match tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
{
|
|
Ok(rt) => rt,
|
|
Err(_) => {
|
|
let _ = tx.send(ActionMsg::Done { ok: 0, total });
|
|
return;
|
|
}
|
|
};
|
|
rt.block_on(async move {
|
|
let factory = crate::credentials::configured_factory();
|
|
let mut ok = 0usize;
|
|
for t in targets {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let (success, detail) = match t.ip.parse::<std::net::IpAddr>() {
|
|
Err(_) => (false, "bad IP".to_string()),
|
|
Ok(ip) => match factory.scan_miner(ip).await {
|
|
Ok(Some(miner)) if !miner.supports_pools_config() => {
|
|
(false, "not supported".to_string())
|
|
}
|
|
Ok(Some(miner)) => {
|
|
let group = PoolGroupConfig {
|
|
name: "default".to_string(),
|
|
quota: 1,
|
|
pools: t
|
|
.pools
|
|
.iter()
|
|
.map(|p| PoolConfig {
|
|
url: PoolURL::from(p.url.clone()),
|
|
username: p.username.clone(),
|
|
password: p.password.clone(),
|
|
})
|
|
.collect(),
|
|
};
|
|
match miner.set_pools_config(vec![group]).await {
|
|
Ok(true) => (true, "ok".to_string()),
|
|
Ok(false) => (false, "refused".to_string()),
|
|
Err(e) => (false, format!("{e}")),
|
|
}
|
|
}
|
|
Ok(None) => (false, "no miner at IP".to_string()),
|
|
Err(e) => (false, format!("{e}")),
|
|
},
|
|
};
|
|
if success {
|
|
ok += 1;
|
|
}
|
|
if tx
|
|
.send(ActionMsg::Result {
|
|
ip: t.ip,
|
|
ok: success,
|
|
detail,
|
|
})
|
|
.is_err()
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
ActionHandle { rx, cancel }
|
|
}
|
|
|
|
/// Progress/results from a background refresh of a specific, already-known
|
|
/// set of miners (re-poll on a timer or after a right-click "Refresh" action,
|
|
/// as opposed to `start_scan`'s full subnet sweep).
|
|
// `Row` is the common variant; boxing it to shrink the rare Started/Done/Failed
|
|
// variants would add an allocation per refreshed miner for no real gain (see the
|
|
// note on ScanMsg).
|
|
#[allow(clippy::large_enum_variant)]
|
|
pub enum RefreshMsg {
|
|
Started {
|
|
total: usize,
|
|
},
|
|
/// A miner's telemetry was re-read successfully.
|
|
Row(MinerRow),
|
|
/// A miner could not be reached or re-identified.
|
|
Failed {
|
|
ip: String,
|
|
detail: String,
|
|
},
|
|
Done {
|
|
ok: usize,
|
|
total: usize,
|
|
},
|
|
}
|
|
|
|
/// A running refresh; `stop` cancels the remaining miners.
|
|
pub struct RefreshHandle {
|
|
pub rx: Receiver<RefreshMsg>,
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl RefreshHandle {
|
|
pub fn stop(&self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// Re-poll a specific list of already-known miner IPs on a background thread:
|
|
/// re-discover each one (asic-rs `scan_miner`) and report its fresh row. In
|
|
/// fake-scan mode it reports the matching bench-fleet fixture row per IP.
|
|
pub fn start_refresh(ips: Vec<String>) -> RefreshHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
let total = ips.len();
|
|
let _ = tx.send(RefreshMsg::Started { total });
|
|
|
|
if fake_scan_enabled() {
|
|
let err_tx = tx.clone();
|
|
let thread_cancel = cancel.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-refresh".into())
|
|
.spawn(move || {
|
|
let fleet = crate::fixtures::bench_fleet();
|
|
let mut ok = 0usize;
|
|
for ip in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
match fleet.iter().find(|r| r.ip == ip) {
|
|
Some(row) => {
|
|
if tx.send(RefreshMsg::Row(row.clone())).is_err() {
|
|
return; // UI gone
|
|
}
|
|
ok += 1;
|
|
}
|
|
None => {
|
|
if tx
|
|
.send(RefreshMsg::Failed {
|
|
ip,
|
|
detail: "offline".into(),
|
|
})
|
|
.is_err()
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let _ = tx.send(RefreshMsg::Done { ok, total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(RefreshMsg::Done { ok: 0, total });
|
|
}
|
|
return RefreshHandle { rx, cancel };
|
|
}
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("miner-refresh".into())
|
|
.spawn(move || {
|
|
// A single-threaded runtime: the loop applies to one miner at a time, so
|
|
// a worker-per-CPU pool would be wasted.
|
|
let rt = match tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
{
|
|
Ok(rt) => rt,
|
|
Err(_) => {
|
|
let _ = tx.send(RefreshMsg::Done { ok: 0, total });
|
|
return;
|
|
}
|
|
};
|
|
rt.block_on(async move {
|
|
let factory = crate::credentials::configured_factory();
|
|
let mut ok = 0usize;
|
|
for ip_s in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let msg = match ip_s.parse::<std::net::IpAddr>() {
|
|
Err(_) => RefreshMsg::Failed {
|
|
ip: ip_s,
|
|
detail: "bad IP".to_string(),
|
|
},
|
|
Ok(ip) => match factory.scan_miner(ip).await {
|
|
Ok(Some(miner)) => {
|
|
ok += 1;
|
|
RefreshMsg::Row(to_row(&*miner).await)
|
|
}
|
|
Ok(None) => match crate::alkane_detect::detect(ip).await {
|
|
Some(row) => {
|
|
ok += 1;
|
|
RefreshMsg::Row(row)
|
|
}
|
|
None => RefreshMsg::Failed {
|
|
ip: ip_s,
|
|
detail: "offline".to_string(),
|
|
},
|
|
},
|
|
Err(e) => match crate::alkane_detect::detect(ip).await {
|
|
Some(row) => {
|
|
ok += 1;
|
|
RefreshMsg::Row(row)
|
|
}
|
|
None => RefreshMsg::Failed {
|
|
ip: ip_s,
|
|
detail: format!("{e}"),
|
|
},
|
|
},
|
|
},
|
|
};
|
|
if tx.send(msg).is_err() {
|
|
return; // UI gone
|
|
}
|
|
}
|
|
let _ = tx.send(RefreshMsg::Done { ok, total });
|
|
});
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(RefreshMsg::Done { ok: 0, total });
|
|
}
|
|
RefreshHandle { rx, cancel }
|
|
}
|
|
|
|
/// Prepare (if the backend supports it) then upload a firmware image to one
|
|
/// miner. Never interrupted once started: `start_firmware_flash_action` only
|
|
/// checks its cancel flag between miners, not while this is running.
|
|
async fn flash_one(miner: &dyn Miner, image: &FirmwareImage) -> Result<bool, String> {
|
|
let image = if miner.supports_prepare_firmware() {
|
|
miner
|
|
.prepare_firmware(image.clone())
|
|
.await
|
|
.map_err(|e| e.to_string())?
|
|
} else {
|
|
image.clone()
|
|
};
|
|
miner
|
|
.upgrade_firmware(image)
|
|
.await
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
|
|
/// Flash `image` to each miner in `ips` on a background thread: re-discover the
|
|
/// miner (asic-rs `scan_miner`), then prepare (if supported) and upload the
|
|
/// firmware, reporting per-IP results. Backends that don't implement firmware
|
|
/// upgrade report "unsupported" rather than attempting anything. The cancel
|
|
/// flag is only checked between miners: a flash in progress always runs to
|
|
/// completion instead of being interrupted mid-upload. In fake-scan mode it
|
|
/// reports simulated successes so the flow works offline.
|
|
pub fn start_firmware_flash_action(ips: Vec<String>, image: FirmwareImage) -> ActionHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
let total = ips.len();
|
|
let _ = tx.send(ActionMsg::Started { total });
|
|
|
|
if fake_scan_enabled() {
|
|
let err_tx = tx.clone();
|
|
let thread_cancel = cancel.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-firmware-flash".into())
|
|
.spawn(move || {
|
|
let mut ok = 0usize;
|
|
for ip in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let _ = tx.send(ActionMsg::Result {
|
|
ip,
|
|
ok: true,
|
|
detail: "simulated".into(),
|
|
});
|
|
ok += 1;
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
return ActionHandle { rx, cancel };
|
|
}
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("firmware-flash".into())
|
|
.spawn(move || {
|
|
// A single-threaded runtime: flashes run one miner at a time by
|
|
// design (see the cancel-between-miners note above).
|
|
let rt = match tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
{
|
|
Ok(rt) => rt,
|
|
Err(_) => {
|
|
let _ = tx.send(ActionMsg::Done { ok: 0, total });
|
|
return;
|
|
}
|
|
};
|
|
rt.block_on(async move {
|
|
let factory = crate::credentials::configured_factory();
|
|
let mut ok = 0usize;
|
|
for ip_s in ips {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let (success, detail) = match ip_s.parse::<std::net::IpAddr>() {
|
|
Err(_) => (false, "bad IP".to_string()),
|
|
Ok(ip) => match factory.scan_miner(ip).await {
|
|
Ok(Some(miner)) => {
|
|
if !miner.supports_upgrade_firmware() {
|
|
(false, "unsupported".to_string())
|
|
} else {
|
|
match flash_one(&*miner, &image).await {
|
|
Ok(true) => (true, "ok".to_string()),
|
|
Ok(false) => (false, "refused".to_string()),
|
|
Err(e) => (false, e.to_string()),
|
|
}
|
|
}
|
|
}
|
|
Ok(None) => (false, "no miner at IP".to_string()),
|
|
Err(e) => (false, format!("{e}")),
|
|
},
|
|
};
|
|
if success {
|
|
ok += 1;
|
|
}
|
|
if tx
|
|
.send(ActionMsg::Result {
|
|
ip: ip_s,
|
|
ok: success,
|
|
detail,
|
|
})
|
|
.is_err()
|
|
{
|
|
return; // UI gone
|
|
}
|
|
}
|
|
let _ = tx.send(ActionMsg::Done { ok, total });
|
|
});
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(ActionMsg::Done { ok: 0, total });
|
|
}
|
|
ActionHandle { rx, cancel }
|
|
}
|
|
|
|
/// Progress/results from a background access (lock-state) probe.
|
|
pub enum AccessProbeMsg {
|
|
Started {
|
|
total: usize,
|
|
},
|
|
/// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable,
|
|
/// None indeterminate; `error` set only when the probe couldn't run.
|
|
Result {
|
|
ip: String,
|
|
locked: Option<bool>,
|
|
error: Option<String>,
|
|
},
|
|
Done {
|
|
total: usize,
|
|
},
|
|
}
|
|
|
|
/// A running access probe; `stop` cancels the remaining miners.
|
|
pub struct AccessProbeHandle {
|
|
pub rx: Receiver<AccessProbeMsg>,
|
|
// The worker honours cancellation between miners; a UI stop control is not
|
|
// wired yet, so the handle-side trigger is kept for when it is.
|
|
#[allow(dead_code)]
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl AccessProbeHandle {
|
|
#[allow(dead_code)]
|
|
pub fn stop(&self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// Probe the access/lock state of `targets` (ip + firmware string) over the web
|
|
/// API with `creds` (user, pass), on a background thread. A digest-auth GET is
|
|
/// fast, but we still run one miner at a time with cancel-between. Fake-scan mode
|
|
/// returns deterministic demo results.
|
|
pub fn start_access_probe(
|
|
targets: Vec<(String, String)>,
|
|
creds: (String, String),
|
|
) -> AccessProbeHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
let total = targets.len();
|
|
let _ = tx.send(AccessProbeMsg::Started { total });
|
|
let (user, pass) = creds;
|
|
|
|
if fake_scan_enabled() {
|
|
let err_tx = tx.clone();
|
|
let thread_cancel = cancel.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("fake-access-probe".into())
|
|
.spawn(move || {
|
|
for (ip, _fw) in targets {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
// Demo: the WardenOS-dev unit (.115) is locked, others unlocked.
|
|
let locked = Some(ip.ends_with(".115"));
|
|
let _ = tx.send(AccessProbeMsg::Result {
|
|
ip,
|
|
locked,
|
|
error: None,
|
|
});
|
|
}
|
|
let _ = tx.send(AccessProbeMsg::Done { total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
|
}
|
|
return AccessProbeHandle { rx, cancel };
|
|
}
|
|
|
|
let thread_cancel = cancel.clone();
|
|
let err_tx = tx.clone();
|
|
let res = std::thread::Builder::new()
|
|
.name("access-probe".into())
|
|
.spawn(move || {
|
|
for (ip, make) in targets {
|
|
if thread_cancel.load(Ordering::Relaxed) {
|
|
break;
|
|
}
|
|
let (locked, error) =
|
|
match crate::access_probe::probe_access(&ip, &make, &user, &pass) {
|
|
Ok(v) => (v, None),
|
|
Err(e) => (None, Some(e)),
|
|
};
|
|
if tx
|
|
.send(AccessProbeMsg::Result { ip, locked, error })
|
|
.is_err()
|
|
{
|
|
return; // UI gone
|
|
}
|
|
}
|
|
let _ = tx.send(AccessProbeMsg::Done { total });
|
|
});
|
|
if res.is_err() {
|
|
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
|
}
|
|
AccessProbeHandle { rx, cancel }
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parse_cidr_line() {
|
|
let ips = parse_line("10.253.1.0/30").unwrap();
|
|
assert_eq!(ips.len(), 4);
|
|
assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 0));
|
|
assert_eq!(ips[3], Ipv4Addr::new(10, 253, 1, 3));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_single_ip() {
|
|
let ips = parse_line("10.253.1.5").unwrap();
|
|
assert_eq!(ips, vec![Ipv4Addr::new(10, 253, 1, 5)]);
|
|
}
|
|
|
|
#[test]
|
|
fn parse_full_range() {
|
|
let ips = parse_line("10.253.1.3-10.253.1.234").unwrap();
|
|
assert_eq!(ips.len(), 232);
|
|
assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 3));
|
|
assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_short_range() {
|
|
let ips = parse_line("10.253.1.3-234").unwrap();
|
|
assert_eq!(ips.len(), 232);
|
|
assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_per_octet_ranges() {
|
|
// The user's example: 9 /24s (octet2 1..9), each with .1.1-255.
|
|
let ips = parse_line("10.1-9.1.1-255").unwrap();
|
|
assert_eq!(ips.len(), 9 * 255, "9 /24 ranges of 255 addresses each");
|
|
assert_eq!(ips[0], Ipv4Addr::new(10, 1, 1, 1), "ascending, first combo");
|
|
assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 9, 1, 255));
|
|
// Ordered by octet: the second address is .1.1.2, the 256th is .2.1.1.
|
|
assert_eq!(ips[1], Ipv4Addr::new(10, 1, 1, 2));
|
|
assert_eq!(ips[255], Ipv4Addr::new(10, 2, 1, 1));
|
|
|
|
// Ranges in more than one octet.
|
|
let ips = parse_line("192.168.0-1.10-12").unwrap();
|
|
assert_eq!(ips.len(), 2 * 3);
|
|
assert_eq!(ips[0], Ipv4Addr::new(192, 168, 0, 10));
|
|
assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(192, 168, 1, 12));
|
|
|
|
// A single address still works through the per-octet path.
|
|
assert_eq!(
|
|
parse_line("10.0.0.5").unwrap(),
|
|
vec![Ipv4Addr::new(10, 0, 0, 5)]
|
|
);
|
|
// Reversed octet range is an error.
|
|
assert!(parse_line("10.9-1.1.1").is_err());
|
|
// Out-of-range octet falls through and is reported.
|
|
assert!(parse_line("10.1.1.999").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn parse_cross_octet_range() {
|
|
let ips = parse_line("10.253.1.250-10.253.2.5").unwrap();
|
|
assert_eq!(ips.len(), 12); // .250..=.255 (6) + 2.0..=2.5 (6)
|
|
assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 250));
|
|
assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 2, 5));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_rejects_reversed_range() {
|
|
assert!(parse_line("10.0.0.10-10.0.0.1").is_err());
|
|
assert!(parse_line("not-an-ip").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn parse_rejects_oversized_cidr_and_range() {
|
|
// a /8 (16.7M) and /0 must be rejected, not allocated
|
|
assert!(parse_line("10.0.0.0/8").is_err());
|
|
assert!(parse_line("0.0.0.0/0").is_err());
|
|
// a large full range too
|
|
assert!(parse_line("10.0.0.0-10.99.0.0").is_err());
|
|
// a /16 (65k) is fine
|
|
assert!(parse_line("10.1.0.0/16").is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn targets_dedup_and_sort() {
|
|
let lines = vec![
|
|
"10.0.0.5".to_string(),
|
|
"10.0.0.1-10.0.0.3".to_string(),
|
|
"10.0.0.2".to_string(),
|
|
];
|
|
let t = parse_targets(&lines).unwrap();
|
|
assert_eq!(
|
|
t,
|
|
vec![
|
|
Ipv4Addr::new(10, 0, 0, 1),
|
|
Ipv4Addr::new(10, 0, 0, 2),
|
|
Ipv4Addr::new(10, 0, 0, 3),
|
|
Ipv4Addr::new(10, 0, 0, 5),
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn default_range_covers_the_whole_192_168_1_subnet() {
|
|
let ips = parse_line(DEFAULT_RANGE).unwrap();
|
|
let cidrs = targets_to_cidrs(&ips);
|
|
assert_eq!(cidrs, vec![(Ipv4Addr::new(192, 168, 1, 0), 24)]);
|
|
}
|
|
|
|
#[test]
|
|
fn cidr_aggregation_round_trips() {
|
|
// a /24 must aggregate back to exactly one /24 block
|
|
let ips = parse_line("10.9.8.0/24").unwrap();
|
|
let cidrs = targets_to_cidrs(&ips);
|
|
assert_eq!(cidrs, vec![(Ipv4Addr::new(10, 9, 8, 0), 24)]);
|
|
|
|
// an arbitrary range's blocks must cover exactly the same address set
|
|
let ips = parse_line("10.0.0.3-10.0.0.20").unwrap();
|
|
let cidrs = targets_to_cidrs(&ips);
|
|
let mut covered = Vec::new();
|
|
for (base, prefix) in cidrs {
|
|
let n = 1u32 << (32 - prefix as u32);
|
|
let b = u32::from(base);
|
|
covered.extend((0..n).map(|i| Ipv4Addr::from(b + i)));
|
|
}
|
|
covered.sort();
|
|
assert_eq!(covered, ips);
|
|
}
|
|
|
|
// ---- harness-driven additions (coverage) ----
|
|
|
|
#[test]
|
|
fn parse_cidr_bare_and_rejections() {
|
|
assert_eq!(
|
|
parse_cidr("10.1.2.3"),
|
|
Some((Ipv4Addr::new(10, 1, 2, 3), 32))
|
|
);
|
|
assert_eq!(
|
|
parse_cidr("10.0.0.1/24"),
|
|
Some((Ipv4Addr::new(10, 0, 0, 1), 24))
|
|
);
|
|
assert_eq!(parse_cidr("10.0.0.1/33"), None);
|
|
assert_eq!(parse_cidr("10.0.0.1/abc"), None);
|
|
assert_eq!(parse_cidr("bad/24"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn prefix_mask_boundaries() {
|
|
assert_eq!(prefix_mask(0), 0);
|
|
assert_eq!(prefix_mask(24), 0xFFFF_FF00);
|
|
assert_eq!(prefix_mask(32), u32::MAX);
|
|
}
|
|
|
|
#[test]
|
|
fn parse_line_single_host_cidr_slash_32() {
|
|
assert_eq!(
|
|
parse_line("10.1.2.3/32").unwrap(),
|
|
vec![Ipv4Addr::new(10, 1, 2, 3)]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn parse_line_empty_and_whitespace() {
|
|
assert_eq!(parse_line("").unwrap(), Vec::<Ipv4Addr>::new());
|
|
assert_eq!(parse_line(" ").unwrap(), Vec::<Ipv4Addr>::new());
|
|
}
|
|
|
|
#[test]
|
|
fn parse_line_short_range_single_address_and_reversed() {
|
|
assert_eq!(
|
|
parse_line("10.253.1.5-5").unwrap(),
|
|
vec![Ipv4Addr::new(10, 253, 1, 5)]
|
|
);
|
|
// short form whose end octet precedes the start is an inverted range.
|
|
assert!(parse_line("10.253.1.200-50").is_err());
|
|
assert!(parse_line("10.253.1.3-300").is_err()); // 300 is not a u8
|
|
}
|
|
|
|
#[test]
|
|
fn parse_targets_aggregate_cap_and_errors() {
|
|
// Each /13 (524288) is under the cap; together they exceed 1,000,000.
|
|
let over = parse_targets(&["10.0.0.0/13".into(), "11.0.0.0/13".into()]);
|
|
assert!(over.is_err(), "aggregate over MAX_ADDRS must be rejected");
|
|
// One bad line among good ones propagates.
|
|
assert!(parse_targets(&["10.0.0.1".into(), "not-an-ip".into()]).is_err());
|
|
// Empty input is an empty (Ok) set.
|
|
assert!(parse_targets(&[]).unwrap().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn validate_ranges_empty_ok_and_bad() {
|
|
assert!(validate_ranges(&[]).is_err()); // no addresses
|
|
assert!(validate_ranges(&["10.0.0.0/30".into()]).is_ok());
|
|
assert!(validate_ranges(&["garbage".into()]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn targets_to_cidrs_splits_noncontiguous_runs() {
|
|
let cidrs = targets_to_cidrs(&[Ipv4Addr::new(10, 0, 0, 5), Ipv4Addr::new(10, 0, 0, 10)]);
|
|
assert_eq!(
|
|
cidrs,
|
|
vec![
|
|
(Ipv4Addr::new(10, 0, 0, 5), 32),
|
|
(Ipv4Addr::new(10, 0, 0, 10), 32)
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn auto_secs_round_trip_and_defaults() {
|
|
// config_path() reads the platform's config root ($HOME, or %APPDATA%
|
|
// on Windows); point it at a private temp dir. It is process-global, so
|
|
// serialise against other such tests and restore it afterward (round 18 #12).
|
|
let _home = crate::model::HOME_TEST_LOCK
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner());
|
|
let root_var = alkane_core::platform::CONFIG_ROOT_VAR;
|
|
let prev = std::env::var_os(root_var);
|
|
let dir = std::env::temp_dir().join(format!("alkane-test-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
std::env::set_var(root_var, &dir);
|
|
|
|
assert_eq!(
|
|
load_auto_secs(),
|
|
DEFAULT_AUTO_SECS,
|
|
"missing file -> default"
|
|
);
|
|
save_auto_secs(150).unwrap();
|
|
assert_eq!(load_auto_secs(), 150, "round-trip");
|
|
std::fs::write(config_path(AUTO_FILE), "not-a-number").unwrap();
|
|
assert_eq!(load_auto_secs(), DEFAULT_AUTO_SECS, "malformed -> default");
|
|
std::fs::write(config_path(AUTO_FILE), " 42 \n").unwrap();
|
|
assert_eq!(load_auto_secs(), 42, "whitespace tolerated");
|
|
|
|
match prev {
|
|
Some(v) => std::env::set_var(root_var, v),
|
|
None => std::env::remove_var(root_var),
|
|
}
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
// ---- microbenchmarks (perf-regression gates; run with --ignored) ----
|
|
|
|
#[test]
|
|
#[ignore]
|
|
fn bench_parse_line_near_max_addrs() {
|
|
use std::time::Instant;
|
|
let start = Ipv4Addr::new(10, 0, 0, 0);
|
|
let end = Ipv4Addr::from(u32::from(start) + (MAX_ADDRS as u32 - 2));
|
|
let line = format!("{start}-{end}");
|
|
let iters = 5u32;
|
|
let t = Instant::now();
|
|
let mut sink = 0usize;
|
|
for _ in 0..iters {
|
|
sink += parse_line(&line).unwrap().len();
|
|
}
|
|
let per = t.elapsed() / iters;
|
|
println!(
|
|
"bench_parse_line_near_max_addrs: {sink} addrs, {:?}/op",
|
|
per
|
|
);
|
|
assert!(
|
|
per.as_millis() < 400,
|
|
"parse_line near MAX_ADDRS regressed: {per:?}/op"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
#[ignore]
|
|
fn bench_parse_targets_many_ranges_near_cap() {
|
|
use std::time::Instant;
|
|
let mut lines = Vec::new();
|
|
let mut total = 0u64;
|
|
let mut b = 0u32;
|
|
while total + 65536 < MAX_ADDRS && b < 200 {
|
|
lines.push(format!("10.{b}.0.0/16"));
|
|
total += 65536;
|
|
b += 1;
|
|
}
|
|
let iters = 5u32;
|
|
let t = Instant::now();
|
|
let mut sink = 0usize;
|
|
for _ in 0..iters {
|
|
sink += parse_targets(&lines).unwrap().len();
|
|
}
|
|
let per = t.elapsed() / iters;
|
|
println!(
|
|
"bench_parse_targets_many_ranges_near_cap: {} lines, {sink} addrs, {:?}/op",
|
|
lines.len(),
|
|
per
|
|
);
|
|
assert!(per.as_millis() < 800, "parse_targets regressed: {per:?}/op");
|
|
}
|
|
|
|
#[test]
|
|
#[ignore]
|
|
fn bench_targets_to_cidrs_large_range() {
|
|
use std::time::Instant;
|
|
let ips = parse_line("10.0.0.1-10.7.255.254").unwrap(); // ~524k addrs, odd start
|
|
let iters = 20u32;
|
|
let t = Instant::now();
|
|
let mut sink = 0usize;
|
|
for _ in 0..iters {
|
|
sink += targets_to_cidrs(&ips).len();
|
|
}
|
|
let per = t.elapsed() / iters;
|
|
println!(
|
|
"bench_targets_to_cidrs_large_range: {} addrs -> {sink} cidrs, {:?}/op",
|
|
ips.len(),
|
|
per
|
|
);
|
|
assert!(
|
|
per.as_millis() < 200,
|
|
"targets_to_cidrs regressed: {per:?}/op"
|
|
);
|
|
}
|
|
|
|
/// Exercise the round-6 background actions through their fake-scan branch:
|
|
/// offline-row emission (start_scan), per-IP refresh (start_refresh),
|
|
/// firmware flash (start_firmware_flash_action), and that a cancelled run
|
|
/// still terminates. ALKANE_FAKE_SCAN is process-global, but no other test
|
|
/// calls these functions, so setting it here only affects this one
|
|
/// (sequential) test; all fake-mode assertions live in a single #[test] so
|
|
/// they never race each other over the env var.
|
|
#[test]
|
|
fn fake_mode_background_actions() {
|
|
use std::sync::mpsc::RecvTimeoutError;
|
|
use std::time::Duration;
|
|
let deadline = Duration::from_secs(5);
|
|
std::env::set_var(FAKE_SCAN_ENV, "1");
|
|
|
|
// start_scan (fake): streams exactly the bench-fleet fixtures, one Row
|
|
// per fixture, and no fabricated rows for empty addresses.
|
|
{
|
|
let h = start_scan(vec!["10.255.1.0/30".into()], DEFAULT_SCAN_TIMEOUT_SECS);
|
|
let mut rows = Vec::new();
|
|
let mut total = 0usize;
|
|
loop {
|
|
match h.rx.recv_timeout(deadline) {
|
|
Ok(ScanMsg::Started { total: t, .. }) => total = t,
|
|
Ok(ScanMsg::Row(r)) => rows.push(r),
|
|
Ok(ScanMsg::Done(_)) => break,
|
|
Ok(_) => {}
|
|
Err(RecvTimeoutError::Timeout) => panic!("fake start_scan hung"),
|
|
Err(RecvTimeoutError::Disconnected) => break,
|
|
}
|
|
}
|
|
let fleet = crate::fixtures::bench_fleet();
|
|
assert_eq!(
|
|
rows.len(),
|
|
fleet.len(),
|
|
"one Row per fixture, no phantom offline rows"
|
|
);
|
|
assert_eq!(total, fleet.len());
|
|
assert!(
|
|
rows.iter().all(|r| r.status() != "offline"),
|
|
"no 'offline' status exists"
|
|
);
|
|
}
|
|
|
|
// start_refresh: a known fixture IP re-reads as a Row, an unknown IP is
|
|
// reported Failed{offline}, and the run ends with Done{ok:1,total:2}.
|
|
{
|
|
let known = "10.255.1.112".to_string(); // an S17 in bench_fleet
|
|
let unknown = "10.0.0.250".to_string();
|
|
let h = start_refresh(vec![known.clone(), unknown.clone()]);
|
|
let (mut rows, mut failed, mut done) = (0usize, 0usize, None);
|
|
loop {
|
|
match h.rx.recv_timeout(deadline) {
|
|
Ok(RefreshMsg::Started { .. }) => {}
|
|
Ok(RefreshMsg::Row(r)) => {
|
|
assert_eq!(r.ip, known);
|
|
rows += 1;
|
|
}
|
|
Ok(RefreshMsg::Failed { ip, detail }) => {
|
|
assert_eq!(ip, unknown);
|
|
assert_eq!(detail, "offline");
|
|
failed += 1;
|
|
}
|
|
Ok(RefreshMsg::Done { ok, total }) => {
|
|
done = Some((ok, total));
|
|
break;
|
|
}
|
|
Err(RecvTimeoutError::Timeout) => panic!("fake start_refresh hung"),
|
|
Err(RecvTimeoutError::Disconnected) => break,
|
|
}
|
|
}
|
|
assert_eq!(rows, 1);
|
|
assert_eq!(failed, 1);
|
|
assert_eq!(done, Some((1, 2)));
|
|
}
|
|
|
|
// start_firmware_flash_action: fake mode reports one simulated success
|
|
// per IP and a matching Done summary.
|
|
{
|
|
let image = FirmwareImage::new("fw.bin".to_string(), vec![0u8; 8]);
|
|
let h = start_firmware_flash_action(
|
|
vec!["10.255.1.166".into(), "10.255.1.149".into()],
|
|
image,
|
|
);
|
|
let (mut results, mut done) = (0usize, None);
|
|
loop {
|
|
match h.rx.recv_timeout(deadline) {
|
|
Ok(ActionMsg::Started { .. }) => {}
|
|
Ok(ActionMsg::Result { ok, detail, .. }) => {
|
|
assert!(ok);
|
|
assert_eq!(detail, "simulated");
|
|
results += 1;
|
|
}
|
|
Ok(ActionMsg::Done { ok, total }) => {
|
|
done = Some((ok, total));
|
|
break;
|
|
}
|
|
Err(RecvTimeoutError::Timeout) => panic!("fake flash hung"),
|
|
Err(RecvTimeoutError::Disconnected) => break,
|
|
}
|
|
}
|
|
assert_eq!(results, 2);
|
|
assert_eq!(done, Some((2, 2)));
|
|
}
|
|
|
|
// Cancellation contract: stopping a run still delivers a terminal Done
|
|
// rather than hanging (the fake branches now honour the cancel flag).
|
|
{
|
|
let big: Vec<String> = (0..200).map(|i| format!("10.9.0.{}", i % 256)).collect();
|
|
let h = start_refresh(big);
|
|
h.stop();
|
|
let mut saw_done = false;
|
|
loop {
|
|
match h.rx.recv_timeout(deadline) {
|
|
Ok(RefreshMsg::Done { .. }) => {
|
|
saw_done = true;
|
|
break;
|
|
}
|
|
Ok(_) => {}
|
|
Err(_) => break,
|
|
}
|
|
}
|
|
assert!(
|
|
saw_done,
|
|
"a cancelled fake refresh must still emit Done, not hang"
|
|
);
|
|
}
|
|
|
|
std::env::remove_var(FAKE_SCAN_ENV);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod live_scan_tests {
|
|
/// Run the real fleet scan over a range and print, per row found, what the
|
|
/// alkane-os menu would offer:
|
|
/// `ALKANE_TEST_SCAN_RANGE=10.255.1.0/24 cargo test -p alkane-gui live_scan -- --ignored --nocapture`
|
|
#[test]
|
|
#[ignore = "needs a reachable miner network (ALKANE_TEST_SCAN_RANGE)"]
|
|
fn live_scan() {
|
|
let Ok(range) = std::env::var("ALKANE_TEST_SCAN_RANGE") else {
|
|
return;
|
|
};
|
|
let handle = super::start_scan(vec![range], 10);
|
|
let mut rows = std::collections::BTreeMap::new();
|
|
while let Ok(msg) = handle.rx.recv() {
|
|
match msg {
|
|
super::ScanMsg::Row(row) => {
|
|
rows.insert(row.ip.clone(), row);
|
|
}
|
|
super::ScanMsg::Done(_) | super::ScanMsg::Failed(_) => break,
|
|
_ => {}
|
|
}
|
|
}
|
|
for row in rows.values() {
|
|
println!(
|
|
"{:<15} brand={:<10} model={:<12} fw={:<8} {:<8} board={:<10} install={} uninstall={}",
|
|
row.ip,
|
|
row.brand,
|
|
row.model,
|
|
row.firmware,
|
|
row.fw_version,
|
|
row.control_board,
|
|
crate::alkane_detect::install_supported(row),
|
|
crate::alkane_detect::is_alkane(row),
|
|
);
|
|
}
|
|
}
|
|
}
|