Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6d286a147 | ||
|
|
3ba3211371 | ||
|
|
c8d5cd71c4 | ||
|
|
c74e8ebaca | ||
|
|
282f0b195c |
Generated
+6
@@ -76,13 +76,19 @@ dependencies = [
|
||||
name = "alkane-gui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"alkane-core",
|
||||
"alkane-discovery",
|
||||
"asic-rs",
|
||||
"base64 0.21.7",
|
||||
"ecb",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"md5crypt",
|
||||
"measurements",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"wx-rs",
|
||||
]
|
||||
|
||||
@@ -19,3 +19,11 @@ tokio = { version = "1", features = ["rt"] }
|
||||
futures-util = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
# WhatsMiner :4028 token-auth access check (round 12 #8b) -- same crates the
|
||||
# vendored asic-rs whatsminer backend uses, so no new versions enter the lock.
|
||||
md5crypt = "1"
|
||||
sha2 = "0.10"
|
||||
aes = "0.8"
|
||||
ecb = "0.1"
|
||||
base64 = "0.21"
|
||||
hex = "0.4"
|
||||
|
||||
@@ -14,10 +14,29 @@
|
||||
//! rather than add an HTTP+digest crate, so the offline/vendored build is
|
||||
//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` =
|
||||
//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover).
|
||||
//!
|
||||
//! WhatsMiner has no such digest-gated web endpoint (it returns a 307 redirect
|
||||
//! for the Antminer paths, so the curl probe always read "indeterminate" and the
|
||||
//! table fell back to a capability guess that marked older units "locked" even
|
||||
//! with the default login -- round 12 #8b). Instead we run the WhatsMiner
|
||||
//! :4028 token handshake: `get_token` (unauthenticated) yields a salt, we derive
|
||||
//! the AES key from the password, and send a NON-mutating encrypted `summary`.
|
||||
//! An encrypted reply means the key (hence password) was accepted -> unlocked;
|
||||
//! a plaintext `enc json load err` means it was rejected -> locked.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use aes::Aes256;
|
||||
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
||||
|
||||
/// Classify a miner's access state from an HTTP status code string (curl's
|
||||
/// `%{http_code}` output). Conservative: anything other than a clear
|
||||
/// authenticated/unauthorized answer is `None`.
|
||||
@@ -35,12 +54,16 @@ fn endpoint(_firmware: &str) -> &'static str {
|
||||
"/cgi-bin/get_miner_conf.cgi"
|
||||
}
|
||||
|
||||
/// Probe one miner's access state over its web API with the given credentials.
|
||||
/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)`
|
||||
/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or
|
||||
/// `Err` only on a failure to run curl at all.
|
||||
pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
|
||||
let url = format!("http://{ip}{}", endpoint(firmware));
|
||||
/// Probe one miner's access state. `make` is the miner brand ("Whatsminer" /
|
||||
/// "Antminer"): WhatsMiner uses the :4028 token handshake, everything else the
|
||||
/// digest-auth web probe. Returns `Ok(Some(true/false))` on a decisive
|
||||
/// lock/unlock answer, `Ok(None)` if indeterminate, `Err` only on a probe that
|
||||
/// could not run at all.
|
||||
pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
|
||||
if make.eq_ignore_ascii_case("whatsminer") {
|
||||
return Ok(probe_whatsminer_access(ip, &whatsminer_password_candidates()));
|
||||
}
|
||||
let url = format!("http://{ip}{}", endpoint(make));
|
||||
let userpass = format!("{user}:{pass}");
|
||||
let mut cmd = Command::new("curl");
|
||||
cmd.args([
|
||||
@@ -96,6 +119,137 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process
|
||||
}
|
||||
}
|
||||
|
||||
/// Passwords to try for a WhatsMiner access check: a user-set per-firmware
|
||||
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
|
||||
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
|
||||
fn whatsminer_password_candidates() -> Vec<String> {
|
||||
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") {
|
||||
if !pass.is_empty() {
|
||||
return vec![pass.clone()];
|
||||
}
|
||||
}
|
||||
vec!["admin".to_string(), "super".to_string()]
|
||||
}
|
||||
|
||||
/// Fetch a WhatsMiner's active fault codes over the unauthenticated :4028
|
||||
/// get_error_code command and format them one per line for the log viewer
|
||||
/// (round 12 #12). Returns None if the miner does not answer.
|
||||
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
|
||||
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
|
||||
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
|
||||
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
|
||||
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
|
||||
match codes {
|
||||
Some(arr) if !arr.is_empty() => {
|
||||
for entry in arr {
|
||||
if let Some(obj) = entry.as_object() {
|
||||
for (code, when) in obj {
|
||||
lines.push(format!(" error {code}: {}", when.as_str().unwrap_or("")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => lines.push(" no active error codes".to_string()),
|
||||
}
|
||||
Some(lines.join("\n"))
|
||||
}
|
||||
|
||||
/// One WhatsMiner :4028 request/response (the miner closes the socket after it
|
||||
/// replies). Returns the NUL-trimmed body.
|
||||
fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String> {
|
||||
let addr: SocketAddr = format!("{ip}:4028")
|
||||
.parse()
|
||||
.map_err(|e| format!("bad address {ip}: {e}"))?;
|
||||
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
|
||||
stream.set_read_timeout(Some(timeout)).ok();
|
||||
stream.set_write_timeout(Some(timeout)).ok();
|
||||
stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if buf.len() > 1 << 20 {
|
||||
break; // cap a runaway response
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
||||
}
|
||||
|
||||
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
|
||||
/// scheme the WhatsMiner btminer API expects (mirrors the vendored asic-rs
|
||||
/// whatsminer v2 backend).
|
||||
fn wm_aes_ecb_enc(pwd_md5: &str, data: &str) -> Option<String> {
|
||||
let key = Sha256::digest(pwd_md5.as_bytes()); // 32 bytes
|
||||
let mut buffer = data.as_bytes().to_vec();
|
||||
while !buffer.len().is_multiple_of(16) {
|
||||
buffer.push(0);
|
||||
}
|
||||
let ct = Aes256EcbEnc::new_from_slice(&key)
|
||||
.ok()?
|
||||
.encrypt_padded_mut::<ZeroPadding>(&mut buffer, data.len())
|
||||
.ok()?;
|
||||
Some(BASE64.encode(ct))
|
||||
}
|
||||
|
||||
/// Check a WhatsMiner's access via the :4028 token handshake, trying each
|
||||
/// candidate password. Returns `Some(false)` (unlocked) on the first password
|
||||
/// the miner accepts, `Some(true)` (locked) if all are rejected, `None` if the
|
||||
/// miner is unreachable or speaks an unexpected dialect. Non-mutating: only
|
||||
/// `get_token` and a read-only `summary` are ever sent.
|
||||
fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
|
||||
let timeout = Duration::from_secs(6);
|
||||
let mut reachable = false;
|
||||
for pass in passwords {
|
||||
// 1. get_token (no auth) -> salt / newsalt / time.
|
||||
let tok_resp = match wm_rpc(ip, "{\"command\":\"get_token\"}", timeout) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
let v: serde_json::Value = match serde_json::from_str(&tok_resp) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return None,
|
||||
};
|
||||
let Some(msg) = v.get("Msg") else { return None };
|
||||
let (Some(salt), Some(newsalt), Some(time)) = (
|
||||
msg.get("salt").and_then(|s| s.as_str()),
|
||||
msg.get("newsalt").and_then(|s| s.as_str()),
|
||||
msg.get("time").and_then(|s| s.as_str()),
|
||||
) else {
|
||||
return None;
|
||||
};
|
||||
reachable = true;
|
||||
// 2. Derive the md5crypt password hash + write-token from the password.
|
||||
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
|
||||
let full = String::from_utf8_lossy(&crypted);
|
||||
let Some(pwd_md5) = full.split('$').nth(3) else { continue };
|
||||
let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
|
||||
let sign_full = String::from_utf8_lossy(&sign_crypted);
|
||||
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
|
||||
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
|
||||
// password) is right the miner replies encrypted; if wrong it returns
|
||||
// a plaintext "enc json load err".
|
||||
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
|
||||
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue };
|
||||
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
|
||||
let resp = match wm_rpc(ip, &payload, timeout) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
if resp.contains("\"enc\"") {
|
||||
return Some(false); // accepted -> unlocked/writable
|
||||
}
|
||||
// rejected -> try the next candidate password
|
||||
}
|
||||
// Reached the miner and every candidate password was rejected -> locked.
|
||||
if reachable { Some(true) } else { None }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -112,4 +266,15 @@ mod tests {
|
||||
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
|
||||
assert_eq!(classify_http_code(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whatsminer_aes_ecb_matches_reference() {
|
||||
// Deterministic vector from the verified btminer scheme: AES-256-ECB over
|
||||
// SHA256(pwd_md5), zero-padded, base64. Guards the WhatsMiner access
|
||||
// handshake crypto (round 12 #8b) without needing a live miner.
|
||||
assert_eq!(
|
||||
wm_aes_ecb_enc("abc123def456", "{\"command\":\"summary\"}").as_deref(),
|
||||
Some("jn5Wru/5hhMtU1IgamxLoUd/YTxaLTxEeiCQxu5pO+Q=")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! is the one place that fans a saved username/password out across the whole
|
||||
//! firmware registry, so `scan`'s callers never have to think about it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
|
||||
@@ -14,6 +15,10 @@ use asic_rs::core::traits::miner::MinerAuth;
|
||||
use crate::scan::config_path;
|
||||
|
||||
pub const CREDENTIALS_FILE: &str = "scan-credentials.txt";
|
||||
/// Per-firmware default logins the operator can override (round 12 #13). One
|
||||
/// `firmware-name<TAB>user<TAB>pass` line per firmware, 0600 like the others.
|
||||
/// Keyed by the firmware registry's Display name (see `firmware_default_creds`).
|
||||
pub const FIRMWARE_CREDENTIALS_FILE: &str = "firmware-credentials.txt";
|
||||
/// SSH login for the control board (used by the PIC probe; distinct from the
|
||||
/// web/API scan credentials above -- miners' SSH root login is usually not the
|
||||
/// same account as the web digest-auth login).
|
||||
@@ -87,16 +92,115 @@ pub fn clear_credentials() -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a `MinerFactory` with the saved credentials (if any) applied as
|
||||
/// discovery auth for every firmware backend, so scans, refreshes, config
|
||||
/// actions, and firmware flashes all authenticate against a non-default
|
||||
/// login the same way. With no saved credentials this is plain `MinerFactory::new()`
|
||||
/// and every backend falls back to its own default auth.
|
||||
/// The stock/default login each firmware ships with, keyed by the firmware
|
||||
/// registry's Display name (round 12 #13). These seed the per-firmware editor and
|
||||
/// let it tell an override from an unchanged default; they mirror the
|
||||
/// `default_auth()` constants in the vendored asic-rs backends (a single
|
||||
/// best-guess per registry entry, since a stock entry can span several backend
|
||||
/// versions). asic-rs does not expose these at the entry level, so they are
|
||||
/// duplicated here; a firmware absent from this table defaults to blank.
|
||||
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
|
||||
&[
|
||||
("AntMiner Stock", "root", "root"),
|
||||
("WhatsMiner Stock", "admin", "admin"),
|
||||
("Braiins", "root", "root"),
|
||||
("VNish", "", "admin"),
|
||||
("LuxOS", "root", "root"),
|
||||
("UMC OS", "", "letmein"),
|
||||
("Marathon", "root", "root"),
|
||||
("VolcMiner Stock", "root", "ltc@dog"),
|
||||
("Elphapex Stock", "root", "root"),
|
||||
("FutureBit Stock", "futurebit", "futurebit123"),
|
||||
("SealMiner Stock", "seal", "seal"),
|
||||
("Auradine Stock", "admin", "admin"),
|
||||
("AvalonMiner Stock", "", ""),
|
||||
("Nerdaxe Stock", "", ""),
|
||||
("Proto Stock", "", ""),
|
||||
("Bitaxe Stock", "", ""),
|
||||
]
|
||||
}
|
||||
|
||||
/// The shipped default login for a firmware, or `("","")` if unknown.
|
||||
pub fn firmware_default_for(name: &str) -> (String, String) {
|
||||
firmware_default_creds()
|
||||
.iter()
|
||||
.find(|(n, _, _)| *n == name)
|
||||
.map(|(_, u, p)| (u.to_string(), p.to_string()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Load the operator's per-firmware credential overrides, keyed by firmware
|
||||
/// Display name. Malformed lines are skipped.
|
||||
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
|
||||
let mut map = HashMap::new();
|
||||
let Ok(s) = std::fs::read_to_string(config_path(FIRMWARE_CREDENTIALS_FILE)) else {
|
||||
return map;
|
||||
};
|
||||
for line in s.lines() {
|
||||
let mut parts = line.splitn(3, '\t');
|
||||
let (Some(name), user) = (parts.next(), parts.next()) else {
|
||||
continue;
|
||||
};
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let user = user.unwrap_or("").to_string();
|
||||
let pass = parts.next().unwrap_or("").to_string();
|
||||
map.insert(name.to_string(), (user, pass));
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
/// Save the per-firmware credential overrides (0600), sorted by name for a
|
||||
/// stable file. An empty map clears the file.
|
||||
pub fn save_firmware_credentials(map: &HashMap<String, (String, String)>) -> std::io::Result<()> {
|
||||
if map.is_empty() {
|
||||
return clear_firmware_credentials();
|
||||
}
|
||||
let p = config_path(FIRMWARE_CREDENTIALS_FILE);
|
||||
if let Some(dir) = p.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(&p)?;
|
||||
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
|
||||
let mut names: Vec<&String> = map.keys().collect();
|
||||
names.sort();
|
||||
for name in names {
|
||||
let (user, pass) = &map[name];
|
||||
f.write_all(format!("{name}\t{user}\t{pass}\n").as_bytes())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the per-firmware overrides file, if any. Not an error if none exists.
|
||||
pub fn clear_firmware_credentials() -> std::io::Result<()> {
|
||||
clear_creds_file(FIRMWARE_CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
/// Build a `MinerFactory` with saved credentials applied as discovery auth.
|
||||
/// Precedence per firmware backend: a per-firmware override (round 12 #13) wins;
|
||||
/// otherwise the single global scan credential (if set) applies to every backend;
|
||||
/// otherwise the backend falls back to its own default auth. With nothing saved
|
||||
/// this is plain `MinerFactory::new()`.
|
||||
pub fn configured_factory() -> MinerFactory {
|
||||
let mut factory = MinerFactory::new();
|
||||
if let Some((user, pass)) = load_credentials() {
|
||||
for fw in asic_rs::factory::default_firmware_registry() {
|
||||
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user.clone(), pass.clone()));
|
||||
let global = load_credentials();
|
||||
let per_fw = load_firmware_credentials();
|
||||
if global.is_none() && per_fw.is_empty() {
|
||||
return factory;
|
||||
}
|
||||
for fw in asic_rs::factory::default_firmware_registry() {
|
||||
let cred = per_fw
|
||||
.get(&fw.to_string())
|
||||
.cloned()
|
||||
.or_else(|| global.clone());
|
||||
if let Some((user, pass)) = cred {
|
||||
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user, pass));
|
||||
}
|
||||
}
|
||||
factory
|
||||
@@ -149,6 +253,35 @@ mod tests {
|
||||
assert_eq!(load_credentials(), None, "cleared -> None");
|
||||
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
|
||||
|
||||
// Per-firmware overrides (round 12 #13). Kept in this same test because
|
||||
// HOME is process-global: a second #[test] mutating it would race under
|
||||
// cargo's default parallel runner.
|
||||
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
|
||||
let mut fw = HashMap::new();
|
||||
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
|
||||
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
|
||||
save_firmware_credentials(&fw).unwrap();
|
||||
// 0600, and it round-trips (an empty username survives the tab format).
|
||||
let fwpath = config_path(FIRMWARE_CREDENTIALS_FILE);
|
||||
assert_eq!(
|
||||
std::fs::metadata(&fwpath).unwrap().permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"per-firmware creds file must be 0600"
|
||||
);
|
||||
let back = load_firmware_credentials();
|
||||
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
|
||||
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
|
||||
assert_eq!(back.len(), 2);
|
||||
// Shipped-default lookup: known firmware resolves, unknown blanks.
|
||||
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
|
||||
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
|
||||
// Overrides + no global still builds a factory.
|
||||
let _ = configured_factory();
|
||||
// Saving an empty map clears the file (no stale overrides linger).
|
||||
save_firmware_credentials(&HashMap::new()).unwrap();
|
||||
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
|
||||
clear_firmware_credentials().unwrap(); // idempotent
|
||||
|
||||
match prev {
|
||||
Some(v) => std::env::set_var("HOME", v),
|
||||
None => std::env::remove_var("HOME"),
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Fetch a miner's log over its firmware API and regex-scan it for useful
|
||||
//! signals (round 12 #12). This is the "logs through API" path the operator
|
||||
//! asked for: where a firmware exposes its log we can read board/PIC lines and
|
||||
//! other metrics without SSH.
|
||||
//!
|
||||
//! Per firmware:
|
||||
//! - VNish (aftermarket Antminer): POST /api/v1/unlock to get a bearer token,
|
||||
//! then GET /api/v1/logs/miner -- the full miner log (PSU init, per-chain
|
||||
//! chip detection, tuning, errors).
|
||||
//! - Stock Antminer: GET /cgi-bin/log.cgi behind digest auth (older models
|
||||
//! such as the Z15 do not serve it -> reported as unavailable).
|
||||
//! - WhatsMiner: the btminer log is not exposed on :4028, but get_error_code
|
||||
//! (unauthenticated) returns the active fault codes, which we format as the
|
||||
//! log view.
|
||||
//!
|
||||
//! We shell out to `curl` (already a dependency of the access probe) so the
|
||||
//! offline/vendored build gains no new crate, and cap the fetched text so a huge
|
||||
//! log never bloats the viewer.
|
||||
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Cap on the log text we keep for display (bytes); the regex summary is still
|
||||
/// computed over everything fetched.
|
||||
const MAX_LOG_BYTES: usize = 256 * 1024;
|
||||
|
||||
/// A fetched log plus the signals a regex pass pulled out of it.
|
||||
pub struct LogScan {
|
||||
/// The (possibly tail-trimmed) log text for the viewer.
|
||||
pub text: String,
|
||||
/// One-line-per-finding summary shown above the log.
|
||||
pub summary: Vec<String>,
|
||||
}
|
||||
|
||||
/// Fetch and scan one miner's log. `brand` is the make ("Antminer"/"Whatsminer"),
|
||||
/// `firmware` the family ("VNish"/"Stock"/...). `vnish_pass`/`wm` creds are used
|
||||
/// where that firmware needs auth. Returns `Err` only when no log could be read.
|
||||
pub fn scan_log(
|
||||
ip: &str,
|
||||
brand: &str,
|
||||
firmware: &str,
|
||||
vnish_pass: &str,
|
||||
antminer_user: &str,
|
||||
antminer_pass: &str,
|
||||
) -> Result<LogScan, String> {
|
||||
let raw = if firmware.eq_ignore_ascii_case("vnish") {
|
||||
fetch_vnish_log(ip, vnish_pass)?
|
||||
} else if brand.eq_ignore_ascii_case("whatsminer") {
|
||||
fetch_whatsminer_errors(ip)?
|
||||
} else {
|
||||
// Stock / other Antminer-family web firmware.
|
||||
fetch_antminer_log(ip, antminer_user, antminer_pass)?
|
||||
};
|
||||
let summary = summarize_log(&raw);
|
||||
Ok(LogScan { text: tail(&raw, MAX_LOG_BYTES), summary })
|
||||
}
|
||||
|
||||
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
|
||||
/// boundary, with a marker when trimmed.
|
||||
fn tail(s: &str, max: usize) -> String {
|
||||
if s.len() <= max {
|
||||
return s.to_string();
|
||||
}
|
||||
let start = s.len() - max;
|
||||
// advance to the next line boundary so we don't cut a line in half
|
||||
let start = s[start..]
|
||||
.find('\n')
|
||||
.map(|i| start + i + 1)
|
||||
.unwrap_or(start);
|
||||
format!("[... earlier log trimmed ...]\n{}", &s[start..])
|
||||
}
|
||||
|
||||
/// Regex-free scan for the high-value signals in a miner log: PIC / hashboard
|
||||
/// firmware lines, per-chain chip detection, and the most recent errors.
|
||||
fn summarize_log(log: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let lc_has = |line: &str, needle: &str| line.to_ascii_lowercase().contains(needle);
|
||||
|
||||
// PIC / hashboard-controller status from the log. Aftermarket firmwares state
|
||||
// it explicitly ("no-PIC miner"); stock boot logs print a PIC version. This
|
||||
// is the log-regex PIC scan the operator asked for (round 12 #12).
|
||||
let pic_lines: Vec<&str> = log.lines().filter(|l| lc_has(l, "pic")).collect();
|
||||
if pic_lines.iter().any(|l| lc_has(l, "no-pic") || lc_has(l, "no pic")) {
|
||||
out.push("PIC: not present (log reports a no-PIC miner)".to_string());
|
||||
} else if let Some(l) = pic_lines
|
||||
.iter()
|
||||
.find(|l| lc_has(l, "version") || lc_has(l, "fw") || lc_has(l, "found"))
|
||||
{
|
||||
out.push(format!("PIC: present -- {}", l.trim()));
|
||||
} else if !pic_lines.is_empty() {
|
||||
out.push(format!("PIC: {} log line(s) mention PIC", pic_lines.len()));
|
||||
for l in pic_lines.iter().take(3) {
|
||||
out.push(format!(" {}", l.trim()));
|
||||
}
|
||||
} else {
|
||||
out.push("PIC: no PIC lines in the log".to_string());
|
||||
}
|
||||
|
||||
// Latest per-chain chip-detection line (the most recent board bring-up).
|
||||
if let Some(l) = log.lines().rev().find(|l| lc_has(l, "chips detected")) {
|
||||
out.push(format!("Chains: {}", l.trim()));
|
||||
}
|
||||
|
||||
// Recent errors (log history, beyond asic-rs's current-message snapshot).
|
||||
// Skip the get_error_code header line (it contains "error" but is not one).
|
||||
let errors: Vec<&str> = log
|
||||
.lines()
|
||||
.rev()
|
||||
.filter(|l| (lc_has(l, "error") || lc_has(l, "fail")) && !lc_has(l, "get_error_code"))
|
||||
.take(3)
|
||||
.collect();
|
||||
if errors.is_empty() {
|
||||
out.push("Errors: none in the log".to_string());
|
||||
} else {
|
||||
out.push(format!("Errors: {} recent", errors.len()));
|
||||
for l in errors {
|
||||
out.push(format!(" {}", l.trim()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// VNish: unlock -> bearer -> the full miner log.
|
||||
fn fetch_vnish_log(ip: &str, pass: &str) -> Result<String, String> {
|
||||
let unlock = curl(&[
|
||||
"-s",
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"9",
|
||||
"-X",
|
||||
"POST",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"-d",
|
||||
&format!("{{\"pw\":\"{pass}\"}}"),
|
||||
&format!("http://{ip}/api/v1/unlock"),
|
||||
])?;
|
||||
let token = serde_json::from_str::<serde_json::Value>(&unlock)
|
||||
.ok()
|
||||
.and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string))
|
||||
.filter(|t| !t.is_empty())
|
||||
.ok_or_else(|| "VNish unlock rejected (check the VNish password in scan credentials)".to_string())?;
|
||||
let log = curl(&[
|
||||
"-s",
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"12",
|
||||
"-H",
|
||||
&format!("Authorization: Bearer {token}"),
|
||||
&format!("http://{ip}/api/v1/logs/miner"),
|
||||
])?;
|
||||
if log.trim().is_empty() {
|
||||
return Err("VNish returned an empty log".to_string());
|
||||
}
|
||||
Ok(log)
|
||||
}
|
||||
|
||||
/// Stock Antminer web log (digest auth). Absent on older models (404).
|
||||
fn fetch_antminer_log(ip: &str, user: &str, pass: &str) -> Result<String, String> {
|
||||
let body = curl(&[
|
||||
"-s",
|
||||
"--digest",
|
||||
"-u",
|
||||
&format!("{user}:{pass}"),
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"12",
|
||||
&format!("http://{ip}/cgi-bin/log.cgi"),
|
||||
])?;
|
||||
if body.contains("404 - Not Found") || body.trim().is_empty() {
|
||||
return Err("this firmware does not expose a log over its web API".to_string());
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// WhatsMiner: format the active error codes (get_error_code, unauthenticated).
|
||||
fn fetch_whatsminer_errors(ip: &str) -> Result<String, String> {
|
||||
let resp = crate::access_probe::whatsminer_get_error_code(ip)
|
||||
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
/// Run curl and return stdout, with a hard wall-clock cap. stdout is drained on a
|
||||
/// separate thread so a large log (hundreds of KB) never deadlocks on a full pipe
|
||||
/// -- the reason a naive "wait then read" times out on the VNish log.
|
||||
fn curl(args: &[&str]) -> Result<String, String> {
|
||||
use std::io::Read;
|
||||
let mut cmd = Command::new("curl");
|
||||
cmd.args(args);
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
cmd.stderr(std::process::Stdio::null());
|
||||
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
|
||||
let mut stdout = child.stdout.take().ok_or("no curl stdout")?;
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = stdout.read_to_end(&mut buf);
|
||||
buf
|
||||
});
|
||||
let timeout = Duration::from_secs(20);
|
||||
let start = std::time::Instant::now();
|
||||
let mut timed_out = false;
|
||||
loop {
|
||||
match child.try_wait().map_err(|e| e.to_string())? {
|
||||
Some(_) => break,
|
||||
None => {
|
||||
if start.elapsed() >= timeout {
|
||||
let _ = child.kill();
|
||||
timed_out = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
}
|
||||
let buf = reader.join().unwrap_or_default();
|
||||
if timed_out && buf.is_empty() {
|
||||
return Err("log fetch timed out".into());
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&buf).into_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summarize_finds_pic_chains_and_errors() {
|
||||
let log = "\
|
||||
[t] INFO: Initializing PSU
|
||||
[t] INFO: chain#1 - 126 chips detected
|
||||
[t] INFO: check PIC on chain 1: version 0x03
|
||||
[t] ERROR: Failed load miner config
|
||||
[t] INFO: chain#2 - 126 chips detected";
|
||||
let s = summarize_log(log);
|
||||
assert!(s.iter().any(|l| l.contains("PIC: present")), "PIC present: {s:?}");
|
||||
assert!(s.iter().any(|l| l.contains("chips detected")), "chains: {s:?}");
|
||||
assert!(s.iter().any(|l| l.contains("Errors: 1")), "errors: {s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarize_detects_no_pic_miner() {
|
||||
let log = "[t] ERROR: This is a no-PIC miner, so all connected chains ...\n[t] INFO: mining";
|
||||
let s = summarize_log(log);
|
||||
assert!(s.iter().any(|l| l.contains("PIC: not present")), "{s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarize_handles_no_pic_lines() {
|
||||
let log = "[t] INFO: chain#1 - 126 chips detected\n[t] INFO: mining";
|
||||
let s = summarize_log(log);
|
||||
assert!(s.iter().any(|l| l.contains("no PIC lines")), "{s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tail_trims_on_line_boundary() {
|
||||
let log = "aaaa\nbbbb\ncccc\n";
|
||||
let t = tail(log, 6);
|
||||
assert!(t.starts_with("[... earlier log trimmed ...]"), "{t}");
|
||||
assert!(t.ends_with("cccc\n"));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
mod access_probe;
|
||||
mod credentials;
|
||||
mod fixtures;
|
||||
mod log_scan;
|
||||
mod model;
|
||||
mod naming;
|
||||
mod pic_probe;
|
||||
@@ -21,6 +22,49 @@ fn main() {
|
||||
std::process::exit(run_selftest());
|
||||
}
|
||||
|
||||
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
|
||||
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
|
||||
// :4028 token check and the Antminer digest check can be verified directly.
|
||||
if let Some(spec) = std::env::var_os("ALKANE_ACCESS_PROBE") {
|
||||
let spec = spec.to_string_lossy();
|
||||
let mut it = spec.split_whitespace();
|
||||
let ip = it.next().unwrap_or("");
|
||||
let make = it.next().unwrap_or("");
|
||||
let (user, pass) = credentials::load_credentials().unwrap_or_default();
|
||||
match access_probe::probe_access(ip, make, &user, &pass) {
|
||||
Ok(Some(true)) => println!("ACCESS {ip} {make}: LOCKED"),
|
||||
Ok(Some(false)) => println!("ACCESS {ip} {make}: UNLOCKED"),
|
||||
Ok(None) => println!("ACCESS {ip} {make}: INDETERMINATE"),
|
||||
Err(e) => println!("ACCESS {ip} {make}: ERROR {e}"),
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
// Headless log-scan check: `ALKANE_LOG_SCAN="<ip> <brand> <firmware>"` fetches
|
||||
// the miner's log over its firmware API and prints the regex summary (round
|
||||
// 12 #12), so the VNish/Antminer/WhatsMiner log paths can be verified without
|
||||
// the GUI.
|
||||
if let Some(spec) = std::env::var_os("ALKANE_LOG_SCAN") {
|
||||
let spec = spec.to_string_lossy();
|
||||
let mut it = spec.split_whitespace();
|
||||
let ip = it.next().unwrap_or("");
|
||||
let brand = it.next().unwrap_or("");
|
||||
let firmware = it.next().unwrap_or("");
|
||||
let (au, ap) = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
|
||||
let vp = credentials::firmware_default_for("VNish").1;
|
||||
let vp = if vp.is_empty() { "admin".to_string() } else { vp };
|
||||
match log_scan::scan_log(ip, brand, firmware, &vp, &au, &ap) {
|
||||
Ok(s) => {
|
||||
println!("LOGSCAN {ip} ({brand}/{firmware}): {} log bytes", s.text.len());
|
||||
for line in &s.summary {
|
||||
println!(" {line}");
|
||||
}
|
||||
}
|
||||
Err(e) => println!("LOGSCAN {ip} ({brand}/{firmware}): ERROR {e}"),
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
// Bootstrap the wx app + main frame (upstream bridge).
|
||||
wx_rs::init_app("alkane-toolkit", 1280, 800);
|
||||
// Follow the system light/dark appearance.
|
||||
|
||||
@@ -568,9 +568,17 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
||||
// on-board SSH/I2C probe -- a separate feature).
|
||||
let pic_present = if model.to_lowercase().contains("nopic") { Some(false) } else { None };
|
||||
// Access: locked/view-only when the miner exposes no writable control at
|
||||
// all, otherwise unlocked. Inferred from capabilities (asic-rs has no direct
|
||||
// lock-state field).
|
||||
let write_locked = Some(!caps.any_control());
|
||||
// all, otherwise unlocked. Inferred from asic-rs capabilities (there is no
|
||||
// direct lock-state field). WhatsMiner is the exception: it is controllable
|
||||
// over its :4028 token API regardless of which commands the matched asic-rs
|
||||
// backend implements, so this heuristic falsely marks older units "locked".
|
||||
// Leave it unknown and let the real access probe (the :4028 token check)
|
||||
// decide (round 12 #8b).
|
||||
let write_locked = if brand.eq_ignore_ascii_case("whatsminer") {
|
||||
None
|
||||
} else {
|
||||
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
|
||||
@@ -1146,11 +1154,11 @@ pub fn start_access_probe(
|
||||
let thread_cancel = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || {
|
||||
for (ip, fw) in targets {
|
||||
for (ip, make) in targets {
|
||||
if thread_cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) {
|
||||
let (locked, error) = match crate::access_probe::probe_access(&ip, &make, &user, &pass) {
|
||||
Ok(v) => (v, None),
|
||||
Err(e) => (None, Some(e)),
|
||||
};
|
||||
|
||||
+218
-4
@@ -56,6 +56,9 @@ const ID_CTX_POWER: i32 = 728;
|
||||
const ID_CTX_RESTART: i32 = 729;
|
||||
const ID_CTX_PIC_PROBE: i32 = 730;
|
||||
const ID_CTX_ACCESS_PROBE: i32 = 731;
|
||||
// View a miner's log fetched over its firmware API (round 12 #12).
|
||||
const ID_CTX_VIEW_LOG: i32 = 734;
|
||||
const ID_LOGVIEW_CLOSE: i32 = 785;
|
||||
// SSH PIC-probe credentials dialog.
|
||||
const ID_PICSSH_OK: i32 = 780;
|
||||
const ID_PICSSH_CANCEL: i32 = 781;
|
||||
@@ -72,6 +75,12 @@ const ID_FLASH_CANCEL: i32 = 745;
|
||||
const ID_CREDS_SAVE: i32 = 746;
|
||||
const ID_CREDS_CLEAR: i32 = 747;
|
||||
const ID_CREDS_CANCEL: i32 = 748;
|
||||
// Per-firmware default-credentials editor (round 12 #13), opened from the scan
|
||||
// credentials dialog.
|
||||
const ID_FWCREDS_OPEN: i32 = 749;
|
||||
const ID_FWCREDS_SAVE: i32 = 750;
|
||||
const ID_FWCREDS_RESET: i32 = 751;
|
||||
const ID_FWCREDS_CANCEL: i32 = 752;
|
||||
// Column-header right-click menu (Excel-style).
|
||||
const ID_HDR_SORT_ASC: i32 = 760;
|
||||
const ID_HDR_SORT_DESC: i32 = 761;
|
||||
@@ -249,6 +258,9 @@ const SHAPE_HASHING: &str = "\u{0004}";
|
||||
const SHAPE_SLOW: &str = "\u{0005}";
|
||||
const SHAPE_NOTHASHING: &str = "\u{0006}";
|
||||
const SHAPE_PAUSED: &str = "\u{0008}";
|
||||
/// Locate-light dot that fades in and out (round 12 #6); distinct from the static
|
||||
/// `SHAPE_DOT` so only the flashing light pulses, not the hashboard health dots.
|
||||
const SHAPE_PULSE_DOT: &str = "\u{000B}";
|
||||
|
||||
/// Register every SVG-backed table-cell icon with the bridge (round 12 #9/#11):
|
||||
/// the access padlocks and the four status KPI icons. Called once at startup;
|
||||
@@ -319,10 +331,11 @@ fn encode_access_icon(pal: &Palette, write_locked: Option<bool>) -> String {
|
||||
}
|
||||
|
||||
/// Light column: a yellow dot while the miner's locate light is flashing, else
|
||||
/// blank (round 11 #10).
|
||||
/// blank (round 11 #10). The dot fades in and out (round 12 #6) via the pulsing
|
||||
/// sentinel, so a flashing light reads as a live pulse rather than a static dot.
|
||||
fn encode_light_dot(pal: &Palette, flashing: Option<bool>) -> String {
|
||||
match flashing {
|
||||
Some(true) => encode_segments(&[(Some(pal.amber), SHAPE_DOT.to_string())]),
|
||||
Some(true) => encode_segments(&[(Some(pal.amber), SHAPE_PULSE_DOT.to_string())]),
|
||||
_ => encode_segments(&[(None, String::new())]),
|
||||
}
|
||||
}
|
||||
@@ -569,11 +582,17 @@ pub struct App {
|
||||
creds_dialog: Widget,
|
||||
creds_user_input: Widget,
|
||||
creds_pass_input: Widget,
|
||||
// Per-firmware default-credentials editor (round 12 #13): the dialog plus one
|
||||
// (firmware name, user field, pass field) per registry firmware.
|
||||
fwcreds_dialog: Widget,
|
||||
fwcreds_rows: Vec<(String, Widget, Widget)>,
|
||||
// Background access (lock-state) probe.
|
||||
access_probe: Option<scan::AccessProbeHandle>,
|
||||
// Background SSH PIC probe + its credentials dialog.
|
||||
pic_probe: Option<scan::PicProbeHandle>,
|
||||
pending_pic_targets: Vec<(String, String)>,
|
||||
// The API log viewer dialog (round 12 #12).
|
||||
logview_dialog: Widget,
|
||||
picssh_dialog: Widget,
|
||||
picssh_user_input: Widget,
|
||||
picssh_pass_input: Widget,
|
||||
@@ -840,9 +859,12 @@ pub fn build(frame: Widget) -> App {
|
||||
creds_dialog: frame,
|
||||
creds_user_input: frame,
|
||||
creds_pass_input: frame,
|
||||
fwcreds_dialog: frame,
|
||||
fwcreds_rows: Vec::new(),
|
||||
access_probe: None,
|
||||
pic_probe: None,
|
||||
pending_pic_targets: Vec::new(),
|
||||
logview_dialog: frame,
|
||||
picssh_dialog: frame,
|
||||
picssh_user_input: frame,
|
||||
picssh_pass_input: frame,
|
||||
@@ -1069,6 +1091,14 @@ impl App {
|
||||
if !sel.is_empty() {
|
||||
t.dvlc_select_rows(&sel);
|
||||
}
|
||||
// Run the locate-light fade timer only while a visible row's light is
|
||||
// actually flashing (round 12 #6), so the table isn't repainted on a timer
|
||||
// when there is nothing to animate.
|
||||
let any_flashing = self
|
||||
.view_idx
|
||||
.iter()
|
||||
.any(|&ri| self.rows[ri].light_flashing == Some(true));
|
||||
wx_rs::set_light_pulse(any_flashing);
|
||||
self.refresh_kpis();
|
||||
}
|
||||
|
||||
@@ -1231,6 +1261,8 @@ impl App {
|
||||
// Real access/lock-state check (credentialed digest GET; uses the saved
|
||||
// scan credentials).
|
||||
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
|
||||
// Fetch and scan this miner's log over its firmware API (round 12 #12).
|
||||
menu.menu_append(ID_CTX_VIEW_LOG, "View log (API)...");
|
||||
// Config actions common to the whole selection (capability
|
||||
// intersection): an action is offered only if every selected miner
|
||||
// supports it.
|
||||
@@ -1330,6 +1362,59 @@ impl App {
|
||||
wx_rs::set_status_text(&msg);
|
||||
}
|
||||
|
||||
/// Fetch the selected miner's log over its firmware API and show it in a
|
||||
/// viewer with a regex summary at the top (round 12 #12). The fetch is a
|
||||
/// short blocking network call (a manual, single-miner action). Returns the
|
||||
/// dialog to show, or None after reporting why no log could be read.
|
||||
fn build_log_view_dialog(&mut self) -> Option<Widget> {
|
||||
let rows = self.selected_rows();
|
||||
let r = rows.first()?;
|
||||
let (ip, brand, firmware) = (r.ip.clone(), r.brand.clone(), r.firmware.clone());
|
||||
// VNish unlock password + Antminer web login: a per-firmware override
|
||||
// (round 12 #13) wins, else the shipped default / saved global creds.
|
||||
let vnish_pass = credentials::load_firmware_credentials()
|
||||
.get("VNish")
|
||||
.map(|(_, p)| p.clone())
|
||||
.filter(|p| !p.is_empty())
|
||||
.unwrap_or_else(|| credentials::firmware_default_for("VNish").1);
|
||||
let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass };
|
||||
let (am_user, am_pass) =
|
||||
credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
|
||||
wx_rs::set_status_text(&format!("fetching log from {ip}..."));
|
||||
let scan = match crate::log_scan::scan_log(&ip, &brand, &firmware, &vnish_pass, &am_user, &am_pass) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
self.set_error_indicator(&format!("log: {e}"));
|
||||
wx_rs::set_status_text(&format!("log fetch failed for {ip}: {e}"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
self.clear_indicator();
|
||||
wx_rs::set_status_text(&format!("{} miners", self.rows.len()));
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}"));
|
||||
let root = Widget::box_sizer(true);
|
||||
let summary = if scan.summary.is_empty() {
|
||||
"(no summary)".to_string()
|
||||
} else {
|
||||
scan.summary.join("\n")
|
||||
};
|
||||
root.add(Widget::static_text(dlg, &summary), 0, sf::BORDER_ALL, 8);
|
||||
let text = Widget::text_ctrl(dlg, true);
|
||||
text.set_min_size(760, 420);
|
||||
text.set_value(&scan.text);
|
||||
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(Widget::button(dlg, "Close", ID_LOGVIEW_CLOSE), 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(800, 540);
|
||||
dlg.fit(dlg);
|
||||
self.logview_dialog = dlg;
|
||||
Some(dlg)
|
||||
}
|
||||
|
||||
/// Build the SSH PIC-probe dialog: captures the selected miners, collects
|
||||
/// SSH credentials (prefilled from the saved SSH login), and on OK runs the
|
||||
/// on-board i2c probe. Returns None (no dialog) if nothing is selected or a
|
||||
@@ -1431,10 +1516,13 @@ impl App {
|
||||
wx_rs::set_status_text("an access check is already running");
|
||||
return;
|
||||
}
|
||||
// Pass the brand (make), not the firmware family: the access probe picks
|
||||
// its strategy by make (WhatsMiner :4028 token vs Antminer web digest),
|
||||
// and "Stock" alone can't tell them apart (round 12 #8b).
|
||||
let targets: Vec<(String, String)> = self
|
||||
.selected_rows()
|
||||
.iter()
|
||||
.map(|r| (r.ip.clone(), r.firmware.clone()))
|
||||
.map(|r| (r.ip.clone(), r.brand.clone()))
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
@@ -1561,6 +1649,8 @@ impl App {
|
||||
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
|
||||
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
|
||||
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
|
||||
ID_CTX_VIEW_LOG => return self.build_log_view_dialog(),
|
||||
ID_LOGVIEW_CLOSE => self.logview_dialog.close(1),
|
||||
ID_CTX_FLASH => {
|
||||
// A flash needs exclusive hardware access; don't even prompt if
|
||||
// any scan / refresh / action is running (re-checked at confirm).
|
||||
@@ -1814,6 +1904,19 @@ impl App {
|
||||
pass_input.set_min_size(200, -1);
|
||||
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
|
||||
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
// The single credential above is applied to every firmware that has no
|
||||
// per-firmware override; the button below edits those per-firmware default
|
||||
// logins (round 12 #13).
|
||||
let fwrow = Widget::box_sizer(false);
|
||||
fwrow.add(
|
||||
Widget::static_text(dlg, "Or set a login per firmware:"),
|
||||
0,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
fwrow.add_stretch(1);
|
||||
fwrow.add(Widget::button(dlg, "Per-firmware defaults...", ID_FWCREDS_OPEN), 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(fwrow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(Widget::button(dlg, "Save", ID_CREDS_SAVE), 0, sf::BORDER_ALL, 6);
|
||||
@@ -1821,7 +1924,7 @@ impl App {
|
||||
btns.add(Widget::button(dlg, "Cancel", ID_CREDS_CANCEL), 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(360, 190);
|
||||
dlg.set_min_size(460, 220);
|
||||
dlg.fit(dlg);
|
||||
self.creds_dialog = dlg;
|
||||
self.creds_user_input = user_input;
|
||||
@@ -1829,6 +1932,113 @@ impl App {
|
||||
dlg
|
||||
}
|
||||
|
||||
/// Build (but do not show) the per-firmware default-credentials editor
|
||||
/// (round 12 #13): one row per firmware in the asic-rs registry, each with a
|
||||
/// username and password field prefilled from the saved override or, failing
|
||||
/// that, the firmware's shipped default. Editing a field away from the default
|
||||
/// makes it an override; setting it back to the default clears the override.
|
||||
fn build_firmware_creds_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, "Per-firmware default logins");
|
||||
let root = Widget::box_sizer(true);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
"Default login used when auto-discovering each firmware. Blank fields mean no login.\nValues left at the firmware's shipped default are not saved as overrides.",
|
||||
),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
8,
|
||||
);
|
||||
// Column headers.
|
||||
let head = Widget::box_sizer(false);
|
||||
let h_fw = Widget::static_text(dlg, "Firmware");
|
||||
h_fw.set_min_size(150, -1);
|
||||
head.add(h_fw, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
let h_user = Widget::static_text(dlg, "Username");
|
||||
h_user.set_min_size(150, -1);
|
||||
head.add(h_user, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
head.add(Widget::static_text(dlg, "Password"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
|
||||
|
||||
let saved = credentials::load_firmware_credentials();
|
||||
let mut rows: Vec<(String, Widget, Widget)> = Vec::new();
|
||||
for fw in asic_rs::factory::default_firmware_registry() {
|
||||
let name = fw.to_string();
|
||||
let (def_user, def_pass) = credentials::firmware_default_for(&name);
|
||||
let (user, pass) = saved
|
||||
.get(&name)
|
||||
.cloned()
|
||||
.unwrap_or((def_user, def_pass));
|
||||
let row = Widget::box_sizer(false);
|
||||
let label = Widget::static_text(dlg, &name);
|
||||
label.set_min_size(150, -1);
|
||||
row.add(label, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
let user_ctrl = Widget::text_ctrl(dlg, false);
|
||||
user_ctrl.set_min_size(150, -1);
|
||||
user_ctrl.set_value(&user);
|
||||
row.add(user_ctrl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
let pass_ctrl = Widget::text_ctrl(dlg, false);
|
||||
pass_ctrl.set_min_size(150, -1);
|
||||
pass_ctrl.set_value(&pass);
|
||||
row.add(pass_ctrl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
|
||||
root.add_sizer(row, 0, sf::EXPAND | sf::BORDER_TOP, 4);
|
||||
rows.push((name, user_ctrl, pass_ctrl));
|
||||
}
|
||||
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(Widget::button(dlg, "Save", ID_FWCREDS_SAVE), 0, sf::BORDER_ALL, 6);
|
||||
btns.add(Widget::button(dlg, "Reset to defaults", ID_FWCREDS_RESET), 0, sf::BORDER_ALL, 6);
|
||||
btns.add(Widget::button(dlg, "Cancel", ID_FWCREDS_CANCEL), 0, sf::BORDER_ALL, 6);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(520, 200);
|
||||
dlg.fit(dlg);
|
||||
self.fwcreds_dialog = dlg;
|
||||
self.fwcreds_rows = rows;
|
||||
dlg
|
||||
}
|
||||
|
||||
/// Persist the per-firmware editor: a row that differs from the firmware's
|
||||
/// shipped default becomes an override; a row equal to the default clears it.
|
||||
fn apply_firmware_creds_save(&mut self) {
|
||||
let mut map: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
|
||||
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
|
||||
let user = user_ctrl.get_value();
|
||||
let pass = pass_ctrl.get_value();
|
||||
let default = credentials::firmware_default_for(name);
|
||||
if (user.clone(), pass.clone()) != default {
|
||||
map.insert(name.clone(), (user, pass));
|
||||
}
|
||||
}
|
||||
match credentials::save_firmware_credentials(&map) {
|
||||
Ok(()) => {
|
||||
self.fwcreds_dialog.close(1);
|
||||
let n = map.len();
|
||||
wx_rs::set_status_text(&format!(
|
||||
"per-firmware logins saved ({n} override{})",
|
||||
if n == 1 { "" } else { "s" }
|
||||
));
|
||||
}
|
||||
Err(e) => wx_rs::set_status_text(&format!("failed to save per-firmware logins: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset every editor row to the firmware's shipped default and clear the
|
||||
/// saved overrides.
|
||||
fn apply_firmware_creds_reset(&mut self) {
|
||||
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
|
||||
let (user, pass) = credentials::firmware_default_for(name);
|
||||
user_ctrl.set_value(&user);
|
||||
pass_ctrl.set_value(&pass);
|
||||
}
|
||||
match credentials::clear_firmware_credentials() {
|
||||
Ok(()) => wx_rs::set_status_text("per-firmware logins reset to defaults"),
|
||||
Err(e) => wx_rs::set_status_text(&format!("failed to clear per-firmware logins: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_creds_save(&mut self) {
|
||||
let user = self.creds_user_input.get_value();
|
||||
let mut pass = self.creds_pass_input.get_value();
|
||||
@@ -2915,6 +3125,10 @@ impl App {
|
||||
ID_CREDS_SAVE => self.apply_creds_save(),
|
||||
ID_CREDS_CLEAR => self.apply_creds_clear(),
|
||||
ID_CREDS_CANCEL => self.creds_dialog.close(0),
|
||||
ID_FWCREDS_OPEN => return Some(self.build_firmware_creds_dialog()),
|
||||
ID_FWCREDS_SAVE => self.apply_firmware_creds_save(),
|
||||
ID_FWCREDS_RESET => self.apply_firmware_creds_reset(),
|
||||
ID_FWCREDS_CANCEL => self.fwcreds_dialog.close(0),
|
||||
ID_KPI_HASHING => self.toggle_kpi_filter("hashing"),
|
||||
ID_KPI_SLOW => self.toggle_kpi_filter("slow"),
|
||||
ID_KPI_NOT => self.toggle_kpi_filter("not hashing"),
|
||||
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
Subject: [PATCH 0006] antminer: route old models to the right backend + read the Z15 control board
|
||||
|
||||
Round-12 #10. Three fixes for stock Antminer Z15/Z15J (fw 2020), all verified
|
||||
live on 10.5.1.x:
|
||||
|
||||
1. Backend routing: the version detector only read summary.cgi, which older
|
||||
models (Z15) do not serve (404) -> version None -> AntMiner::new defaulted to
|
||||
the newest backend, which mis-parsed the miner (empty control board, no
|
||||
expected hashrate/wattage/fans). Fall back to the cgminer :4028 `version`
|
||||
RPC's CompileTime so the Z15 (2020) routes to the v2020 backend.
|
||||
|
||||
2. Control board "read, not guess": the Z15 has no miner_type.cgi, so its
|
||||
control-board subtype is unreadable there. Read the kernel build string from
|
||||
get_system_info.cgi instead ("Linux 4.6.0-xilinx-..." -> Xilinx); the
|
||||
ControlBoardVersion field now carries both the subtype and the kernel, and the
|
||||
parser prefers the subtype and falls back to the kernel marker.
|
||||
|
||||
3. Malformed cgminer stats: the Z15 emits a stats array whose objects are not
|
||||
comma-separated (`...}{"STATS":0...`), invalid JSON that serde rejected,
|
||||
dropping the whole stats command and every stats-derived field. Insert the
|
||||
missing separators before parsing (a no-op on well-formed responses); this
|
||||
restores expected hashrate, fans, hashboards and uptime. The expected
|
||||
hashrate also gets the same Equihash Sol/s reinterpretation as the realtime
|
||||
rate, so both read on one scale (e.g. 144k / 320k) instead of the expected
|
||||
reading ~1e6x larger.
|
||||
|
||||
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
index 5b9f77b3..a02bdf9d 100644
|
||||
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
@@ -434,14 +434,29 @@ impl GetDataLocations for AntMinerV2020 {
|
||||
tag: None,
|
||||
},
|
||||
)],
|
||||
- DataField::ControlBoardVersion => vec![(
|
||||
- WEB_MINER_TYPE,
|
||||
- DataExtractor {
|
||||
- func: get_by_pointer,
|
||||
- key: Some("/subtype"),
|
||||
- tag: None,
|
||||
- },
|
||||
- )],
|
||||
+ // Prefer the explicit control-board subtype from miner_type.cgi, but
|
||||
+ // carry the kernel build string from get_system_info.cgi too: older
|
||||
+ // models (e.g. Z15/Z15J) have no miner_type.cgi, and their kernel
|
||||
+ // string ("...-xilinx-...") names the control board we can actually
|
||||
+ // read instead of guessing from the model (round 12 #10).
|
||||
+ DataField::ControlBoardVersion => vec![
|
||||
+ (
|
||||
+ WEB_MINER_TYPE,
|
||||
+ DataExtractor {
|
||||
+ func: get_by_pointer,
|
||||
+ key: Some("/subtype"),
|
||||
+ tag: Some("subtype"),
|
||||
+ },
|
||||
+ ),
|
||||
+ (
|
||||
+ WEB_SYSTEM_INFO,
|
||||
+ DataExtractor {
|
||||
+ func: get_by_pointer,
|
||||
+ key: Some("/system_kernel_version"),
|
||||
+ tag: Some("kernel"),
|
||||
+ },
|
||||
+ ),
|
||||
+ ],
|
||||
// cgminer names its summary keys after the unit they are in —
|
||||
// `GHS 5s` on SHA-256 models, `MHS 5s` on Scrypt ones — so keep
|
||||
// the whole entry and let the parse pick the key that is present.
|
||||
@@ -748,16 +763,33 @@ impl GetExpectedHashrate for AntMinerV2020 {
|
||||
let value = field?
|
||||
.pointer("/hashrate")
|
||||
.and_then(Self::parse_f64_field)?;
|
||||
+ // Equihash miners (Z15/Z15J) report `total_rateideal` as a Sol/s count in
|
||||
+ // the same (mislabelled) scale as the realtime "GHS" rate, so reinterpret
|
||||
+ // it as the base Hash unit -- matching parse_hashrate. Without this,
|
||||
+ // expected reads ~1e6x larger than realtime and the realtime figure looks
|
||||
+ // absent next to it (round 12 #10).
|
||||
+ let is_equihash = self.device_info.algo == HashAlgorithm::Equihash
|
||||
+ || self
|
||||
+ .device_info
|
||||
+ .model
|
||||
+ .to_string()
|
||||
+ .to_ascii_uppercase()
|
||||
+ .contains("Z15");
|
||||
+ let unit = if is_equihash {
|
||||
+ HashRateUnit::Hash
|
||||
+ } else {
|
||||
+ // `total_rateideal` does not name its own scale, so take it from
|
||||
+ // STATS' `rate_unit` (`"GH"` / `"MH"`).
|
||||
+ field
|
||||
+ .and_then(|v| v.pointer("/unit"))
|
||||
+ .and_then(|v| v.as_str())
|
||||
+ .and_then(|s| HashRateUnit::from_str(s).ok())
|
||||
+ .unwrap_or(HashRateUnit::GigaHash)
|
||||
+ };
|
||||
Some(
|
||||
HashRate {
|
||||
value,
|
||||
- // `total_rateideal` does not name its own scale, so take it
|
||||
- // from STATS' `rate_unit` (`"GH"` / `"MH"`).
|
||||
- unit: field
|
||||
- .and_then(|v| v.pointer("/unit"))
|
||||
- .and_then(|v| v.as_str())
|
||||
- .and_then(|s| HashRateUnit::from_str(s).ok())
|
||||
- .unwrap_or(HashRateUnit::GigaHash),
|
||||
+ unit,
|
||||
algo: self.device_info.algo,
|
||||
}
|
||||
.as_unit(HashRateUnit::default()),
|
||||
@@ -888,11 +920,34 @@ impl GetControlBoardVersion for AntMinerV2020 {
|
||||
&self,
|
||||
data: &HashMap<DataField, Value>,
|
||||
) -> Option<MinerControlBoard> {
|
||||
- let cb_type = data.extract::<String>(DataField::ControlBoardVersion)?;
|
||||
- match cb_type.as_str() {
|
||||
- s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
|
||||
- _ => AntMinerControlBoard::parse(cb_type.split("_").collect::<Vec<&str>>()[0])
|
||||
- .map(|cb| cb.into()),
|
||||
+ let field = data.get(&DataField::ControlBoardVersion)?;
|
||||
+ // Explicit control-board subtype (miner_type.cgi) wins when present.
|
||||
+ let subtype = field
|
||||
+ .pointer("/subtype")
|
||||
+ .and_then(|v| v.as_str())
|
||||
+ .unwrap_or("");
|
||||
+ if !subtype.is_empty() {
|
||||
+ return match subtype {
|
||||
+ s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
|
||||
+ _ => AntMinerControlBoard::parse(subtype.split('_').next().unwrap_or(subtype))
|
||||
+ .map(|cb| cb.into()),
|
||||
+ };
|
||||
+ }
|
||||
+ // No subtype (older models): read the control board from the kernel build
|
||||
+ // string instead of guessing from the model (round 12 #10). Bitmain names
|
||||
+ // the SoC in the kernel version, e.g. "Linux 4.6.0-xilinx-..." (Z15) or an
|
||||
+ // AMLogic/Meson kernel on newer AMLogic boards.
|
||||
+ let kernel = field
|
||||
+ .pointer("/kernel")
|
||||
+ .and_then(|v| v.as_str())
|
||||
+ .unwrap_or("")
|
||||
+ .to_ascii_lowercase();
|
||||
+ if kernel.contains("xilinx") || kernel.contains("zynq") {
|
||||
+ Some(AntMinerControlBoard::Xilinx.into())
|
||||
+ } else if kernel.contains("aml") || kernel.contains("meson") {
|
||||
+ Some(AntMinerControlBoard::AMLogic.into())
|
||||
+ } else {
|
||||
+ None
|
||||
}
|
||||
}
|
||||
}
|
||||
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
|
||||
index 23962f35..52232c1f 100644
|
||||
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
|
||||
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
|
||||
@@ -71,7 +71,17 @@ impl AntMinerRPCAPI {
|
||||
read_stream_response(&mut stream, DEFAULT_RPC_TIMEOUT).await
|
||||
};
|
||||
let response = response?;
|
||||
- self.parse_rpc_result(&response)
|
||||
+ self.parse_rpc_result(&Self::sanitize_cgminer(&response))
|
||||
+ }
|
||||
+
|
||||
+ /// Antminer's cgminer `stats` sometimes emits an array whose objects are not
|
||||
+ /// comma-separated (`...}{"STATS":0,...` on the Z15/Z15J), which is invalid
|
||||
+ /// JSON that serde rejects -- dropping the whole stats command and with it
|
||||
+ /// every stats-derived field (expected hashrate, wattage, fans, hashboards,
|
||||
+ /// uptime). Insert the missing separators. Well-formed JSON never contains an
|
||||
+ /// unseparated `}{`, so this is a no-op on valid responses (round 12 #10).
|
||||
+ fn sanitize_cgminer(response: &str) -> String {
|
||||
+ response.replace("}{", "},{")
|
||||
}
|
||||
|
||||
fn parse_rpc_result(&self, response: &str) -> anyhow::Result<Value> {
|
||||
diff --git a/vendor/asic-rs-firmwares-antminer/src/firmware.rs b/vendor/asic-rs-firmwares-antminer/src/firmware.rs
|
||||
index fce5e8ff..46abbc9d 100644
|
||||
--- a/vendor/asic-rs-firmwares-antminer/src/firmware.rs
|
||||
+++ b/vendor/asic-rs-firmwares-antminer/src/firmware.rs
|
||||
@@ -142,18 +142,9 @@ async fn get_model_with_auth(
|
||||
}
|
||||
}
|
||||
|
||||
-/// Fetch the firmware version from a miner using digest auth.
|
||||
-async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
|
||||
- let client = build_discovery_client().ok()?;
|
||||
- let data: Response = client
|
||||
- .get(format!("http://{ip}/cgi-bin/summary.cgi"))
|
||||
- .send_digest_auth((auth.username(), auth.password()))
|
||||
- .await
|
||||
- .ok()?;
|
||||
-
|
||||
- let json_data = data.json::<serde_json::Value>().await.ok()?;
|
||||
- let fw_version = json_data["INFO"]["CompileTime"].as_str().unwrap_or("");
|
||||
-
|
||||
+/// Parse an Antminer cgminer `CompileTime` string ("Mon Dec 14 18:01:42 CST
|
||||
+/// 2020") into a date-based semver (year.month.day) used to pick the backend.
|
||||
+fn parse_antminer_compile_time(fw_version: &str) -> Option<semver::Version> {
|
||||
let cleaned: String = {
|
||||
let mut parts: Vec<&str> = fw_version.split_whitespace().collect();
|
||||
if parts.len() > 4 {
|
||||
@@ -161,9 +152,7 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
|
||||
}
|
||||
parts.join(" ")
|
||||
};
|
||||
-
|
||||
let dt = NaiveDateTime::parse_from_str(&cleaned, "%a %b %e %H:%M:%S %Y").ok()?;
|
||||
-
|
||||
Some(semver::Version::new(
|
||||
dt.year() as u64,
|
||||
dt.month() as u64,
|
||||
@@ -171,6 +160,34 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
|
||||
))
|
||||
}
|
||||
|
||||
+/// Fetch the firmware version (as a date-based semver) to pick the backend.
|
||||
+async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
|
||||
+ // Newer Antminers expose the firmware CompileTime via summary.cgi.
|
||||
+ if let Ok(client) = build_discovery_client()
|
||||
+ && let Ok(data) = client
|
||||
+ .get(format!("http://{ip}/cgi-bin/summary.cgi"))
|
||||
+ .send_digest_auth((auth.username(), auth.password()))
|
||||
+ .await
|
||||
+ && let Ok(json_data) = data.json::<serde_json::Value>().await
|
||||
+ && let Some(v) =
|
||||
+ parse_antminer_compile_time(json_data["INFO"]["CompileTime"].as_str().unwrap_or(""))
|
||||
+ {
|
||||
+ return Some(v);
|
||||
+ }
|
||||
+
|
||||
+ // Older models (e.g. Z15/Z15J) have no summary.cgi, so summary-based version
|
||||
+ // detection returns nothing and the miner would default to the newest
|
||||
+ // backend and be mis-parsed. Fall back to the cgminer :4028 `version` RPC,
|
||||
+ // which still reports the CompileTime, so the right (older) backend is picked
|
||||
+ // (round 12 #10).
|
||||
+ let rpc = asic_rs_core::util::send_rpc_command(&ip, "version").await?;
|
||||
+ parse_antminer_compile_time(
|
||||
+ rpc.pointer("/VERSION/0/CompileTime")
|
||||
+ .and_then(|v| v.as_str())
|
||||
+ .unwrap_or(""),
|
||||
+ )
|
||||
+}
|
||||
+
|
||||
#[async_trait]
|
||||
impl MinerFirmware for AntMinerStockFirmware {
|
||||
/// Uses default credentials. For custom credentials, use `build_miner`
|
||||
+9
-1
@@ -10,7 +10,7 @@
|
||||
+pub use widgets::*;
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -0,0 +1,806 @@
|
||||
@@ -0,0 +1,814 @@
|
||||
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
|
||||
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
|
||||
+// wxWidgets object tree (parents own children; nothing to free in Rust).
|
||||
@@ -118,6 +118,7 @@
|
||||
+ pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
|
||||
+ pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
|
||||
+ pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
|
||||
+ pub fn wxbr_set_light_pulse(on: c_int);
|
||||
+ pub fn wxbr_bind_sys_colour(win: *mut c_void);
|
||||
+ pub fn wxbr_destroy(win: *mut c_void);
|
||||
+ pub fn wxbr_destroy_children(win: *mut c_void);
|
||||
@@ -225,6 +226,13 @@
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Start (or stop) the locate-light dot fade animation. Call with `true` while at
|
||||
+/// least one miner's locate light is flashing so the table repaint timer only
|
||||
+/// runs when there is a pulsing dot to animate (round 12 #6).
|
||||
+pub fn set_light_pulse(on: bool) {
|
||||
+ unsafe { notsafe::wxbr_set_light_pulse(on as c_int) }
|
||||
+}
|
||||
+
|
||||
+/// Open a URL in the system default browser. Returns true on success.
|
||||
+pub fn launch_browser(url: &str) -> bool {
|
||||
+ let c = CString::new(url).unwrap_or_default();
|
||||
|
||||
+81
-6
@@ -1,6 +1,6 @@
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -0,0 +1,1547 @@
|
||||
@@ -0,0 +1,1622 @@
|
||||
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
|
||||
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
|
||||
+// render-callback bridge (which is kept untouched).
|
||||
@@ -37,6 +37,7 @@
|
||||
+#include <wx/statusbr.h>
|
||||
+#include <cstring>
|
||||
+#include <cstdio>
|
||||
+#include <cmath>
|
||||
+#include <map>
|
||||
+#include <vector>
|
||||
+#ifdef __WXGTK__
|
||||
@@ -167,20 +168,71 @@
|
||||
+const wxUniChar SHAPE_SLOW = 0x05; // turtle (slow)
|
||||
+const wxUniChar SHAPE_NOTHASHING = 0x06; // cracked wine glass (not hashing)
|
||||
+const wxUniChar SHAPE_PAUSED = 0x08; // otter (paused)
|
||||
+const wxUniChar SHAPE_PULSE_DOT = 0x0B; // locate-light dot that fades in/out (round 12 #6)
|
||||
+const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies
|
||||
+
|
||||
+// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
|
||||
+// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
|
||||
+// the timer can invalidate exactly it.
|
||||
+double g_pulse_phase = 0.0;
|
||||
+wxDataViewCtrl* g_pulse_target = nullptr;
|
||||
+
|
||||
+bool IsShapeSentinel(const wxString& s, wxUniChar& out) {
|
||||
+ if (s.length() != 1) return false;
|
||||
+ wxUniChar c = s[0];
|
||||
+ if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK ||
|
||||
+ c == SHAPE_HASHING || c == SHAPE_SLOW || c == SHAPE_NOTHASHING ||
|
||||
+ c == SHAPE_PAUSED) {
|
||||
+ c == SHAPE_PAUSED || c == SHAPE_PULSE_DOT) {
|
||||
+ out = c;
|
||||
+ return true;
|
||||
+ }
|
||||
+ return false;
|
||||
+}
|
||||
+
|
||||
+// Blend `fg` toward `bg` by alpha (1.0 = fully fg), used to fade the locate dot.
|
||||
+wxColour BlendColour(const wxColour& bg, const wxColour& fg, double a) {
|
||||
+ auto mix = [a](unsigned char b, unsigned char f) {
|
||||
+ double v = (double)b * (1.0 - a) + (double)f * a + 0.5;
|
||||
+ if (v < 0) v = 0;
|
||||
+ if (v > 255) v = 255;
|
||||
+ return (unsigned char)v;
|
||||
+ };
|
||||
+ return wxColour(mix(bg.Red(), fg.Red()), mix(bg.Green(), fg.Green()), mix(bg.Blue(), fg.Blue()));
|
||||
+}
|
||||
+
|
||||
+// Drives the locate-light dot's fade (round 12 #6): while running it advances the
|
||||
+// phase and repaints the treeview so the SHAPE_PULSE_DOT cells re-render at the
|
||||
+// new opacity. Runs only while at least one locate light is flashing.
|
||||
+class PulseTimer : public wxTimer {
|
||||
+ public:
|
||||
+ void Notify() override {
|
||||
+ g_pulse_phase += 0.4; // ~1.6 s cycle at the 100 ms tick below
|
||||
+ if (!g_pulse_target) return;
|
||||
+ // A plain Refresh() does not re-invoke the custom cell renderer under wxGTK
|
||||
+ // (GtkTreeView caches rendered cells); emitting a row change does, so the
|
||||
+ // SHAPE_PULSE_DOT cells re-render at the new phase. The timer only runs while
|
||||
+ // a light is flashing, so touching every row here is cheap.
|
||||
+ AttrListStore* store = dynamic_cast<AttrListStore*>(g_pulse_target->GetModel());
|
||||
+ if (store) {
|
||||
+ unsigned int n = store->GetItemCount();
|
||||
+ for (unsigned int r = 0; r < n; r++) store->RowChanged(r);
|
||||
+ } else {
|
||||
+ g_pulse_target->Refresh();
|
||||
+ }
|
||||
+ }
|
||||
+};
|
||||
+PulseTimer* g_pulse_timer = nullptr;
|
||||
+
|
||||
+void SetLightPulse(bool on) {
|
||||
+ if (!g_pulse_timer) g_pulse_timer = new PulseTimer();
|
||||
+ if (on) {
|
||||
+ if (!g_pulse_timer->IsRunning()) g_pulse_timer->Start(100);
|
||||
+ } else {
|
||||
+ g_pulse_timer->Stop();
|
||||
+ if (g_pulse_target) g_pulse_target->Refresh();
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+// Registry of SVG-backed shape icons (round 12 #9 access padlocks, #11 status
|
||||
+// icons). The Rust side registers a raw SVG (with its viewBox dims for aspect)
|
||||
+// per sentinel; DrawShape recolours it to the segment colour, rasterises once
|
||||
@@ -225,7 +277,9 @@
|
||||
+
|
||||
+// Draw one shape sentinel centred at x; returns the horizontal space it used
|
||||
+// (SHAPE_ADVANCE for the vector shapes, the icon width for a wider SVG icon).
|
||||
+int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const wxColour& colour) {
|
||||
+// `bg` is the cell background the shape sits on, used to fade the pulsing dot.
|
||||
+int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
+ const wxColour& colour, const wxColour& bg) {
|
||||
+ int cy = cell.y + cell.height / 2;
|
||||
+ // SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the
|
||||
+ // segment colour, rasterise (cached), and draw centred in its slot.
|
||||
@@ -243,9 +297,15 @@
|
||||
+ }
|
||||
+ }
|
||||
+ int cx = x + SHAPE_ADVANCE / 2;
|
||||
+ if (shape == SHAPE_DOT) {
|
||||
+ if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
|
||||
+ wxColour fill = colour;
|
||||
+ if (shape == SHAPE_PULSE_DOT) {
|
||||
+ // Fade between ~0.3 and 1.0 opacity over a ~1.6 s cycle (round 12 #6).
|
||||
+ double a = 0.3 + 0.7 * (0.5 + 0.5 * std::sin(g_pulse_phase));
|
||||
+ fill = BlendColour(bg, colour, a);
|
||||
+ }
|
||||
+ dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
+ dc->SetBrush(wxBrush(colour));
|
||||
+ dc->SetBrush(wxBrush(fill));
|
||||
+ dc->DrawCircle(cx, cy, 4);
|
||||
+ return SHAPE_ADVANCE;
|
||||
+ }
|
||||
@@ -344,7 +404,16 @@
|
||||
+ // selection highlight (round 11 #10/#13).
|
||||
+ wxUniChar shape;
|
||||
+ if (IsShapeSentinel(seg.text, shape)) {
|
||||
+ x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain);
|
||||
+ // Background the shape sits on, so the pulsing locate dot fades toward it.
|
||||
+ wxColour cellbg;
|
||||
+ if (selected) {
|
||||
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
|
||||
+ } else if (GetAttr().HasBackgroundColour()) {
|
||||
+ cellbg = GetAttr().GetBackgroundColour();
|
||||
+ } else {
|
||||
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
+ }
|
||||
+ x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
+ continue;
|
||||
+ }
|
||||
+ if (seg.text.IsEmpty()) continue;
|
||||
@@ -768,6 +837,7 @@
|
||||
+ AttrListStore* store = new AttrListStore();
|
||||
+ dv->AssociateModel(store);
|
||||
+ store->DecRef(); // the control owns a reference now
|
||||
+ g_pulse_target = dv; // the locate-dot pulse timer repaints this control
|
||||
+ dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
|
||||
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
+ });
|
||||
@@ -1468,6 +1538,11 @@
|
||||
+ g_shape_bmp_cache.clear();
|
||||
+}
|
||||
+
|
||||
+// Start/stop the locate-light dot fade animation (round 12 #6). The Rust side
|
||||
+// calls this after each refresh with whether any miner's locate light is
|
||||
+// flashing, so the repaint timer only runs when there is a dot to animate.
|
||||
+void wxbr_set_light_pulse(int on) { SetLightPulse(on != 0); }
|
||||
+
|
||||
+// ---- live theme changes -----------------------------------------------------
|
||||
+
|
||||
+// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
#include <wx/statusbr.h>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#ifdef __WXGTK__
|
||||
@@ -164,20 +165,71 @@ const wxUniChar SHAPE_HASHING = 0x04; // rabbit (hashing)
|
||||
const wxUniChar SHAPE_SLOW = 0x05; // turtle (slow)
|
||||
const wxUniChar SHAPE_NOTHASHING = 0x06; // cracked wine glass (not hashing)
|
||||
const wxUniChar SHAPE_PAUSED = 0x08; // otter (paused)
|
||||
const wxUniChar SHAPE_PULSE_DOT = 0x0B; // locate-light dot that fades in/out (round 12 #6)
|
||||
const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies
|
||||
|
||||
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
|
||||
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
|
||||
// the timer can invalidate exactly it.
|
||||
double g_pulse_phase = 0.0;
|
||||
wxDataViewCtrl* g_pulse_target = nullptr;
|
||||
|
||||
bool IsShapeSentinel(const wxString& s, wxUniChar& out) {
|
||||
if (s.length() != 1) return false;
|
||||
wxUniChar c = s[0];
|
||||
if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK ||
|
||||
c == SHAPE_HASHING || c == SHAPE_SLOW || c == SHAPE_NOTHASHING ||
|
||||
c == SHAPE_PAUSED) {
|
||||
c == SHAPE_PAUSED || c == SHAPE_PULSE_DOT) {
|
||||
out = c;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Blend `fg` toward `bg` by alpha (1.0 = fully fg), used to fade the locate dot.
|
||||
wxColour BlendColour(const wxColour& bg, const wxColour& fg, double a) {
|
||||
auto mix = [a](unsigned char b, unsigned char f) {
|
||||
double v = (double)b * (1.0 - a) + (double)f * a + 0.5;
|
||||
if (v < 0) v = 0;
|
||||
if (v > 255) v = 255;
|
||||
return (unsigned char)v;
|
||||
};
|
||||
return wxColour(mix(bg.Red(), fg.Red()), mix(bg.Green(), fg.Green()), mix(bg.Blue(), fg.Blue()));
|
||||
}
|
||||
|
||||
// Drives the locate-light dot's fade (round 12 #6): while running it advances the
|
||||
// phase and repaints the treeview so the SHAPE_PULSE_DOT cells re-render at the
|
||||
// new opacity. Runs only while at least one locate light is flashing.
|
||||
class PulseTimer : public wxTimer {
|
||||
public:
|
||||
void Notify() override {
|
||||
g_pulse_phase += 0.4; // ~1.6 s cycle at the 100 ms tick below
|
||||
if (!g_pulse_target) return;
|
||||
// A plain Refresh() does not re-invoke the custom cell renderer under wxGTK
|
||||
// (GtkTreeView caches rendered cells); emitting a row change does, so the
|
||||
// SHAPE_PULSE_DOT cells re-render at the new phase. The timer only runs while
|
||||
// a light is flashing, so touching every row here is cheap.
|
||||
AttrListStore* store = dynamic_cast<AttrListStore*>(g_pulse_target->GetModel());
|
||||
if (store) {
|
||||
unsigned int n = store->GetItemCount();
|
||||
for (unsigned int r = 0; r < n; r++) store->RowChanged(r);
|
||||
} else {
|
||||
g_pulse_target->Refresh();
|
||||
}
|
||||
}
|
||||
};
|
||||
PulseTimer* g_pulse_timer = nullptr;
|
||||
|
||||
void SetLightPulse(bool on) {
|
||||
if (!g_pulse_timer) g_pulse_timer = new PulseTimer();
|
||||
if (on) {
|
||||
if (!g_pulse_timer->IsRunning()) g_pulse_timer->Start(100);
|
||||
} else {
|
||||
g_pulse_timer->Stop();
|
||||
if (g_pulse_target) g_pulse_target->Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
// Registry of SVG-backed shape icons (round 12 #9 access padlocks, #11 status
|
||||
// icons). The Rust side registers a raw SVG (with its viewBox dims for aspect)
|
||||
// per sentinel; DrawShape recolours it to the segment colour, rasterises once
|
||||
@@ -222,7 +274,9 @@ const wxBitmap& ShapeBitmap(wxUniChar shape, const ShapeSvg& sv, const wxColour&
|
||||
|
||||
// Draw one shape sentinel centred at x; returns the horizontal space it used
|
||||
// (SHAPE_ADVANCE for the vector shapes, the icon width for a wider SVG icon).
|
||||
int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const wxColour& colour) {
|
||||
// `bg` is the cell background the shape sits on, used to fade the pulsing dot.
|
||||
int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
|
||||
const wxColour& colour, const wxColour& bg) {
|
||||
int cy = cell.y + cell.height / 2;
|
||||
// SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the
|
||||
// segment colour, rasterise (cached), and draw centred in its slot.
|
||||
@@ -240,9 +294,15 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const wx
|
||||
}
|
||||
}
|
||||
int cx = x + SHAPE_ADVANCE / 2;
|
||||
if (shape == SHAPE_DOT) {
|
||||
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
|
||||
wxColour fill = colour;
|
||||
if (shape == SHAPE_PULSE_DOT) {
|
||||
// Fade between ~0.3 and 1.0 opacity over a ~1.6 s cycle (round 12 #6).
|
||||
double a = 0.3 + 0.7 * (0.5 + 0.5 * std::sin(g_pulse_phase));
|
||||
fill = BlendColour(bg, colour, a);
|
||||
}
|
||||
dc->SetPen(*wxTRANSPARENT_PEN);
|
||||
dc->SetBrush(wxBrush(colour));
|
||||
dc->SetBrush(wxBrush(fill));
|
||||
dc->DrawCircle(cx, cy, 4);
|
||||
return SHAPE_ADVANCE;
|
||||
}
|
||||
@@ -341,7 +401,16 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
// selection highlight (round 11 #10/#13).
|
||||
wxUniChar shape;
|
||||
if (IsShapeSentinel(seg.text, shape)) {
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain);
|
||||
// Background the shape sits on, so the pulsing locate dot fades toward it.
|
||||
wxColour cellbg;
|
||||
if (selected) {
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
} else {
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
}
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
continue;
|
||||
}
|
||||
if (seg.text.IsEmpty()) continue;
|
||||
@@ -765,6 +834,7 @@ void* wxbr_dvlc(void* parent) {
|
||||
AttrListStore* store = new AttrListStore();
|
||||
dv->AssociateModel(store);
|
||||
store->DecRef(); // the control owns a reference now
|
||||
g_pulse_target = dv; // the locate-dot pulse timer repaints this control
|
||||
dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
|
||||
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
|
||||
});
|
||||
@@ -1465,6 +1535,11 @@ void wxbr_register_shape_svg(int sentinel, const char* svg, int vbw, int vbh) {
|
||||
g_shape_bmp_cache.clear();
|
||||
}
|
||||
|
||||
// Start/stop the locate-light dot fade animation (round 12 #6). The Rust side
|
||||
// calls this after each refresh with whether any miner's locate light is
|
||||
// flashing, so the repaint timer only runs when there is a dot to animate.
|
||||
void wxbr_set_light_pulse(int on) { SetLightPulse(on != 0); }
|
||||
|
||||
// ---- live theme changes -----------------------------------------------------
|
||||
|
||||
// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
|
||||
|
||||
@@ -105,6 +105,7 @@ mod notsafe {
|
||||
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
|
||||
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
|
||||
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
|
||||
pub fn wxbr_set_light_pulse(on: c_int);
|
||||
pub fn wxbr_bind_sys_colour(win: *mut c_void);
|
||||
pub fn wxbr_destroy(win: *mut c_void);
|
||||
pub fn wxbr_destroy_children(win: *mut c_void);
|
||||
@@ -212,6 +213,13 @@ pub fn register_shape_svg(sentinel: u32, svg: &str, vbw: i32, vbh: i32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start (or stop) the locate-light dot fade animation. Call with `true` while at
|
||||
/// least one miner's locate light is flashing so the table repaint timer only
|
||||
/// runs when there is a pulsing dot to animate (round 12 #6).
|
||||
pub fn set_light_pulse(on: bool) {
|
||||
unsafe { notsafe::wxbr_set_light_pulse(on as c_int) }
|
||||
}
|
||||
|
||||
/// Open a URL in the system default browser. Returns true on success.
|
||||
pub fn launch_browser(url: &str) -> bool {
|
||||
let c = CString::new(url).unwrap_or_default();
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"f1972769a1b4811d5772e96b2e6c45b461cdcb4175355dba2b586b9df776fc1d","src/backends/v2020/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2020/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"278e4dd04a753858e12df96ead3522aef0616ebf6f27b3da4f1a12b064c19ee6","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"55d5b722632c0a5cfcf1f8c8252a88c5a1ece887173bb513cca0b22b874d628f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"4018fbe6d907231746b1eb44c8027688b64e9cdb4ba722e0d54c2467786b9afd","src/backends/v2020/rpc.rs":"b517f88b9125fe1d8a20d5167f5d0d105b1339fce3d1a9fad5592e00470f46fb","src/backends/v2020/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"278e4dd04a753858e12df96ead3522aef0616ebf6f27b3da4f1a12b064c19ee6","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"e75c21d63218204b61bfab067599402e5c0b20452beaf0b16bfa79bf8afb6b35","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
|
||||
+75
-20
@@ -434,14 +434,29 @@ impl GetDataLocations for AntMinerV2020 {
|
||||
tag: None,
|
||||
},
|
||||
)],
|
||||
DataField::ControlBoardVersion => vec![(
|
||||
WEB_MINER_TYPE,
|
||||
DataExtractor {
|
||||
func: get_by_pointer,
|
||||
key: Some("/subtype"),
|
||||
tag: None,
|
||||
},
|
||||
)],
|
||||
// Prefer the explicit control-board subtype from miner_type.cgi, but
|
||||
// carry the kernel build string from get_system_info.cgi too: older
|
||||
// models (e.g. Z15/Z15J) have no miner_type.cgi, and their kernel
|
||||
// string ("...-xilinx-...") names the control board we can actually
|
||||
// read instead of guessing from the model (round 12 #10).
|
||||
DataField::ControlBoardVersion => vec![
|
||||
(
|
||||
WEB_MINER_TYPE,
|
||||
DataExtractor {
|
||||
func: get_by_pointer,
|
||||
key: Some("/subtype"),
|
||||
tag: Some("subtype"),
|
||||
},
|
||||
),
|
||||
(
|
||||
WEB_SYSTEM_INFO,
|
||||
DataExtractor {
|
||||
func: get_by_pointer,
|
||||
key: Some("/system_kernel_version"),
|
||||
tag: Some("kernel"),
|
||||
},
|
||||
),
|
||||
],
|
||||
// cgminer names its summary keys after the unit they are in —
|
||||
// `GHS 5s` on SHA-256 models, `MHS 5s` on Scrypt ones — so keep
|
||||
// the whole entry and let the parse pick the key that is present.
|
||||
@@ -748,16 +763,33 @@ impl GetExpectedHashrate for AntMinerV2020 {
|
||||
let value = field?
|
||||
.pointer("/hashrate")
|
||||
.and_then(Self::parse_f64_field)?;
|
||||
// Equihash miners (Z15/Z15J) report `total_rateideal` as a Sol/s count in
|
||||
// the same (mislabelled) scale as the realtime "GHS" rate, so reinterpret
|
||||
// it as the base Hash unit -- matching parse_hashrate. Without this,
|
||||
// expected reads ~1e6x larger than realtime and the realtime figure looks
|
||||
// absent next to it (round 12 #10).
|
||||
let is_equihash = self.device_info.algo == HashAlgorithm::Equihash
|
||||
|| self
|
||||
.device_info
|
||||
.model
|
||||
.to_string()
|
||||
.to_ascii_uppercase()
|
||||
.contains("Z15");
|
||||
let unit = if is_equihash {
|
||||
HashRateUnit::Hash
|
||||
} else {
|
||||
// `total_rateideal` does not name its own scale, so take it from
|
||||
// STATS' `rate_unit` (`"GH"` / `"MH"`).
|
||||
field
|
||||
.and_then(|v| v.pointer("/unit"))
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| HashRateUnit::from_str(s).ok())
|
||||
.unwrap_or(HashRateUnit::GigaHash)
|
||||
};
|
||||
Some(
|
||||
HashRate {
|
||||
value,
|
||||
// `total_rateideal` does not name its own scale, so take it
|
||||
// from STATS' `rate_unit` (`"GH"` / `"MH"`).
|
||||
unit: field
|
||||
.and_then(|v| v.pointer("/unit"))
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| HashRateUnit::from_str(s).ok())
|
||||
.unwrap_or(HashRateUnit::GigaHash),
|
||||
unit,
|
||||
algo: self.device_info.algo,
|
||||
}
|
||||
.as_unit(HashRateUnit::default()),
|
||||
@@ -888,11 +920,34 @@ impl GetControlBoardVersion for AntMinerV2020 {
|
||||
&self,
|
||||
data: &HashMap<DataField, Value>,
|
||||
) -> Option<MinerControlBoard> {
|
||||
let cb_type = data.extract::<String>(DataField::ControlBoardVersion)?;
|
||||
match cb_type.as_str() {
|
||||
s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
|
||||
_ => AntMinerControlBoard::parse(cb_type.split("_").collect::<Vec<&str>>()[0])
|
||||
.map(|cb| cb.into()),
|
||||
let field = data.get(&DataField::ControlBoardVersion)?;
|
||||
// Explicit control-board subtype (miner_type.cgi) wins when present.
|
||||
let subtype = field
|
||||
.pointer("/subtype")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if !subtype.is_empty() {
|
||||
return match subtype {
|
||||
s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
|
||||
_ => AntMinerControlBoard::parse(subtype.split('_').next().unwrap_or(subtype))
|
||||
.map(|cb| cb.into()),
|
||||
};
|
||||
}
|
||||
// No subtype (older models): read the control board from the kernel build
|
||||
// string instead of guessing from the model (round 12 #10). Bitmain names
|
||||
// the SoC in the kernel version, e.g. "Linux 4.6.0-xilinx-..." (Z15) or an
|
||||
// AMLogic/Meson kernel on newer AMLogic boards.
|
||||
let kernel = field
|
||||
.pointer("/kernel")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
if kernel.contains("xilinx") || kernel.contains("zynq") {
|
||||
Some(AntMinerControlBoard::Xilinx.into())
|
||||
} else if kernel.contains("aml") || kernel.contains("meson") {
|
||||
Some(AntMinerControlBoard::AMLogic.into())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-1
@@ -71,7 +71,17 @@ impl AntMinerRPCAPI {
|
||||
read_stream_response(&mut stream, DEFAULT_RPC_TIMEOUT).await
|
||||
};
|
||||
let response = response?;
|
||||
self.parse_rpc_result(&response)
|
||||
self.parse_rpc_result(&Self::sanitize_cgminer(&response))
|
||||
}
|
||||
|
||||
/// Antminer's cgminer `stats` sometimes emits an array whose objects are not
|
||||
/// comma-separated (`...}{"STATS":0,...` on the Z15/Z15J), which is invalid
|
||||
/// JSON that serde rejects -- dropping the whole stats command and with it
|
||||
/// every stats-derived field (expected hashrate, wattage, fans, hashboards,
|
||||
/// uptime). Insert the missing separators. Well-formed JSON never contains an
|
||||
/// unseparated `}{`, so this is a no-op on valid responses (round 12 #10).
|
||||
fn sanitize_cgminer(response: &str) -> String {
|
||||
response.replace("}{", "},{")
|
||||
}
|
||||
|
||||
fn parse_rpc_result(&self, response: &str) -> anyhow::Result<Value> {
|
||||
|
||||
+31
-14
@@ -142,18 +142,9 @@ async fn get_model_with_auth(
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the firmware version from a miner using digest auth.
|
||||
async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
|
||||
let client = build_discovery_client().ok()?;
|
||||
let data: Response = client
|
||||
.get(format!("http://{ip}/cgi-bin/summary.cgi"))
|
||||
.send_digest_auth((auth.username(), auth.password()))
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let json_data = data.json::<serde_json::Value>().await.ok()?;
|
||||
let fw_version = json_data["INFO"]["CompileTime"].as_str().unwrap_or("");
|
||||
|
||||
/// Parse an Antminer cgminer `CompileTime` string ("Mon Dec 14 18:01:42 CST
|
||||
/// 2020") into a date-based semver (year.month.day) used to pick the backend.
|
||||
fn parse_antminer_compile_time(fw_version: &str) -> Option<semver::Version> {
|
||||
let cleaned: String = {
|
||||
let mut parts: Vec<&str> = fw_version.split_whitespace().collect();
|
||||
if parts.len() > 4 {
|
||||
@@ -161,9 +152,7 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
|
||||
}
|
||||
parts.join(" ")
|
||||
};
|
||||
|
||||
let dt = NaiveDateTime::parse_from_str(&cleaned, "%a %b %e %H:%M:%S %Y").ok()?;
|
||||
|
||||
Some(semver::Version::new(
|
||||
dt.year() as u64,
|
||||
dt.month() as u64,
|
||||
@@ -171,6 +160,34 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
|
||||
))
|
||||
}
|
||||
|
||||
/// Fetch the firmware version (as a date-based semver) to pick the backend.
|
||||
async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
|
||||
// Newer Antminers expose the firmware CompileTime via summary.cgi.
|
||||
if let Ok(client) = build_discovery_client()
|
||||
&& let Ok(data) = client
|
||||
.get(format!("http://{ip}/cgi-bin/summary.cgi"))
|
||||
.send_digest_auth((auth.username(), auth.password()))
|
||||
.await
|
||||
&& let Ok(json_data) = data.json::<serde_json::Value>().await
|
||||
&& let Some(v) =
|
||||
parse_antminer_compile_time(json_data["INFO"]["CompileTime"].as_str().unwrap_or(""))
|
||||
{
|
||||
return Some(v);
|
||||
}
|
||||
|
||||
// Older models (e.g. Z15/Z15J) have no summary.cgi, so summary-based version
|
||||
// detection returns nothing and the miner would default to the newest
|
||||
// backend and be mis-parsed. Fall back to the cgminer :4028 `version` RPC,
|
||||
// which still reports the CompileTime, so the right (older) backend is picked
|
||||
// (round 12 #10).
|
||||
let rpc = asic_rs_core::util::send_rpc_command(&ip, "version").await?;
|
||||
parse_antminer_compile_time(
|
||||
rpc.pointer("/VERSION/0/CompileTime")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(""),
|
||||
)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MinerFirmware for AntMinerStockFirmware {
|
||||
/// Uses default credentials. For custom credentials, use `build_miner`
|
||||
|
||||
Reference in New Issue
Block a user