Cleared all clippy findings in alkane-gui (cargo clippy --no-deps): mechanical
fixes via clippy --fix (redundant imports, useless format!, manual_contains,
manual_is_multiple_of, unnecessary_map_or, unused parens) plus manual fixes:
- type_complexity: factored the segment tuple into model::{Rgb, Segment} aliases.
- large_enum_variant: #[allow] on ScanMsg/RefreshMsg with a note -- Row is the
common variant, so boxing it to shrink the rare Started/Done would add an
allocation per miner on the hot path.
- dead code: removed unused SHAPE_PULSE_DOT, ColorKind::Accent, clear_op_status,
and RestoreMsg's unread `total`; kept the restore/access-probe cancel handles
(workers honour cancellation; UI stop control pending) under #[allow].
- question_mark, needless_range_loop, drop_non_drop, doc_lazy_continuation fixes.
Only vendored wx-rs warnings remain (out of scope). Added LICENSE-MIT and
LICENSE-APACHE (Cargo.toml already declares MIT OR Apache-2.0). 94 tests +
selftest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
286 lines
11 KiB
Rust
286 lines
11 KiB
Rust
//! Restore an aftermarket-firmware miner to stock (round 12 #8a).
|
|
//!
|
|
//! All three supported aftermarket firmwares ship a free, self-restoring revert
|
|
//! (the stock image is retained on-device at install time; no image is uploaded):
|
|
//! - VNish: POST /api/v1/unlock -> bearer -> POST /api/v1/firmware/remove
|
|
//! - LuxOS: luxminer :4028 {"command":"logon"} -> SessionID ->
|
|
//! {"command":"uninstallluxos","parameter":"<SessionID>"}
|
|
//! - Braiins: SSH `uninstall.sh` (re-flashes the on-NAND stock backup)
|
|
//!
|
|
//! DESTRUCTIVE: this removes the running aftermarket firmware and reboots the
|
|
//! miner to stock. It is gated behind a typed confirmation in the UI and runs on
|
|
//! a background thread so the reboot latency never blocks the event loop. The
|
|
//! flows are documented + live-confirmed in the miner-firmware wiki
|
|
//! (40-boot-os-and-build/firmware-install-remove-api and siblings).
|
|
|
|
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::time::Duration;
|
|
|
|
use crate::scan::fake_scan_enabled;
|
|
|
|
pub enum RestoreMsg {
|
|
Started,
|
|
Result { ip: String, ok: bool, detail: String },
|
|
Done,
|
|
}
|
|
|
|
pub struct RestoreHandle {
|
|
pub rx: Receiver<RestoreMsg>,
|
|
// The worker honours cancellation between miners (see `tc` below); a UI stop
|
|
// control is not wired yet, so the handle-side trigger is kept for when it is.
|
|
#[allow(dead_code)]
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl RestoreHandle {
|
|
#[allow(dead_code)]
|
|
pub fn stop(&self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// One miner to restore: its IP plus the firmware family ("VNish"/"LuxOS"/
|
|
/// "Braiins") that selects the revert flow.
|
|
pub struct RestoreTarget {
|
|
pub ip: String,
|
|
pub firmware: String,
|
|
}
|
|
|
|
/// Start restoring the given miners to stock on a background thread. `vnish_pass`
|
|
/// is the VNish web password; `ssh_user`/`ssh_pass` drive the Braiins SSH revert.
|
|
pub fn start_restore(
|
|
targets: Vec<RestoreTarget>,
|
|
vnish_pass: String,
|
|
ssh_user: String,
|
|
ssh_pass: String,
|
|
) -> RestoreHandle {
|
|
let (tx, rx) = channel();
|
|
let cancel = Arc::new(AtomicBool::new(false));
|
|
|
|
if fake_scan_enabled() {
|
|
// Offline demo: report each target as restored without touching anything.
|
|
let _ = tx.send(RestoreMsg::Started);
|
|
for t in targets {
|
|
let _ = tx.send(RestoreMsg::Result {
|
|
ip: t.ip,
|
|
ok: true,
|
|
detail: "restored to stock (demo)".into(),
|
|
});
|
|
}
|
|
let _ = tx.send(RestoreMsg::Done);
|
|
return RestoreHandle { rx, cancel };
|
|
}
|
|
|
|
let tc = cancel.clone();
|
|
let _ = std::thread::Builder::new()
|
|
.name("restore-stock".into())
|
|
.spawn(move || {
|
|
let _ = tx.send(RestoreMsg::Started);
|
|
for t in targets {
|
|
if tc.load(Ordering::Relaxed) {
|
|
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() {
|
|
return;
|
|
}
|
|
}
|
|
let _ = tx.send(RestoreMsg::Done);
|
|
});
|
|
RestoreHandle { rx, cancel }
|
|
}
|
|
|
|
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)
|
|
} else if fw.contains("lux") {
|
|
restore_luxos(&t.ip)
|
|
} 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))
|
|
}
|
|
}
|
|
|
|
/// VNish: unlock -> bearer -> firmware/remove (self-restores + reboots ~3 s).
|
|
fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
|
|
let unlock = match 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"),
|
|
]) {
|
|
Ok(s) => s,
|
|
Err(e) => return (false, format!("unlock request failed: {e}")),
|
|
};
|
|
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());
|
|
let Some(token) = token else {
|
|
return (false, "VNish unlock rejected (wrong web password?)".into());
|
|
};
|
|
match curl(&[
|
|
"-s", "--connect-timeout", "5", "--max-time", "12",
|
|
"-X", "POST", "-H", &format!("Authorization: Bearer {token}"),
|
|
&format!("http://{ip}/api/v1/firmware/remove"),
|
|
]) {
|
|
// The miner reverts + reboots after ~3 s; the response is {"after":N}.
|
|
Ok(resp) if resp.contains("after") => (true, "reverting to stock (~3 s)".into()),
|
|
Ok(resp) => (false, format!("firmware/remove returned: {}", resp.trim())),
|
|
Err(e) => (false, format!("firmware/remove failed: {e}")),
|
|
}
|
|
}
|
|
|
|
/// LuxOS: credential-free luxminer session, then uninstallluxos (reboots to stock).
|
|
fn restore_luxos(ip: &str) -> (bool, String) {
|
|
let logon = match lux_rpc(ip, "{\"command\":\"logon\"}") {
|
|
Ok(s) => s,
|
|
Err(e) => return (false, format!("logon failed: {e}")),
|
|
};
|
|
let session = serde_json::from_str::<serde_json::Value>(&logon)
|
|
.ok()
|
|
.and_then(|v| {
|
|
v.pointer("/SESSION/0/SessionID")
|
|
.or_else(|| v.pointer("/Session/0/SessionID"))
|
|
.and_then(|s| s.as_str())
|
|
.map(str::to_string)
|
|
});
|
|
let Some(session) = session.filter(|s| !s.is_empty()) else {
|
|
return (false, format!("no SessionID in logon response: {}", logon.trim()));
|
|
};
|
|
let cmd = format!("{{\"command\":\"uninstallluxos\",\"parameter\":\"{session}\"}}");
|
|
match lux_rpc(ip, &cmd) {
|
|
// Code 350 "Uninstalling LuxOS"; the miner reboots + reverts in background.
|
|
Ok(resp) if resp.contains("350") || resp.to_lowercase().contains("uninstall") => {
|
|
(true, "uninstalling LuxOS (reboots to stock)".into())
|
|
}
|
|
Ok(resp) => (false, format!("uninstallluxos returned: {}", resp.trim())),
|
|
Err(e) => (false, format!("uninstallluxos failed: {e}")),
|
|
}
|
|
}
|
|
|
|
/// 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());
|
|
}
|
|
let target = format!("{user}@{ip}");
|
|
// uninstall.sh is on Braiins OS+'s PATH; run it non-interactively.
|
|
let mut cmd = Command::new("sshpass");
|
|
cmd.arg("-p").arg(pass).arg("ssh");
|
|
cmd.args([
|
|
"-o", "StrictHostKeyChecking=no",
|
|
"-o", "UserKnownHostsFile=/dev/null",
|
|
"-o", "ConnectTimeout=8",
|
|
&target,
|
|
"uninstall.sh || /sbin/uninstall.sh",
|
|
]);
|
|
match run_with_timeout(cmd, Duration::from_secs(60)) {
|
|
Ok(out) => {
|
|
let s = String::from_utf8_lossy(&out).to_lowercase();
|
|
if s.contains("not found") || s.contains("no such") {
|
|
(false, "uninstall.sh not found on the miner".into())
|
|
} else {
|
|
(true, "ran uninstall.sh (reverts to stock + reboots)".into())
|
|
}
|
|
}
|
|
Err(e) => {
|
|
// A reboot mid-command commonly drops the SSH connection; treat a
|
|
// connection-closed error after the command as likely success.
|
|
if e.contains("closed") || e.contains("reset") || e.contains("timed out") {
|
|
(true, "SSH dropped (miner likely rebooting to stock)".into())
|
|
} else {
|
|
(false, format!("SSH uninstall failed: {e}"))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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 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();
|
|
s.set_write_timeout(Some(t)).ok();
|
|
s.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
|
|
let mut buf = Vec::new();
|
|
let mut chunk = [0u8; 4096];
|
|
loop {
|
|
match s.read(&mut chunk) {
|
|
Ok(0) => break,
|
|
Ok(n) => {
|
|
buf.extend_from_slice(&chunk[..n]);
|
|
if buf.len() > 1 << 16 {
|
|
break;
|
|
}
|
|
}
|
|
Err(_) => break,
|
|
}
|
|
}
|
|
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
|
}
|
|
|
|
/// curl with a wall-clock cap (small responses; no pipe-drain thread needed).
|
|
fn curl(args: &[&str]) -> Result<String, String> {
|
|
let mut cmd = Command::new("curl");
|
|
cmd.args(args);
|
|
run_with_timeout(cmd, Duration::from_secs(15)).map(|o| String::from_utf8_lossy(&o).into_owned())
|
|
}
|
|
|
|
/// Run a command, capture stdout, with a hard wall-clock timeout.
|
|
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result<Vec<u8>, String> {
|
|
cmd.stdout(std::process::Stdio::piped());
|
|
cmd.stderr(std::process::Stdio::piped());
|
|
let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?;
|
|
let mut stdout = child.stdout.take().ok_or("no stdout")?;
|
|
let reader = std::thread::spawn(move || {
|
|
let mut b = Vec::new();
|
|
let _ = stdout.read_to_end(&mut b);
|
|
b
|
|
});
|
|
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 out = reader.join().unwrap_or_default();
|
|
if timed_out && out.is_empty() {
|
|
return Err("timed out".into());
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
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() };
|
|
// Unknown firmware is rejected cleanly (no network attempt in the branch).
|
|
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
|
|
assert!(!ok);
|
|
assert!(detail.contains("no restore-to-stock path"), "{detail}");
|
|
}
|
|
}
|