From a75fe5ba52a49d89f20946ee373c3d7201f54c0e Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 20 Sep 2026 11:39:49 -0600 Subject: [PATCH] GUI round 12 (#8a): restore aftermarket firmware to stock (right-click) Adds a right-click "Restore to stock firmware..." action for aftermarket-firmware miners, behind a strong typed (RESTORE) confirmation that lists exactly which miners will be reverted. All three supported firmwares self-restore for free (the stock image is retained on-device; no image is uploaded), per the live-confirmed flows in the miner-firmware wiki: - VNish: POST /api/v1/unlock -> bearer -> POST /api/v1/firmware/remove (~3 s) - LuxOS: luxminer :4028 logon -> uninstallluxos (credential-free) - Braiins: SSH `uninstall.sh` (re-flashes the on-NAND stock backup) New crates/alkane-gui/src/restore.rs runs the revert on a background thread with a result channel and a fake-scan demo path; VNish password reuses the round 12 #13 per-firmware default, Braiins uses the saved SSH login. The menu item only appears when the selection includes a revertible firmware. Also fixes an event-routing bug introduced in #12/#8a: the log-viewer Close and restore OK/Cancel buttons were mistakenly handled in the MenuItem match instead of ButtonClicked, so they never fired -- this restores #12's log-viewer Close button too. Moved them to the ButtonClicked match. Verified under Xvfb + openbox: the menu item shows for VNish/LuxOS/Braiins rows; the confirm dialog renders the targets and typed gate; typing RESTORE runs the (fake) revert and closes the dialog; a wrong value is rejected and the dialog stays open. restore unit test + GUI self-test pass. NOTE: no live restore was run -- the designated test range 10.2.1.0/24 is currently empty, and production miners were not touched; the live flash awaits a unit in that range. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- crates/alkane-gui/src/main.rs | 1 + crates/alkane-gui/src/restore.rs | 282 +++++++++++++++++++++++++++++++ crates/alkane-gui/src/ui.rs | 148 +++++++++++++++- 3 files changed, 430 insertions(+), 1 deletion(-) create mode 100644 crates/alkane-gui/src/restore.rs diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 446e1450..9ed9a637 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -9,6 +9,7 @@ mod model; mod naming; mod pic_probe; mod presets; +mod restore; mod scan; mod ui; diff --git a/crates/alkane-gui/src/restore.rs b/crates/alkane-gui/src/restore.rs new file mode 100644 index 00000000..12e92c84 --- /dev/null +++ b/crates/alkane-gui/src/restore.rs @@ -0,0 +1,282 @@ +//! 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":""} +//! - 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 { total: usize }, + Result { ip: String, ok: bool, detail: String }, + Done { total: usize }, +} + +pub struct RestoreHandle { + pub rx: Receiver, + cancel: Arc, +} + +impl RestoreHandle { + 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, + vnish_pass: String, + ssh_user: String, + ssh_pass: String, +) -> RestoreHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + + if fake_scan_enabled() { + // Offline demo: report each target as restored without touching anything. + let _ = tx.send(RestoreMsg::Started { total }); + 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 { total }); + return RestoreHandle { rx, cancel }; + } + + let tc = cancel.clone(); + let _ = std::thread::Builder::new() + .name("restore-stock".into()) + .spawn(move || { + let _ = tx.send(RestoreMsg::Started { total }); + 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 { total }); + }); + 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::(&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::(&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 { + 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 { + 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, 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}"); + } +} diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index b6739c87..fdffc20a 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -3,6 +3,7 @@ use crate::credentials; use crate::model::*; +use crate::restore; use crate::scan::{self, ScanMsg}; use asic_rs::core::data::firmware::FirmwareImage; use std::cell::RefCell; @@ -59,6 +60,10 @@ 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; +// Restore aftermarket firmware to stock (round 12 #8a); strong typed confirm. +const ID_CTX_RESTORE_STOCK: i32 = 735; +const ID_RESTORE_OK: i32 = 786; +const ID_RESTORE_CANCEL: i32 = 787; // SSH PIC-probe credentials dialog. const ID_PICSSH_OK: i32 = 780; const ID_PICSSH_CANCEL: i32 = 781; @@ -156,6 +161,19 @@ fn ratio_color(pal: &Palette, ratio: f64) -> (u8, u8, u8) { } } +/// Whether a firmware family has a supported restore-to-stock path (round 12 +/// #8a): VNish/WildRose (HTTP), LuxOS (:4028), Braiins (SSH). Others (stock, +/// ePIC, etc.) have no in-tool revert here. +fn firmware_is_restorable(family: &str) -> bool { + let f = family.trim().to_ascii_lowercase(); + f.contains("vnish") + || f.contains("wildrose") + || f.contains("anthill") + || f.contains("lux") + || f.contains("braiins") + || f.contains("bos") +} + /// Colour for a firmware family (round-10 #3). Stock -- and any family we don't /// recognise -- returns None so the Firmware cell keeps the theme default text /// colour (which tracks light/dark and focus). The rest get a distinctive, @@ -593,6 +611,11 @@ pub struct App { pending_pic_targets: Vec<(String, String)>, // The API log viewer dialog (round 12 #12). logview_dialog: Widget, + // Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog. + restore: Option, + restore_dialog: Widget, + restore_input: Widget, + pending_restore: Vec, picssh_dialog: Widget, picssh_user_input: Widget, picssh_pass_input: Widget, @@ -865,6 +888,10 @@ pub fn build(frame: Widget) -> App { pic_probe: None, pending_pic_targets: Vec::new(), logview_dialog: frame, + restore: None, + restore_dialog: frame, + restore_input: frame, + pending_restore: Vec::new(), picssh_dialog: frame, picssh_user_input: frame, picssh_pass_input: frame, @@ -1263,6 +1290,12 @@ impl App { 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)..."); + // Restore aftermarket firmware to stock (round 12 #8a): offered only when + // the selection includes a revertible aftermarket firmware. + if self.selected_rows().iter().any(|r| firmware_is_restorable(&r.firmware)) { + menu.menu_append_separator(); + menu.menu_append(ID_CTX_RESTORE_STOCK, "Restore to stock firmware..."); + } // Config actions common to the whole selection (capability // intersection): an action is offered only if every selected miner // supports it. @@ -1415,6 +1448,112 @@ impl App { Some(dlg) } + /// Strong typed confirmation before restoring aftermarket firmware to stock + /// (round 12 #8a): the operator must type RESTORE, on top of seeing exactly + /// which miners (IP + firmware) will be reverted. DESTRUCTIVE + reboots. + fn build_restore_confirm_dialog(&mut self) -> Option { + let targets: Vec = self + .selected_rows() + .iter() + .filter(|r| firmware_is_restorable(&r.firmware)) + .map(|r| restore::RestoreTarget { ip: r.ip.clone(), firmware: r.firmware.clone() }) + .collect(); + if targets.is_empty() { + wx_rs::set_status_text("select a VNish / LuxOS / Braiins miner to restore"); + return None; + } + let n = targets.len(); + let list = targets + .iter() + .map(|t| format!(" {} ({})", t.ip, t.firmware)) + .collect::>() + .join("\n"); + self.pending_restore = targets; + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Restore to stock firmware"); + let root = Widget::box_sizer(true); + let msg = format!( + "Restore these {n} miner(s) to STOCK firmware? This removes the aftermarket firmware and reboots the miner; it interrupts mining and cannot be undone remotely for all firmwares.\n\n{list}\n\nType RESTORE to confirm:" + ); + root.add(Widget::static_text(dlg, &msg), 0, sf::BORDER_ALL, 12); + let input = Widget::text_ctrl(dlg, false); + input.set_min_size(200, -1); + root.add(input, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, "Restore to stock", ID_RESTORE_OK), 0, sf::BORDER_ALL, 6); + btns.add(Widget::button(dlg, "Cancel", ID_RESTORE_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(460, 200); + dlg.fit(dlg); + self.restore_dialog = dlg; + self.restore_input = input; + Some(dlg) + } + + /// Apply the restore confirmation: only start if the operator typed RESTORE + /// exactly. Resolves the per-firmware credentials (VNish password from the + /// round 12 #13 defaults; Braiins SSH login from the saved SSH creds). + fn apply_restore_confirm(&mut self) { + if self.restore_input.get_value().trim() != "RESTORE" { + wx_rs::set_status_text("type RESTORE exactly to confirm"); + return; + } + let targets = std::mem::take(&mut self.pending_restore); + if targets.is_empty() { + self.restore_dialog.close(0); + return; + } + 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 (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default(); + let n = targets.len(); + self.restore_dialog.close(1); + self.restore = Some(restore::start_restore(targets, vnish_pass, ssh_user, ssh_pass)); + wx_rs::set_status_text(&format!("restoring {n} miner(s) to stock...")); + } + + /// Drain restore-to-stock results into the status bar. + fn drain_restore(&mut self) { + let Some(h) = &self.restore else { return }; + let mut done = false; + let mut oks = 0usize; + let mut fails: Vec = Vec::new(); + while let Ok(msg) = h.rx.try_recv() { + match msg { + restore::RestoreMsg::Started { total } => { + wx_rs::set_status_text(&format!("restoring {total} miner(s) to stock...")); + } + restore::RestoreMsg::Result { ip, ok, detail } => { + if ok { + oks += 1; + } else { + fails.push(format!("{ip}: {detail}")); + } + } + restore::RestoreMsg::Done { .. } => done = true, + } + } + if done { + self.restore = None; + if fails.is_empty() { + wx_rs::set_status_text(&format!("restore-to-stock: {oks} started; miners reboot to stock")); + } else { + self.set_error_indicator(&format!("restore: {} failed", fails.len())); + wx_rs::set_status_text(&format!( + "restore-to-stock: {oks} ok, {} failed ({})", + fails.len(), + fails.join("; ") + )); + } + } + } + /// 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 @@ -1650,7 +1789,7 @@ impl App { 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_RESTORE_STOCK => return self.build_restore_confirm_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if // any scan / refresh / action is running (re-checked at confirm). @@ -2285,6 +2424,7 @@ impl App { self.drain_refresh(); self.drain_pic_probe(); self.drain_access_probe(); + self.drain_restore(); if self.scanning { return; // status already shows scan progress } @@ -3129,6 +3269,12 @@ impl App { 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_LOGVIEW_CLOSE => self.logview_dialog.close(1), + ID_RESTORE_OK => self.apply_restore_confirm(), + ID_RESTORE_CANCEL => { + self.pending_restore.clear(); + self.restore_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"),