diff --git a/crates/alkane-gui/src/bench_sequence.rs b/crates/alkane-gui/src/bench_sequence.rs new file mode 100644 index 00000000..d251d8e9 --- /dev/null +++ b/crates/alkane-gui/src/bench_sequence.rs @@ -0,0 +1,332 @@ +//! Headless bench automation (`ALKANE_BENCH_SEQUENCE`): drive the GUI's real +//! install/restore operation layer (`stock_ops`) through the A113D network-only +//! install <-> flag-restore cycle, with no window. This exercises the GUI +//! operator flow end-to-end against real hardware, for bench proofs, without the +//! wx event loop (the worker functions stream progress over a channel, exactly +//! as the UI drains them). +//! +//! Spec: `ALKANE_BENCH_SEQUENCE=" [iterations]"`. +//! The alkane root credential is read from the saved SSH credentials file. +//! +//! On the A113D, "restore to stock" is the one-byte flag flip (the install +//! overwrites no stock partition), so the cycle is: install (stock -> alkane) -> +//! verify alkane -> restore (flag flip -> stock) -> verify stock. + +use std::io::Read; +use std::net::TcpStream; +use std::path::PathBuf; +use std::process::Command; +use std::time::{Duration, Instant}; + +use crate::credentials; +use crate::stock_ops::{self, AfwSource, StockHandle, StockMsg}; + +/// Drain a `StockHandle` to completion, printing progress; returns true iff +/// every board reported ok and at least one `Result` arrived. +fn drive(label: &str, handle: StockHandle) -> bool { + let mut ok = true; + let mut saw = false; + loop { + match handle.rx.recv() { + Ok(StockMsg::Started) => println!(" [{label}] started"), + Ok(StockMsg::Progress(s)) => println!(" [{label}] {s}"), + Ok(StockMsg::Result { ip, ok: r, detail }) => { + saw = true; + ok = ok && r; + println!( + " [{label}] {ip}: {} - {detail}", + if r { "OK" } else { "FAIL" } + ); + } + Ok(StockMsg::Done) => break, + Err(_) => { + println!(" [{label}] channel closed early"); + ok = false; + break; + } + } + } + ok && saw +} + +/// Read the SSH identification banner (no auth), e.g. `SSH-2.0-dropbear_2026.93`. +fn ssh_banner(host: &str) -> Option { + let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?; + let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?; + let mut buf = [0u8; 256]; + let n = stream.read(&mut buf).ok()?; + if n == 0 { + return None; + } + Some( + String::from_utf8_lossy(&buf[..n]) + .lines() + .next() + .unwrap_or("") + .trim() + .to_string(), + ) +} + +/// HTTP server header probe (stock serves lighttpd / an antMiner realm). +fn http_is_stock(host: &str) -> Option { + let out = Command::new("curl") + .args([ + "-sS", + "-m", + "6", + "-o", + "/dev/null", + "-D", + "-", + &format!("http://{host}/"), + ]) + .output() + .ok()?; + let h = String::from_utf8_lossy(&out.stdout).to_lowercase(); + if h.is_empty() { + None + } else if h.contains("lighttpd") || h.contains("antminer configuration") { + Some(true) + } else { + Some(false) + } +} + +/// Classify the board: `Some(true)` = looks like genuine stock, `Some(false)` = +/// looks like alkane, `None` = no decisive answer (e.g. mid-reboot). +/// +/// Primary signal is the SSH banner: stock A113D is `dropbear_2018.76`; alkane +/// ships a much newer dropbear. HTTP (lighttpd) is a stock fallback. +fn classify(host: &str) -> (String, Option) { + let banner = ssh_banner(host); + if let Some(b) = &banner { + let lb = b.to_lowercase(); + if lb.contains("dropbear_2018") || lb.contains("dropbear_2019") { + return (format!("ssh \"{b}\" -> stock"), Some(true)); + } + if lb.contains("dropbear") || lb.contains("openssh") { + return (format!("ssh \"{b}\" -> alkane"), Some(false)); + } + } + match http_is_stock(host) { + Some(true) => ("http lighttpd/antMiner -> stock".to_string(), Some(true)), + Some(false) => ("http non-stock -> alkane".to_string(), Some(false)), + None => ( + banner + .map(|b| format!("ssh \"{b}\" (unclassified), no http")) + .unwrap_or_else(|| "no ssh, no http (mid-reboot?)".to_string()), + None, + ), + } +} + +/// The MAC (lladdr) the kernel has cached for `host` (pings first to populate). +fn mac_of(host: &str) -> Option { + let _ = Command::new("ping") + .args(["-c", "1", "-W", "1", host]) + .output(); + let out = Command::new("ip") + .args(["neigh", "show", host]) + .output() + .ok()?; + let s = String::from_utf8_lossy(&out.stdout); + let mut it = s.split_whitespace(); + while let Some(t) = it.next() { + if t == "lladdr" { + return it.next().map(|m| m.to_lowercase()); + } + } + None +} + +/// Populate the neighbour table by parallel-pinging the /24 of `sample` (a bench +/// board can take a different DHCP lease across a reboot, so we must re-find it). +fn sweep_subnet(sample: &str) { + let base = match sample.rsplit_once('.') { + Some((net, _)) => net.to_string(), + None => return, + }; + let mut kids = Vec::new(); + for h in 2..=254 { + if let Ok(c) = Command::new("ping") + .args(["-c", "1", "-W", "1", &format!("{base}.{h}")]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + { + kids.push(c); + } + } + for mut c in kids { + let _ = c.wait(); + } +} + +/// Current IPv4 for `mac` from the neighbour table, if present. +fn ip_for_mac(mac: &str) -> Option { + let out = Command::new("ip").args(["neigh"]).output().ok()?; + let s = String::from_utf8_lossy(&out.stdout); + let mac = mac.to_lowercase(); + for line in s.lines() { + if line.to_lowercase().contains(&mac) { + if let Some(ip) = line.split_whitespace().next() { + if ip.contains('.') { + return Some(ip.to_string()); + } + } + } + } + None +} + +/// Poll until the board (located by MAC, so a changed DHCP lease is followed) +/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's +/// current IP, a description, and whether the target state was reached. +fn wait_for( + mac: Option<&str>, + fallback: &str, + want_stock: bool, + timeout: Duration, +) -> (String, String, bool) { + let deadline = Instant::now() + timeout; + let mut ip = fallback.to_string(); + let mut swept = Instant::now() - Duration::from_secs(60); + loop { + // Re-locate by MAC; sweep the subnet at most every ~25s to catch a new lease. + if let Some(m) = mac { + if ip_for_mac(m).is_none() && swept.elapsed() >= Duration::from_secs(25) { + sweep_subnet(fallback); + swept = Instant::now(); + } + if let Some(found) = ip_for_mac(m) { + ip = found; + } + } + let (desc, is_stock) = classify(&ip); + let line = format!("[{ip}] {desc}"); + if is_stock == Some(want_stock) { + return (ip, line, true); + } + if Instant::now() >= deadline { + return (ip, line, false); + } + std::thread::sleep(Duration::from_secs(5)); + } +} + +pub fn run(spec: &str) -> i32 { + let mut it = spec.split_whitespace(); + let host = match it.next() { + Some(h) => h.to_string(), + None => { + eprintln!("ALKANE_BENCH_SEQUENCE=\" [iterations]\""); + return 2; + } + }; + let afw = match it.next() { + Some(a) => PathBuf::from(a), + None => { + eprintln!("missing local .afw path"); + return 2; + } + }; + let iterations: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1); + let board = "a113d".to_string(); + // Install reaches STOCK via the compiled-in from-stock method; pass the saved + // board SSH credential through to it. + let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p); + // The flag-restore reaches the running ALKANE board over SSH as `root` - a + // DIFFERENT credential from the stock login. Alkane bench images bake + // root/alkane; allow an override via ALKANE_ROOT_PASSWORD. + let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD") + .ok() + .or_else(|| Some("alkane".to_string())); + + println!("== A113D headless GUI bench sequence (network-only install <-> flag-restore) =="); + println!( + "host={host} afw={} board={board} iterations={iterations} stock_cred={} alkane_cred={}", + afw.display(), + if stock_password.is_some() { "loaded" } else { "none" }, + if alkane_password.is_some() { "set" } else { "none" } + ); + if !afw.exists() { + eprintln!("afw not found: {}", afw.display()); + return 2; + } + + // Resolve the board's MAC now (on stock) so we can re-find it after each + // reboot even if its DHCP lease changes under alkane. + let mac = mac_of(&host); + println!( + "board MAC: {}", + mac.as_deref() + .unwrap_or("unknown (will use the fixed host)") + ); + + let boot_timeout = Duration::from_secs(300); + let mut all_ok = true; + + for i in 1..=iterations { + println!("\n-- iteration {i}/{iterations} --"); + + // 1. install (stock -> alkane) through the GUI operation layer + println!("[1/4] install: stock -> alkane"); + let h = stock_ops::start_install( + vec![host.clone()], + board.clone(), + AfwSource::Local(afw.clone()), + true, // allow unsigned (bench image) + stock_password.clone(), + false, // not an in-place update + ); + if !drive("install", h) { + all_ok = false; + println!("[1/4] install FAILED; aborting"); + break; + } + + // 2. verify alkane is live (board reboots into alkane) + println!( + "[2/4] verify alkane (awaiting reboot, up to {}s)...", + boot_timeout.as_secs() + ); + let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout); + println!( + " {desc} => {}", + if ok { "ALKANE" } else { "NOT ALKANE (fail)" } + ); + all_ok = all_ok && ok; + + // 3. restore (alkane -> stock) flag-flip at the board's CURRENT address + println!("[3/4] restore: alkane -> stock (flag flip) at {alkane_ip}"); + let h = stock_ops::start_restore_flag(vec![alkane_ip.clone()], alkane_password.clone()); + if !drive("restore", h) { + all_ok = false; + println!("[3/4] restore FAILED"); + } + + // 4. verify stock is back + println!( + "[4/4] verify stock (awaiting reboot, up to {}s)...", + boot_timeout.as_secs() + ); + let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout); + println!( + " {desc} => {}", + if ok { "STOCK" } else { "NOT STOCK (fail)" } + ); + all_ok = all_ok && ok; + } + + println!( + "\n== BENCH RESULT: {} ==", + if all_ok { "PASS" } else { "FAIL" } + ); + if all_ok { + 0 + } else { + 1 + } +} diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 02c53c5f..092ffcf1 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -8,6 +8,7 @@ mod access_probe; mod alkane_detect; mod askpass; +mod bench_sequence; mod bug_report; mod credentials; mod export; @@ -41,6 +42,13 @@ fn main() { std::process::exit(run_selftest()); } + // Headless bench automation: drive the real install/restore operation layer + // (stock_ops) through the A113D network-only install <-> flag-restore cycle + // against real hardware, with no window. See bench_sequence.rs. + if let Some(spec) = std::env::var_os("ALKANE_BENCH_SEQUENCE") { + std::process::exit(bench_sequence::run(&spec.to_string_lossy())); + } + // Headless access-probe check: `ALKANE_ACCESS_PROBE=" "` prints the // lock state the real access probe computes (no GUI, no wx), so the WhatsMiner // :4028 token check and the Antminer digest check can be verified directly. @@ -123,9 +131,14 @@ fn run_selftest() -> i32 { /// True when the process runs one of the headless check modes instead of the GUI. fn headless_mode() -> bool { - ["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"] - .iter() - .any(|v| std::env::var_os(v).is_some()) + [ + "ALKANE_SELFTEST", + "ALKANE_ACCESS_PROBE", + "ALKANE_LOG_SCAN", + "ALKANE_BENCH_SEQUENCE", + ] + .iter() + .any(|v| std::env::var_os(v).is_some()) } /// A Windows GUI-subsystem process has no console, so output from the headless diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index abb37cd7..b09b685a 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -24,8 +24,13 @@ use crate::scan::fake_scan_enabled; /// Control boards alkane-os can be installed onto from stock (mirrors the CLI's /// `SUPPORTED`). Only these are offered as install targets. -pub const SUPPORTED_BOARDS: &[(&str, &str)] = - &[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")]; +pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[ + ("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"), + ( + "a113d", + "Antminer S19j Pro (Amlogic A113D/AXG control board)", + ), +]; /// The default install board when the user has not chosen another. pub const DEFAULT_BOARD: &str = "zynq-7010"; @@ -408,3 +413,65 @@ pub fn start_restore_onboard(ips: Vec, password: Option) -> Stoc } StockHandle { rx, cancel } } + +/// Restore the given alkane A113D boards to genuine Bitmain stock, over the +/// network, by clearing the one-byte boot flag in-band from the running alkane +/// OS. The A113D install overwrites no stock partition, so this flag flip is the +/// complete restore: clear `ALAN`, reboot, and stock boots via `storeboot` from +/// the untouched `boot` MTD. No vendor firmware file or on-board backup needed. +/// `password`, if set, is the board's alkane root credential. +pub fn start_restore_flag(ips: Vec, password: Option) -> StockHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + + if fake_scan_enabled() { + let _ = tx.send(StockMsg::Started); + for ip in ips { + let _ = tx.send(StockMsg::Result { + ip, + ok: true, + detail: "restored to stock (flag flip, demo)".into(), + }); + } + let _ = tx.send(StockMsg::Done); + return StockHandle { rx, cancel }; + } + + let tc = cancel.clone(); + let err_tx = tx.clone(); + let spawned = std::thread::Builder::new() + .name("restore-flag".into()) + .spawn(move || { + let _ = tx.send(StockMsg::Started); + for ip in ips { + if tc.load(Ordering::Relaxed) { + break; + } + let _ = tx.send(StockMsg::Progress(format!( + "restoring {ip} to stock (clearing the alkane boot flag)..." + ))); + let (ok, detail) = match stock::restore_aml_flag(&ip, password.as_deref()) { + Ok(()) => ( + true, + "restored to stock (flag cleared, rebooting; verify over the network)" + .to_string(), + ), + Err(e) => (false, format!("restore failed: {e}")), + }; + if tx.send(StockMsg::Result { ip, ok, detail }).is_err() { + return; + } + } + let _ = tx.send(StockMsg::Done); + }); + + if spawned.is_err() { + let _ = err_tx.send(StockMsg::Result { + ip: String::new(), + ok: false, + detail: "could not start the restore worker thread".into(), + }); + let _ = err_tx.send(StockMsg::Done); + } + StockHandle { rx, cancel } +}