Gate first-party Toolkit Rust formatting #12
@@ -35,6 +35,12 @@ jobs:
|
||||
- name: Check runner image pins
|
||||
run: python3 ci/check-runner-image.py
|
||||
|
||||
- name: Check first-party Rust formatting
|
||||
run: |
|
||||
rustup component add rustfmt >/dev/null
|
||||
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -- --check
|
||||
|
||||
|
||||
- name: Compute version
|
||||
id: ver
|
||||
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -49,6 +49,13 @@ jobs:
|
||||
if: steps.surface.outputs.surface != 'documentation'
|
||||
run: python3 ci/test-pr-surface.py
|
||||
|
||||
- name: Check first-party Rust formatting
|
||||
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
|
||||
run: |
|
||||
rustup component add rustfmt >/dev/null
|
||||
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -- --check
|
||||
|
||||
|
||||
- name: Check workflow-only change
|
||||
if: steps.surface.outputs.surface == 'workflow'
|
||||
run: |
|
||||
|
||||
@@ -10,9 +10,8 @@
|
||||

|
||||

|
||||
|
||||
The code quality grade reports first-party Clippy checks from the last
|
||||
successful main build. Test coverage has a separate badge. Formatting is not
|
||||
part of the grade yet.
|
||||
The code quality grade reports GUI Clippy and first-party Rust formatting checks
|
||||
from the last successful main build. Test coverage has a separate badge.
|
||||
|
||||
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
||||
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
|
||||
|
||||
+1
-1
@@ -193,7 +193,7 @@ def main() -> int:
|
||||
write("quality", "code quality", grade,
|
||||
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
|
||||
f"code quality: {grade} (first-party Clippy only)")
|
||||
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
|
||||
if args.tests is not None:
|
||||
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
||||
if args.coverage is not None:
|
||||
|
||||
@@ -56,9 +56,9 @@ class BenchBadgeTests(unittest.TestCase):
|
||||
self.assertEqual(gen_badges.quality_grade(None), "pending")
|
||||
svg = gen_badges.badge_svg(
|
||||
"code quality", "A", "brightgreen",
|
||||
"code quality: A (first-party Clippy only)",
|
||||
"code quality: A (GUI Clippy and first-party rustfmt)",
|
||||
)
|
||||
self.assertIn('aria-label="code quality: A (first-party Clippy only)"', svg)
|
||||
self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg)
|
||||
self.assertIn('>A</text>', svg)
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ def check_workflow_contract() -> None:
|
||||
"""Keep the short workflow check from silently dropping release gates."""
|
||||
required = {
|
||||
"release.yml": ("main", "release", (
|
||||
"Check runner image pins", "Clippy (our crate, warnings are errors)",
|
||||
"Check runner image pins", "Check first-party Rust formatting",
|
||||
"Clippy (our crate, warnings are errors)",
|
||||
"Build release", "Unit tests", "Microbenchmarks",
|
||||
"Headless UI self-test", "Coverage", "Microbenchmark coverage",
|
||||
"Generate measured badges", "Publish measured badges",
|
||||
@@ -44,7 +45,8 @@ def check_workflow_contract() -> None:
|
||||
)),
|
||||
"verify.yml": ("main", "verify", (
|
||||
"Check runner image pins", "Detect changed surface",
|
||||
"Check CI change surface", "Check workflow-only change",
|
||||
"Check CI change surface", "Check first-party Rust formatting",
|
||||
"Check workflow-only change",
|
||||
"Clippy (our crate, warnings are errors)", "Build", "Unit tests",
|
||||
"Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build",
|
||||
)),
|
||||
@@ -73,6 +75,9 @@ def check_workflow_contract() -> None:
|
||||
assert condition == "steps.surface.outputs.surface == 'full'", path
|
||||
elif filename == "verify.yml" and gate == "Check CI change surface":
|
||||
assert condition == "steps.surface.outputs.surface != 'documentation'", path
|
||||
elif filename == "verify.yml" and gate == "Check first-party Rust formatting":
|
||||
assert condition == ("steps.surface.outputs.surface == 'headless' || "
|
||||
"steps.surface.outputs.surface == 'full'"), path
|
||||
elif filename == "verify.yml" and gate == "Check workflow-only change":
|
||||
assert condition == "steps.surface.outputs.surface == 'workflow'", path
|
||||
else:
|
||||
|
||||
@@ -29,10 +29,10 @@ use std::net::{SocketAddr, TcpStream};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use aes::cipher::{block_padding::ZeroPadding, BlockEncryptMut, KeyInit};
|
||||
use aes::Aes256;
|
||||
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
||||
@@ -42,9 +42,9 @@ type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
||||
/// authenticated/unauthorized answer is `None`.
|
||||
pub fn classify_http_code(code: &str) -> Option<bool> {
|
||||
match code.trim() {
|
||||
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
||||
"401" | "403" => Some(true), // rejected -> locked/view-only
|
||||
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
||||
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
||||
"401" | "403" => Some(true), // rejected -> locked/view-only
|
||||
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,10 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
|
||||
]);
|
||||
// The user:pass goes through a curl config on stdin, never argv, so it can't
|
||||
// be read from the process list (round 18 #12).
|
||||
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
|
||||
let config = format!(
|
||||
"user = \"{}\"\n",
|
||||
curl_config_quote(&format!("{user}:{pass}"))
|
||||
);
|
||||
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
|
||||
// curl prints the status code to stdout regardless of exit status (000 on a
|
||||
// connection failure), so classify the code rather than the exit status.
|
||||
@@ -113,7 +116,8 @@ fn wait_with_timeout(
|
||||
stdin_data: Option<&[u8]>,
|
||||
) -> Result<std::process::Output, String> {
|
||||
use std::io::{Read, Write};
|
||||
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
if stdin_data.is_some() {
|
||||
cmd.stdin(std::process::Stdio::piped());
|
||||
}
|
||||
@@ -135,7 +139,11 @@ fn wait_with_timeout(
|
||||
if let Some(mut e) = child.stderr.take() {
|
||||
let _ = e.read_to_end(&mut stderr);
|
||||
}
|
||||
return Ok(std::process::Output { status, stdout, stderr });
|
||||
return Ok(std::process::Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
});
|
||||
}
|
||||
None => {
|
||||
if start.elapsed() >= timeout {
|
||||
@@ -158,7 +166,8 @@ fn curl_config_quote(s: &str) -> String {
|
||||
/// 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 let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock")
|
||||
{
|
||||
if !pass.is_empty() {
|
||||
return vec![pass.clone()];
|
||||
}
|
||||
@@ -170,9 +179,17 @@ fn whatsminer_password_candidates() -> Vec<String> {
|
||||
/// 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 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 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() => {
|
||||
@@ -198,7 +215,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
|
||||
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())?;
|
||||
stream
|
||||
.write_all(payload.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
@@ -213,7 +232,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
||||
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
|
||||
@@ -278,15 +299,20 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
|
||||
// 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 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 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,
|
||||
@@ -302,7 +328,11 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
|
||||
}
|
||||
// Only report "locked" when we cleanly reached the miner and every candidate
|
||||
// was rejected with no transient errors; otherwise the result is indeterminate.
|
||||
if reachable && !errored { Some(true) } else { None }
|
||||
if reachable && !errored {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -311,14 +341,30 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn classify_codes() {
|
||||
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
|
||||
assert_eq!(
|
||||
classify_http_code("200"),
|
||||
Some(false),
|
||||
"authenticated -> unlocked"
|
||||
);
|
||||
assert_eq!(classify_http_code("204"), Some(false));
|
||||
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
|
||||
assert_eq!(
|
||||
classify_http_code("401"),
|
||||
Some(true),
|
||||
"unauthorized -> locked"
|
||||
);
|
||||
assert_eq!(classify_http_code("403"), Some(true));
|
||||
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
||||
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
|
||||
assert_eq!(
|
||||
classify_http_code("404"),
|
||||
None,
|
||||
"endpoint absent -> unknown"
|
||||
);
|
||||
assert_eq!(classify_http_code("500"), None);
|
||||
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
|
||||
assert_eq!(
|
||||
classify_http_code(" 200 "),
|
||||
Some(false),
|
||||
"whitespace tolerated"
|
||||
);
|
||||
assert_eq!(classify_http_code(""), None);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,18 +19,20 @@
|
||||
//! ALKANE_PROBE_USER / ALKANE_PROBE_PASS if set (so a test can authenticate
|
||||
//! without touching the app's saved config).
|
||||
|
||||
use asic_rs::MinerFactory;
|
||||
use asic_rs::core::traits::miner::MinerAuth;
|
||||
use asic_rs::MinerFactory;
|
||||
use futures_util::StreamExt;
|
||||
use measurements::Power;
|
||||
|
||||
fn load_creds() -> Option<(String, String)> {
|
||||
if let (Ok(u), Ok(pw)) = (std::env::var("ALKANE_PROBE_USER"), std::env::var("ALKANE_PROBE_PASS")) {
|
||||
if let (Ok(u), Ok(pw)) = (
|
||||
std::env::var("ALKANE_PROBE_USER"),
|
||||
std::env::var("ALKANE_PROBE_PASS"),
|
||||
) {
|
||||
return Some((u, pw));
|
||||
}
|
||||
let home = std::env::var("HOME").ok()?;
|
||||
let p = std::path::PathBuf::from(home)
|
||||
.join(".config/alkane-toolkit/scan-credentials.txt");
|
||||
let p = std::path::PathBuf::from(home).join(".config/alkane-toolkit/scan-credentials.txt");
|
||||
let s = std::fs::read_to_string(p).ok()?;
|
||||
let mut l = s.lines();
|
||||
let u = l.next()?.to_string();
|
||||
@@ -92,8 +94,14 @@ async fn scan(cidrs: &[String]) {
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_default();
|
||||
let fw_ver = data.firmware_version.clone().unwrap_or_default();
|
||||
let bs = data.best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
|
||||
let sbs = data.session_best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
|
||||
let bs = data
|
||||
.best_share
|
||||
.map(|v| format!("{v:.0}"))
|
||||
.unwrap_or_default();
|
||||
let sbs = data
|
||||
.session_best_share
|
||||
.map(|v| format!("{v:.0}"))
|
||||
.unwrap_or_default();
|
||||
println!(
|
||||
"{ip}\t{}\t{}\t{}\t{}\t{}\t{watts:.0}\t{}\t{}\t{bs}\t{sbs}",
|
||||
data.device_info.make,
|
||||
@@ -281,7 +289,10 @@ async fn msgs(ip_s: &str) {
|
||||
Ok(Some(m)) => {
|
||||
let d = m.get_data().await;
|
||||
let th = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
|
||||
h.clone().map(|x| x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
|
||||
h.clone().map(|x| {
|
||||
x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
||||
.value
|
||||
})
|
||||
};
|
||||
println!(
|
||||
"{ip}: {} {} hashboards={:?} expected={:?}",
|
||||
@@ -389,7 +400,7 @@ async fn lifecycle(ip_s: &str, verb: &str) {
|
||||
|
||||
/// Read (no tz arg) or set the miner's timezone (round 16 / G10). Capability-gated.
|
||||
async fn timezone(ip_s: &str, tz: Option<&str>) {
|
||||
use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
|
||||
use asic_rs::core::config::timezone::{TimezoneConfig, Tz};
|
||||
let Ok(ip) = ip_s.parse::<std::net::IpAddr>() else {
|
||||
eprintln!("bad ip {ip_s}");
|
||||
return;
|
||||
@@ -566,7 +577,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
|
||||
TuningTarget::HashRate(hr)
|
||||
}
|
||||
None => {
|
||||
eprintln!("miner reports no current hashrate; cannot build a hashrate target");
|
||||
eprintln!(
|
||||
"miner reports no current hashrate; cannot build a hashrate target"
|
||||
);
|
||||
return;
|
||||
}
|
||||
},
|
||||
@@ -593,7 +606,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
|
||||
}
|
||||
} else if kind == "power" && m.supports_set_power_limit() {
|
||||
match m.set_power_limit(Power::from_watts(value)).await {
|
||||
Ok(v) => println!("set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"),
|
||||
Ok(v) => println!(
|
||||
"set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"
|
||||
),
|
||||
Err(e) => println!("set_power_limit({value} W) -> Err: {e:#}"),
|
||||
}
|
||||
} else {
|
||||
@@ -680,7 +695,10 @@ async fn setpreset(ip_s: &str, name: &str) {
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
|
||||
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
eprintln!("tokio runtime: {e}");
|
||||
|
||||
@@ -9,8 +9,8 @@ use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
|
||||
use asic_rs::MinerFactory;
|
||||
use asic_rs::core::traits::miner::MinerAuth;
|
||||
use asic_rs::MinerFactory;
|
||||
|
||||
use crate::scan::config_path;
|
||||
|
||||
@@ -195,8 +195,8 @@ pub fn configured_factory() -> MinerFactory {
|
||||
// (round 18 #12: config actions / refresh / pools / flash previously used
|
||||
// asic-rs's 10s default, so on a slow link they could fail to reach miners a
|
||||
// longer-timeout scan had found). start_scan may still override it explicitly.
|
||||
let mut factory =
|
||||
MinerFactory::new().with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
|
||||
let mut factory = MinerFactory::new()
|
||||
.with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
|
||||
let global = load_credentials();
|
||||
let per_fw = load_firmware_credentials();
|
||||
if global.is_none() && per_fw.is_empty() {
|
||||
@@ -223,7 +223,9 @@ mod tests {
|
||||
// config_path() reads $HOME; point it at a private temp dir. HOME is
|
||||
// process-global, so serialise against other HOME-mutating tests via the
|
||||
// shared lock and restore HOME afterward (round 18 #12).
|
||||
let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _home = crate::model::HOME_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let prev = std::env::var_os("HOME");
|
||||
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -233,10 +235,17 @@ mod tests {
|
||||
assert_eq!(load_credentials(), None, "no file -> None");
|
||||
|
||||
save_credentials("admin", "hunter2").unwrap();
|
||||
assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string())));
|
||||
assert_eq!(
|
||||
load_credentials(),
|
||||
Some(("admin".to_string(), "hunter2".to_string()))
|
||||
);
|
||||
|
||||
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
|
||||
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
|
||||
assert_eq!(
|
||||
meta.permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"credentials file must be 0600"
|
||||
);
|
||||
|
||||
// configured_factory() must construct in both branches without panicking:
|
||||
// with saved credentials (fans auth across every firmware backend) ...
|
||||
@@ -254,7 +263,10 @@ mod tests {
|
||||
0o600,
|
||||
"save over a pre-existing 0644 file must re-tighten to 0600"
|
||||
);
|
||||
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
|
||||
assert_eq!(
|
||||
load_credentials(),
|
||||
Some(("admin2".to_string(), "s3cr3t".to_string()))
|
||||
);
|
||||
|
||||
clear_credentials().unwrap();
|
||||
// ... and with no saved credentials (plain MinerFactory::new()).
|
||||
@@ -265,9 +277,15 @@ mod tests {
|
||||
// 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");
|
||||
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(
|
||||
"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).
|
||||
@@ -278,17 +296,29 @@ mod tests {
|
||||
"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("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()));
|
||||
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");
|
||||
assert!(
|
||||
load_firmware_credentials().is_empty(),
|
||||
"empty save -> cleared"
|
||||
);
|
||||
clear_firmware_credentials().unwrap(); // idempotent
|
||||
|
||||
match prev {
|
||||
|
||||
@@ -100,28 +100,62 @@ fn scalar_columns() -> Vec<Col> {
|
||||
("slow", |r| r.slow.to_string()),
|
||||
("paused", |r| r.paused.to_string()),
|
||||
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
|
||||
("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")),
|
||||
("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")),
|
||||
("write_locked", |r| {
|
||||
opt_bool(r.write_locked, "locked", "unlocked")
|
||||
}),
|
||||
("light_flashing", |r| {
|
||||
opt_bool(r.light_flashing, "on", "off")
|
||||
}),
|
||||
("hashrate_ths", |r| num(r.hashrate_ths)),
|
||||
("expected_ths", |r| num(r.expected_ths)),
|
||||
("efficiency_j_th", |r| num(r.efficiency)),
|
||||
("power_w", |r| num(r.power_w)),
|
||||
("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("tuning_percent", |r| {
|
||||
r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("chip_temp_c", |r| num(r.chip_temp_c)),
|
||||
("fluid_temp_c", |r| num(r.fluid_temp_c)),
|
||||
("env_temp_c", |r| num(r.env_temp_c)),
|
||||
("outlet_temp_c", |r| num(r.outlet_temp_c)),
|
||||
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
|
||||
("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("total_chips", |r| r.total_chips.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("expected_chips", |r| r.expected_chips.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("expected_hashboards", |r| r.expected_hashboards.map(|v| v.to_string()).unwrap_or_default()),
|
||||
("uptime_secs", |r| if r.uptime_secs > 0 { r.uptime_secs.to_string() } else { String::new() }),
|
||||
("fan_count", |r| {
|
||||
r.fan_count.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("expected_fans", |r| {
|
||||
r.expected_fans.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("total_chips", |r| {
|
||||
r.total_chips.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("expected_chips", |r| {
|
||||
r.expected_chips.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("hashboards", |r| {
|
||||
r.hashboards.map(|v| v.to_string()).unwrap_or_default()
|
||||
}),
|
||||
("expected_hashboards", |r| {
|
||||
r.expected_hashboards
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default()
|
||||
}),
|
||||
("uptime_secs", |r| {
|
||||
if r.uptime_secs > 0 {
|
||||
r.uptime_secs.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}),
|
||||
("best_share", |r| r.best_share.map(num).unwrap_or_default()),
|
||||
("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()),
|
||||
("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()),
|
||||
("session_best_share", |r| {
|
||||
r.session_best_share.map(num).unwrap_or_default()
|
||||
}),
|
||||
("pool_account", |r| {
|
||||
r.worker
|
||||
.split_once('.')
|
||||
.map(|(a, _)| a)
|
||||
.unwrap_or(&r.worker)
|
||||
.to_string()
|
||||
}),
|
||||
("pool_url", |r| r.pool_url.clone()),
|
||||
("errors", |r| r.errors.join("; ")),
|
||||
]
|
||||
@@ -137,7 +171,10 @@ pub const GROUP_POOLS: &str = "pools";
|
||||
/// Every selectable export field, in output order: each scalar column header,
|
||||
/// then the four variable-length group keys.
|
||||
pub fn export_field_names() -> Vec<String> {
|
||||
let mut v: Vec<String> = scalar_columns().iter().map(|(h, _)| (*h).to_string()).collect();
|
||||
let mut v: Vec<String> = scalar_columns()
|
||||
.iter()
|
||||
.map(|(h, _)| (*h).to_string())
|
||||
.collect();
|
||||
v.push(GROUP_BOARD_TEMPS.to_string());
|
||||
v.push(GROUP_FANS.to_string());
|
||||
v.push(GROUP_BOARD_STATUS.to_string());
|
||||
@@ -152,16 +189,26 @@ pub fn rows_to_csv_selected(
|
||||
rows: &[MinerRow],
|
||||
selected: &std::collections::HashSet<String>,
|
||||
) -> String {
|
||||
let cols: Vec<Col> =
|
||||
scalar_columns().into_iter().filter(|(h, _)| selected.contains(*h)).collect();
|
||||
let cols: Vec<Col> = scalar_columns()
|
||||
.into_iter()
|
||||
.filter(|(h, _)| selected.contains(*h))
|
||||
.collect();
|
||||
// A group's columns appear only when it is selected; an unselected group's
|
||||
// width stays 0, so the header/value loops below emit nothing for it.
|
||||
let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize {
|
||||
if want { rows.iter().map(f).max().unwrap_or(0) } else { 0 }
|
||||
if want {
|
||||
rows.iter().map(f).max().unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| r.board_temps.len());
|
||||
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| {
|
||||
r.board_temps.len()
|
||||
});
|
||||
let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len());
|
||||
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| r.board_status.len());
|
||||
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| {
|
||||
r.board_status.len()
|
||||
});
|
||||
let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len());
|
||||
|
||||
// Header.
|
||||
@@ -193,7 +240,13 @@ pub fn rows_to_csv_selected(
|
||||
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
|
||||
}
|
||||
for i in 0..max_boards {
|
||||
vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string());
|
||||
vals.push(
|
||||
r.board_status
|
||||
.get(i)
|
||||
.map(board_health_str)
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
for i in 0..max_pools {
|
||||
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
|
||||
@@ -222,7 +275,11 @@ mod tests {
|
||||
fan_rpms: vec![6000.0, 6100.0],
|
||||
..Default::default()
|
||||
},
|
||||
MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() },
|
||||
MinerRow {
|
||||
ip: "10.0.0.2".into(),
|
||||
model: "M30S".into(),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let all: std::collections::HashSet<String> = export_field_names().into_iter().collect();
|
||||
let csv = rows_to_csv_selected(&rows, &all);
|
||||
|
||||
@@ -42,9 +42,22 @@ impl Board {
|
||||
let slow = is_slow(self.mining, self.hashrate, self.expected);
|
||||
// A few extra metrics so the demo/offline mode shows non-empty values
|
||||
// for some of the additional columns.
|
||||
let last_octet: u8 = self.ip.rsplit('.').next().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let last_octet: u8 = self
|
||||
.ip
|
||||
.rsplit('.')
|
||||
.next()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let (boards, chips, efficiency) = if self.mining {
|
||||
(Some(3u32), Some(210u32), if self.hashrate > 0.0 { self.power / self.hashrate } else { 0.0 })
|
||||
(
|
||||
Some(3u32),
|
||||
Some(210u32),
|
||||
if self.hashrate > 0.0 {
|
||||
self.power / self.hashrate
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(None, None, 0.0)
|
||||
};
|
||||
@@ -63,7 +76,11 @@ impl Board {
|
||||
// Per-board hashrate for the R2 Health tooltip demo: split the total three
|
||||
// ways with a little variety (index-aligned with the 3 boards).
|
||||
let board_hashrates = if self.mining && self.hashrate > 0.0 {
|
||||
vec![self.hashrate * 0.34, self.hashrate * 0.35, self.hashrate * 0.31]
|
||||
vec![
|
||||
self.hashrate * 0.34,
|
||||
self.hashrate * 0.35,
|
||||
self.hashrate * 0.31,
|
||||
]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
@@ -147,7 +164,10 @@ impl Board {
|
||||
slow,
|
||||
paused: self.paused,
|
||||
// offline defaults to false (online); these bench rows are reachable.
|
||||
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
|
||||
mac: format!(
|
||||
"AA:BB:CC:00:{:02X}:{last_octet:02X}",
|
||||
last_octet.wrapping_mul(3)
|
||||
),
|
||||
hostname: format!("miner-{last_octet}"),
|
||||
hashboards: boards,
|
||||
expected_hashboards: Some(3),
|
||||
@@ -156,22 +176,40 @@ impl Board {
|
||||
psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 },
|
||||
// PSU info demo (round 17 R5): mining units show a version + rated
|
||||
// envelope + live output, so the columns and the R2 PSU tooltip render.
|
||||
psu_version: if self.mining { "22 (117)".to_string() } else { String::new() },
|
||||
psu_version: if self.mining {
|
||||
"22 (117)".to_string()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
psu_voltage_min_v: self.mining.then_some(11.88),
|
||||
psu_voltage_max_v: self.mining.then_some(15.18),
|
||||
psu_out_voltage_v: self.mining.then_some(13.2),
|
||||
psu_out_current_a: self.mining.then_some(210.0),
|
||||
uptime_secs: if self.mining { 3600 * 24 * 2 + 3600 * 5 } else { 0 },
|
||||
uptime_secs: if self.mining {
|
||||
3600 * 24 * 2 + 3600 * 5
|
||||
} else {
|
||||
0
|
||||
},
|
||||
// One unit is "being located" so the Light column's yellow dot is
|
||||
// demonstrable offline (round 11 #10).
|
||||
light_flashing: Some(self.ip == "10.255.1.167"),
|
||||
pool_url: if self.worker.is_empty() { String::new() } else { "stratum+tcp://pool.blueflare:3333".to_string() },
|
||||
pool_url: if self.worker.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
"stratum+tcp://pool.blueflare:3333".to_string()
|
||||
},
|
||||
pools: if self.worker.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![
|
||||
("stratum+tcp://pool.blueflare:3333".to_string(), self.worker.to_string()),
|
||||
("stratum+tcp://backup.blueflare:3333".to_string(), format!("{}_bak", self.worker)),
|
||||
(
|
||||
"stratum+tcp://pool.blueflare:3333".to_string(),
|
||||
self.worker.to_string(),
|
||||
),
|
||||
(
|
||||
"stratum+tcp://backup.blueflare:3333".to_string(),
|
||||
format!("{}_bak", self.worker),
|
||||
),
|
||||
]
|
||||
},
|
||||
operating_state: if self.paused {
|
||||
@@ -223,9 +261,18 @@ impl Board {
|
||||
// is exercisable offline on units that advertise preset support.
|
||||
presets: if self.mining {
|
||||
vec![
|
||||
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
|
||||
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
|
||||
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
|
||||
crate::model::MinerPreset {
|
||||
name: "default".into(),
|
||||
pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()),
|
||||
},
|
||||
crate::model::MinerPreset {
|
||||
name: "540MHz".into(),
|
||||
pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()),
|
||||
},
|
||||
crate::model::MinerPreset {
|
||||
name: "490MHz".into(),
|
||||
pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()),
|
||||
},
|
||||
]
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -247,35 +294,152 @@ pub fn bench_fleet() -> Vec<MinerRow> {
|
||||
let boards = [
|
||||
// firmware families span the palette (Stock/VNish/Braiins/LuxOS/ePIC/
|
||||
// Hive/BixBit/Alkane) so the offline demo shows the Firmware colouring.
|
||||
Board { ip: "10.255.1.112", make: "Antminer", model_id: "S17", board: "Xilinx", firmware: "Stock", fw_version: "",
|
||||
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
|
||||
worker: "", mining: false, paused: false },
|
||||
Board { ip: "10.255.1.166", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "VNish", fw_version: "1.2.8",
|
||||
hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0,
|
||||
worker: "blueflare.s19", mining: true, paused: false },
|
||||
Board { ip: "10.255.1.152", make: "Antminer", model_id: "S19jPro", board: "AMLogic", firmware: "Braiins", fw_version: "25.05.1",
|
||||
hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0,
|
||||
worker: "blueflare.s19jpro", mining: true, paused: false },
|
||||
Board { ip: "10.255.1.167", make: "Antminer", model_id: "S19KPro", board: "AMLogic", firmware: "LuxOS", fw_version: "2024.9.0",
|
||||
hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0,
|
||||
worker: "blueflare.s19kpro", mining: true, paused: false },
|
||||
Board { ip: "10.255.1.149", make: "Antminer", model_id: "S21Pro", board: "CVITek", firmware: "ePIC", fw_version: "1.0.3",
|
||||
hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0,
|
||||
worker: "blueflare.s21pro", mining: true, paused: false }, // slow: 60/200 = 30%
|
||||
Board { ip: "10.255.1.126", make: "Whatsminer", model_id: "M30SVE40", board: "H3", firmware: "Stock", fw_version: "H3.0.1",
|
||||
hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0,
|
||||
worker: "blueflare.h3", mining: true, paused: false },
|
||||
Board { ip: "10.255.1.131", make: "Whatsminer", model_id: "M30SPlusVE40", board: "H616", firmware: "Hiveon", fw_version: "1.05",
|
||||
hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0,
|
||||
worker: "blueflare.h616", mining: true, paused: false },
|
||||
Board { ip: "10.255.1.148", make: "Whatsminer", model_id: "M50VH50", board: "H6", firmware: "Bixbit", fw_version: "0.9.9.4",
|
||||
hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0,
|
||||
worker: "blueflare.m50", mining: true, paused: false },
|
||||
Board {
|
||||
ip: "10.255.1.112",
|
||||
make: "Antminer",
|
||||
model_id: "S17",
|
||||
board: "Xilinx",
|
||||
firmware: "Stock",
|
||||
fw_version: "",
|
||||
hashrate: 0.0,
|
||||
expected: 0.0,
|
||||
power: 0.0,
|
||||
temp: 0.0,
|
||||
fan: 0.0,
|
||||
worker: "",
|
||||
mining: false,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.166",
|
||||
make: "Antminer",
|
||||
model_id: "S19",
|
||||
board: "BeagleBoneBlack",
|
||||
firmware: "VNish",
|
||||
fw_version: "1.2.8",
|
||||
hashrate: 95.0,
|
||||
expected: 96.0,
|
||||
power: 3250.0,
|
||||
temp: 65.0,
|
||||
fan: 4200.0,
|
||||
worker: "blueflare.s19",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.152",
|
||||
make: "Antminer",
|
||||
model_id: "S19jPro",
|
||||
board: "AMLogic",
|
||||
firmware: "Braiins",
|
||||
fw_version: "25.05.1",
|
||||
hashrate: 100.0,
|
||||
expected: 104.0,
|
||||
power: 3100.0,
|
||||
temp: 62.0,
|
||||
fan: 3900.0,
|
||||
worker: "blueflare.s19jpro",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.167",
|
||||
make: "Antminer",
|
||||
model_id: "S19KPro",
|
||||
board: "AMLogic",
|
||||
firmware: "LuxOS",
|
||||
fw_version: "2024.9.0",
|
||||
hashrate: 120.0,
|
||||
expected: 128.0,
|
||||
power: 3300.0,
|
||||
temp: 68.0,
|
||||
fan: 4500.0,
|
||||
worker: "blueflare.s19kpro",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.149",
|
||||
make: "Antminer",
|
||||
model_id: "S21Pro",
|
||||
board: "CVITek",
|
||||
firmware: "ePIC",
|
||||
fw_version: "1.0.3",
|
||||
hashrate: 60.0,
|
||||
expected: 200.0,
|
||||
power: 1500.0,
|
||||
temp: 55.0,
|
||||
fan: 3000.0,
|
||||
worker: "blueflare.s21pro",
|
||||
mining: true,
|
||||
paused: false,
|
||||
}, // slow: 60/200 = 30%
|
||||
Board {
|
||||
ip: "10.255.1.126",
|
||||
make: "Whatsminer",
|
||||
model_id: "M30SVE40",
|
||||
board: "H3",
|
||||
firmware: "Stock",
|
||||
fw_version: "H3.0.1",
|
||||
hashrate: 92.0,
|
||||
expected: 96.0,
|
||||
power: 3400.0,
|
||||
temp: 70.0,
|
||||
fan: 4800.0,
|
||||
worker: "blueflare.h3",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.131",
|
||||
make: "Whatsminer",
|
||||
model_id: "M30SPlusVE40",
|
||||
board: "H616",
|
||||
firmware: "Hiveon",
|
||||
fw_version: "1.05",
|
||||
hashrate: 100.0,
|
||||
expected: 100.0,
|
||||
power: 3450.0,
|
||||
temp: 71.0,
|
||||
fan: 4900.0,
|
||||
worker: "blueflare.h616",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
Board {
|
||||
ip: "10.255.1.148",
|
||||
make: "Whatsminer",
|
||||
model_id: "M50VH50",
|
||||
board: "H6",
|
||||
firmware: "Bixbit",
|
||||
fw_version: "0.9.9.4",
|
||||
hashrate: 118.0,
|
||||
expected: 122.0,
|
||||
power: 3300.0,
|
||||
temp: 66.0,
|
||||
fan: 4600.0,
|
||||
worker: "blueflare.m50",
|
||||
mining: true,
|
||||
paused: false,
|
||||
},
|
||||
// Rebucketed from idle/not-hashing to paused so the "paused"
|
||||
// status/KPI bucket is exercisable in the fake-scan/offline demo.
|
||||
Board { ip: "10.255.1.115", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "Alkane", fw_version: "0.1",
|
||||
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
|
||||
worker: "", mining: false, paused: true },
|
||||
Board {
|
||||
ip: "10.255.1.115",
|
||||
make: "Antminer",
|
||||
model_id: "S19",
|
||||
board: "BeagleBoneBlack",
|
||||
firmware: "Alkane",
|
||||
fw_version: "0.1",
|
||||
hashrate: 0.0,
|
||||
expected: 0.0,
|
||||
power: 0.0,
|
||||
temp: 0.0,
|
||||
fan: 0.0,
|
||||
worker: "",
|
||||
mining: false,
|
||||
paused: true,
|
||||
},
|
||||
];
|
||||
boards.into_iter().map(Board::into_row).collect()
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ impl Lang {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Lang::En => "English",
|
||||
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
|
||||
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
|
||||
Lang::Ru => "\u{0420}\u{0443}\u{0441}\u{0441}\u{043a}\u{0438}\u{0439}", // Русский
|
||||
Lang::Fr => "Fran\u{e7}ais",
|
||||
Lang::Es => "Espa\u{f1}ol",
|
||||
@@ -72,7 +72,9 @@ const LANG_FILE: &str = "language.txt";
|
||||
|
||||
fn config_path() -> PathBuf {
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
|
||||
PathBuf::from(home).join(".config/alkane-toolkit").join(LANG_FILE)
|
||||
PathBuf::from(home)
|
||||
.join(".config/alkane-toolkit")
|
||||
.join(LANG_FILE)
|
||||
}
|
||||
|
||||
/// Load the saved language into the global (call once at startup).
|
||||
|
||||
@@ -32,13 +32,17 @@ pub fn scan_log(ip: &str, brand: &str, timeout_secs: u64) -> Result<LogScan, Str
|
||||
if brand.eq_ignore_ascii_case("whatsminer") {
|
||||
let resp = crate::access_probe::whatsminer_get_error_code(ip)
|
||||
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
|
||||
return Ok(LogScan { text: tail(&resp, MAX_LOG_BYTES) });
|
||||
return Ok(LogScan {
|
||||
text: tail(&resp, MAX_LOG_BYTES),
|
||||
});
|
||||
}
|
||||
let text = crate::scan::fetch_log(ip, timeout_secs)?;
|
||||
if text.trim().is_empty() {
|
||||
return Err("the miner returned an empty log".to_string());
|
||||
}
|
||||
Ok(LogScan { text: tail(&text, MAX_LOG_BYTES) })
|
||||
Ok(LogScan {
|
||||
text: tail(&text, MAX_LOG_BYTES),
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
|
||||
@@ -55,7 +59,10 @@ fn tail(s: &str, max: usize) -> String {
|
||||
start += 1;
|
||||
}
|
||||
// then 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);
|
||||
let start = s[start..]
|
||||
.find('\n')
|
||||
.map(|i| start + i + 1)
|
||||
.unwrap_or(start);
|
||||
format!("[... earlier log trimmed ...]\n{}", &s[start..])
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,10 @@ static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Local wall-clock HH:MM:SS for a log line. Uses the system clock offset from
|
||||
/// UTC via the TZ-less epoch; good enough for an activity log timestamp.
|
||||
fn stamp() -> String {
|
||||
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
let t = secs % 86_400;
|
||||
format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
|
||||
//! alkane-toolkit: primary view (docs/UI-SPEC.md).
|
||||
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
||||
|
||||
mod access_probe;
|
||||
@@ -6,8 +6,8 @@ mod credentials;
|
||||
mod export;
|
||||
mod fixtures;
|
||||
mod i18n;
|
||||
mod logs;
|
||||
mod log_scan;
|
||||
mod logs;
|
||||
mod model;
|
||||
mod naming;
|
||||
mod pool_prefs;
|
||||
@@ -16,7 +16,6 @@ mod restore;
|
||||
mod scan;
|
||||
mod ui;
|
||||
|
||||
|
||||
fn main() {
|
||||
// Headless workflow self-test: render the bench-fleet fixtures through the
|
||||
// real widgets and check the table + KPIs against the expected hardware
|
||||
|
||||
+684
-175
File diff suppressed because it is too large
Load Diff
@@ -234,7 +234,10 @@ fn clean_antminer(id: &str) -> String {
|
||||
/// Normalise a raw control-board name for matching: drop spaces/punctuation and
|
||||
/// uppercase, so "BeagleBone Black", "BeagleBoneBlack" and "BBB" all collapse.
|
||||
fn compact_upper(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_ascii_alphanumeric()).flat_map(|c| c.to_uppercase()).collect()
|
||||
s.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric())
|
||||
.flat_map(|c| c.to_uppercase())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The control-board short code for the Control-board column, e.g.
|
||||
@@ -365,7 +368,10 @@ mod tests {
|
||||
assert_eq!(chip_type_for_model("Antminer", "S19"), Some("BM1398"));
|
||||
assert_eq!(chip_type_for_model("Antminer", "T19"), Some("BM1398"));
|
||||
// Raw "Unknown" passthrough with brand + parenthetical normalizes to S19.
|
||||
assert_eq!(chip_type_for_model("Antminer", "ANTMINER S19 (88)"), Some("BM1398"));
|
||||
assert_eq!(
|
||||
chip_type_for_model("Antminer", "ANTMINER S19 (88)"),
|
||||
Some("BM1398")
|
||||
);
|
||||
// WhatsMiner chips are not cleanly named -> never derived.
|
||||
assert_eq!(chip_type_for_model("Whatsminer", "M30S+VE40"), None);
|
||||
// Unknown Antminer model -> None (no guess).
|
||||
@@ -431,23 +437,56 @@ mod tests {
|
||||
#[test]
|
||||
fn control_board_short_codes() {
|
||||
// Antminer families (board name as asic-rs renders the enum variant).
|
||||
assert_eq!(control_board_code("Antminer", "BeagleBoneBlack", "S19"), "BBB (C77)");
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "BeagleBoneBlack", "S19"),
|
||||
"BBB (C77)"
|
||||
);
|
||||
// Also accept the spaced form some layers produce.
|
||||
assert_eq!(control_board_code("Antminer", "BeagleBone Black", "S19"), "BBB (C77)");
|
||||
assert_eq!(control_board_code("Antminer", "CVITek", "S21 Pro"), "CVI (C88)");
|
||||
assert_eq!(control_board_code("Antminer", "Xilinx", "S17 Pro"), "XIL (C49)");
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "BeagleBone Black", "S19"),
|
||||
"BBB (C77)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "CVITek", "S21 Pro"),
|
||||
"CVI (C88)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "Xilinx", "S17 Pro"),
|
||||
"XIL (C49)"
|
||||
);
|
||||
assert_eq!(control_board_code("Antminer", "Xilinx", "T17"), "XIL (C49)");
|
||||
assert_eq!(control_board_code("Antminer", "Xilinx", "S19 Pro"), "XIL (C55)");
|
||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19j Pro"), "AML (C76)");
|
||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19k Pro"), "AML (CBE)");
|
||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19 XP"), "AML (CBE)");
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "Xilinx", "S19 Pro"),
|
||||
"XIL (C55)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "AMLogic", "S19j Pro"),
|
||||
"AML (C76)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "AMLogic", "S19k Pro"),
|
||||
"AML (CBE)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "AMLogic", "S19 XP"),
|
||||
"AML (CBE)"
|
||||
);
|
||||
// WhatsMiner families.
|
||||
assert_eq!(control_board_code("Whatsminer", "H3", "M30S"), "H3 (CB2)");
|
||||
assert_eq!(control_board_code("Whatsminer", "H6", "M50"), "H6 (CB4)");
|
||||
assert_eq!(control_board_code("Whatsminer", "H6OS", "M50"), "H6os (CB4)");
|
||||
assert_eq!(control_board_code("Whatsminer", "H616", "M30S+"), "H616 (CB6)");
|
||||
assert_eq!(
|
||||
control_board_code("Whatsminer", "H6OS", "M50"),
|
||||
"H6os (CB4)"
|
||||
);
|
||||
assert_eq!(
|
||||
control_board_code("Whatsminer", "H616", "M30S+"),
|
||||
"H616 (CB6)"
|
||||
);
|
||||
// Unknown / blank pass through.
|
||||
assert_eq!(control_board_code("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "Unknown: FOO", "S19"),
|
||||
"Unknown: FOO"
|
||||
);
|
||||
assert_eq!(control_board_code("Antminer", "", "S19"), "");
|
||||
}
|
||||
|
||||
@@ -455,23 +494,35 @@ mod tests {
|
||||
fn control_board_cpu_and_board_split() {
|
||||
// CPU column vs board-code column.
|
||||
assert_eq!(control_board_cpu("Antminer", "AMLogic", "S19j Pro"), "AML");
|
||||
assert_eq!(control_board_board("Antminer", "AMLogic", "S19j Pro"), "C76");
|
||||
assert_eq!(
|
||||
control_board_board("Antminer", "AMLogic", "S19j Pro"),
|
||||
"C76"
|
||||
);
|
||||
assert_eq!(control_board_cpu("Antminer", "CVITek", "S21 Pro"), "CVI");
|
||||
assert_eq!(control_board_board("Antminer", "CVITek", "S21 Pro"), "C88");
|
||||
assert_eq!(control_board_cpu("Whatsminer", "H616", "M30S+"), "H616");
|
||||
assert_eq!(control_board_board("Whatsminer", "H616", "M30S+"), "CB6");
|
||||
// S21 Pro on an AMLogic board is the 140mm CBE, not C76.
|
||||
assert_eq!(control_board_board("Antminer", "AMLogic", "S21 Pro"), "CBE");
|
||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S21 Pro"), "AML (CBE)");
|
||||
assert_eq!(
|
||||
control_board_code("Antminer", "AMLogic", "S21 Pro"),
|
||||
"AML (CBE)"
|
||||
);
|
||||
// Unknown -> cpu holds the raw string, no board code.
|
||||
assert_eq!(control_board_cpu("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
|
||||
assert_eq!(
|
||||
control_board_cpu("Antminer", "Unknown: FOO", "S19"),
|
||||
"Unknown: FOO"
|
||||
);
|
||||
assert_eq!(control_board_board("Antminer", "Unknown: FOO", "S19"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_family_splits_vendor_prefix() {
|
||||
// Stock firmware: vendor word moves out of the family word (round 11 #6).
|
||||
assert_eq!(firmware_family("AntMiner Stock"), ("Stock".to_string(), Some("AntMiner".to_string())));
|
||||
assert_eq!(
|
||||
firmware_family("AntMiner Stock"),
|
||||
("Stock".to_string(), Some("AntMiner".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
firmware_family("WhatsMiner Stock"),
|
||||
("Stock".to_string(), Some("WhatsMiner".to_string()))
|
||||
|
||||
@@ -36,8 +36,20 @@ impl PoolField {
|
||||
PoolField::Account => Vec::new(),
|
||||
// Per-miner worker-name placeholders (see MinerRow::expand_worker_template).
|
||||
PoolField::Worker => vec![
|
||||
"{ip1}", "{ip2}", "{ip3}", "{ip4}", "{serial}", "{mac}", "{nameplate-hr}",
|
||||
"{brand}", "{model}", "{submodel}", "{cpu}", "{cb}", "{firmware}", "{hostname}",
|
||||
"{ip1}",
|
||||
"{ip2}",
|
||||
"{ip3}",
|
||||
"{ip4}",
|
||||
"{serial}",
|
||||
"{mac}",
|
||||
"{nameplate-hr}",
|
||||
"{brand}",
|
||||
"{model}",
|
||||
"{submodel}",
|
||||
"{cpu}",
|
||||
"{cb}",
|
||||
"{firmware}",
|
||||
"{hostname}",
|
||||
],
|
||||
PoolField::Password => vec!["x"],
|
||||
}
|
||||
@@ -68,7 +80,13 @@ fn config_path(file: &str) -> PathBuf {
|
||||
pub fn load_saved(field: PoolField) -> Vec<String> {
|
||||
std::fs::read_to_string(config_path(field.saved_file()))
|
||||
.ok()
|
||||
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect())
|
||||
.map(|s| {
|
||||
s.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(String::from)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -153,13 +171,18 @@ mod tests {
|
||||
#[test]
|
||||
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
|
||||
let presets = ["x", "{ip1}"];
|
||||
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let vals: Vec<String> = [
|
||||
" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep",
|
||||
]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
|
||||
// "keep" all drop; " keep " is trimmed and kept.
|
||||
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
|
||||
assert_eq!(
|
||||
dedupe_saved(&presets, &vals),
|
||||
vec!["myworker".to_string(), "keep".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -43,7 +43,12 @@ impl PresetView {
|
||||
PresetView {
|
||||
order: v.order.clone(),
|
||||
// keep the visible columns in display order for stability
|
||||
visible: v.order.iter().copied().filter(|c| v.visible.contains(c)).collect(),
|
||||
visible: v
|
||||
.order
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|c| v.visible.contains(c))
|
||||
.collect(),
|
||||
sort: v.sort,
|
||||
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
|
||||
}
|
||||
@@ -62,7 +67,12 @@ impl PresetView {
|
||||
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
|
||||
visible.insert(Column::Ip); // IP is always shown
|
||||
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
|
||||
ViewState { order, visible, sort: self.sort, filters }
|
||||
ViewState {
|
||||
order,
|
||||
visible,
|
||||
sort: self.sort,
|
||||
filters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,8 +144,14 @@ mod tests {
|
||||
// The Health column (round 13 #3) replaced these in the default profile.
|
||||
assert!(!view.visible.contains(&Column::Error));
|
||||
// Columns dropped from the default profile in round 11.
|
||||
assert!(!view.visible.contains(&Column::BoardCode), "not in the default profile");
|
||||
assert!(!view.visible.contains(&Column::Fan1), "not in the default profile");
|
||||
assert!(
|
||||
!view.visible.contains(&Column::BoardCode),
|
||||
"not in the default profile"
|
||||
);
|
||||
assert!(
|
||||
!view.visible.contains(&Column::Fan1),
|
||||
"not in the default profile"
|
||||
);
|
||||
// to_view covers every column in `order`.
|
||||
assert_eq!(view.order.len(), ALL_COLUMNS.len());
|
||||
// Round-trip a snapshot back out.
|
||||
|
||||
@@ -16,16 +16,20 @@
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::mpsc::{channel, Receiver};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::scan::fake_scan_enabled;
|
||||
|
||||
pub enum RestoreMsg {
|
||||
Started,
|
||||
Result { ip: String, ok: bool, detail: String },
|
||||
Result {
|
||||
ip: String,
|
||||
ok: bool,
|
||||
detail: String,
|
||||
},
|
||||
Done,
|
||||
}
|
||||
|
||||
@@ -87,7 +91,14 @@ pub fn start_restore(
|
||||
break;
|
||||
}
|
||||
let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass);
|
||||
if tx.send(RestoreMsg::Result { ip: t.ip, ok, detail }).is_err() {
|
||||
if tx
|
||||
.send(RestoreMsg::Result {
|
||||
ip: t.ip,
|
||||
ok,
|
||||
detail,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -106,7 +117,12 @@ pub fn start_restore(
|
||||
RestoreHandle { rx, cancel }
|
||||
}
|
||||
|
||||
fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &str) -> (bool, String) {
|
||||
fn restore_one(
|
||||
t: &RestoreTarget,
|
||||
vnish_pass: &str,
|
||||
ssh_user: &str,
|
||||
ssh_pass: &str,
|
||||
) -> (bool, String) {
|
||||
let fw = t.firmware.to_ascii_lowercase();
|
||||
if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") {
|
||||
restore_vnish(&t.ip, vnish_pass)
|
||||
@@ -115,7 +131,10 @@ fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &s
|
||||
} else if fw.contains("braiins") || fw.contains("bos") {
|
||||
restore_braiins(&t.ip, ssh_user, ssh_pass)
|
||||
} else {
|
||||
(false, format!("no restore-to-stock path for firmware '{}'", t.firmware))
|
||||
(
|
||||
false,
|
||||
format!("no restore-to-stock path for firmware '{}'", t.firmware),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +146,17 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
|
||||
let body = serde_json::json!({ "pw": pass }).to_string();
|
||||
let unlock = match curl(
|
||||
&[
|
||||
"-s", "--connect-timeout", "5", "--max-time", "9",
|
||||
"-X", "POST", "-H", "Content-Type: application/json",
|
||||
"-d", "@-",
|
||||
"-s",
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"9",
|
||||
"-X",
|
||||
"POST",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"-d",
|
||||
"@-",
|
||||
&format!("http://{ip}/api/v1/unlock"),
|
||||
],
|
||||
Some(body.as_bytes()),
|
||||
@@ -146,8 +173,15 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
|
||||
};
|
||||
match curl(
|
||||
&[
|
||||
"-s", "--connect-timeout", "5", "--max-time", "12",
|
||||
"-X", "POST", "-H", &format!("Authorization: Bearer {token}"),
|
||||
"-s",
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"12",
|
||||
"-X",
|
||||
"POST",
|
||||
"-H",
|
||||
&format!("Authorization: Bearer {token}"),
|
||||
&format!("http://{ip}/api/v1/firmware/remove"),
|
||||
],
|
||||
None,
|
||||
@@ -174,7 +208,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
|
||||
.map(str::to_string)
|
||||
});
|
||||
let Some(session) = session.filter(|s| !s.is_empty()) else {
|
||||
return (false, format!("no SessionID in logon response: {}", logon.trim()));
|
||||
return (
|
||||
false,
|
||||
format!("no SessionID in logon response: {}", logon.trim()),
|
||||
);
|
||||
};
|
||||
// serde-encode so the miner-supplied SessionID can't break or inject into the
|
||||
// JSON-RPC command (round 18 #12).
|
||||
@@ -206,7 +243,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
|
||||
/// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup).
|
||||
fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||
if pass.is_empty() {
|
||||
return (false, "Braiins restore needs an SSH password (set the SSH login)".into());
|
||||
return (
|
||||
false,
|
||||
"Braiins restore needs an SSH password (set the SSH login)".into(),
|
||||
);
|
||||
}
|
||||
let target = format!("{user}@{ip}");
|
||||
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
|
||||
@@ -218,10 +258,14 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||
cmd.env("SSHPASS", pass);
|
||||
cmd.arg("-e").arg("ssh");
|
||||
cmd.args([
|
||||
"-o", "StrictHostKeyChecking=no",
|
||||
"-o", "UserKnownHostsFile=/dev/null",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ConnectTimeout=8",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=no",
|
||||
"-o",
|
||||
"UserKnownHostsFile=/dev/null",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ConnectTimeout=8",
|
||||
&target,
|
||||
"uninstall.sh || /sbin/uninstall.sh",
|
||||
]);
|
||||
@@ -247,7 +291,12 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
|
||||
/// reported as a FAILURE, never a false success. A dropped connection or a
|
||||
/// timeout after the command started is the expected signature of the reboot.
|
||||
fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bool) -> (bool, String) {
|
||||
fn classify_braiins(
|
||||
stdout: &str,
|
||||
stderr: &str,
|
||||
code: Option<i32>,
|
||||
timed_out: bool,
|
||||
) -> (bool, String) {
|
||||
let err = stderr.to_lowercase();
|
||||
// ssh's own connection/auth failures (exit 255) never reach the remote command.
|
||||
let conn_fail = [
|
||||
@@ -264,7 +313,10 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
|
||||
.any(|m| err.contains(m));
|
||||
if conn_fail {
|
||||
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
|
||||
return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error")));
|
||||
return (
|
||||
false,
|
||||
format!("SSH failed: {}", why.unwrap_or("connection/auth error")),
|
||||
);
|
||||
}
|
||||
let out = stdout.to_lowercase();
|
||||
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
|
||||
@@ -273,14 +325,19 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
|
||||
match code {
|
||||
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
|
||||
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
|
||||
_ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()),
|
||||
_ if timed_out => (
|
||||
true,
|
||||
"SSH timed out (miner likely rebooting to stock)".into(),
|
||||
),
|
||||
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
|
||||
}
|
||||
}
|
||||
|
||||
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
|
||||
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
|
||||
let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?;
|
||||
let addr: SocketAddr = format!("{ip}:4028")
|
||||
.parse()
|
||||
.map_err(|e| format!("bad addr: {e}"))?;
|
||||
let t = Duration::from_secs(8);
|
||||
let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?;
|
||||
s.set_read_timeout(Some(t)).ok();
|
||||
@@ -300,7 +357,9 @@ fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
||||
Ok(String::from_utf8_lossy(&buf)
|
||||
.trim_matches('\u{0}')
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// The captured result of a timed subprocess run.
|
||||
@@ -391,24 +450,45 @@ mod tests {
|
||||
// The critical regression guard (round 18 #12): a wrong password or an
|
||||
// unreachable miner writes to stderr, leaves stdout empty, and exits
|
||||
// non-zero -- it must report failure, never "restored".
|
||||
let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false);
|
||||
let (ok, msg) =
|
||||
classify_braiins("", "Permission denied, please try again.", Some(255), false);
|
||||
assert!(!ok, "wrong password must not report success");
|
||||
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
|
||||
|
||||
let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false);
|
||||
let (ok, _) = classify_braiins(
|
||||
"",
|
||||
"ssh: connect to host 10.0.0.9 port 22: Connection refused",
|
||||
Some(255),
|
||||
false,
|
||||
);
|
||||
assert!(!ok, "unreachable miner must not report success");
|
||||
|
||||
let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false);
|
||||
let (ok, _) = classify_braiins(
|
||||
"",
|
||||
"ssh: Could not resolve hostname miner: Name or service not known",
|
||||
Some(255),
|
||||
false,
|
||||
);
|
||||
assert!(!ok, "unresolvable host must not report success");
|
||||
|
||||
// Genuine outcomes.
|
||||
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
|
||||
assert!(ok, "clean exit 0 is success");
|
||||
let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false);
|
||||
let (ok, _) = classify_braiins(
|
||||
"",
|
||||
"Connection to 10.0.0.5 closed by remote host.",
|
||||
None,
|
||||
false,
|
||||
);
|
||||
assert!(ok, "connection dropped mid-command (reboot) is success");
|
||||
let (ok, _) = classify_braiins("", "", None, true);
|
||||
assert!(ok, "timeout after the command started (reboot) is success");
|
||||
let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false);
|
||||
let (ok, _) = classify_braiins(
|
||||
"bash: uninstall.sh: command not found\n",
|
||||
"",
|
||||
Some(127),
|
||||
false,
|
||||
);
|
||||
assert!(!ok, "missing uninstall.sh is a failure");
|
||||
}
|
||||
|
||||
@@ -416,7 +496,10 @@ mod tests {
|
||||
fn firmware_selects_the_right_flow() {
|
||||
// The dispatcher only recognises the three revertible aftermarket
|
||||
// families; anything else has no restore path.
|
||||
let mk = |fw: &str| RestoreTarget { ip: "0.0.0.0".into(), firmware: fw.into() };
|
||||
let mk = |fw: &str| RestoreTarget {
|
||||
ip: "0.0.0.0".into(),
|
||||
firmware: fw.into(),
|
||||
};
|
||||
// Unknown firmware is rejected cleanly (no network attempt in the branch).
|
||||
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
|
||||
assert!(!ok);
|
||||
|
||||
+790
-452
File diff suppressed because it is too large
Load Diff
+960
-293
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user