diff --git a/crates/alkane-gui/src/alkane_detect.rs b/crates/alkane-gui/src/alkane_detect.rs new file mode 100644 index 00000000..268f04c9 --- /dev/null +++ b/crates/alkane-gui/src/alkane_detect.rs @@ -0,0 +1,305 @@ +//! Boards running Alkane OS on the network, and which alkane-os actions apply to +//! a scanned row. +//! +//! asic-rs recognises miners by their cgminer socket (:4028) or a vendor web UI. +//! A board running Alkane OS keeps its cgminer-compatible socket on loopback and +//! serves its own console, so asic-rs reports nothing at that address and the +//! board never appeared in the fleet. This probe finds it over plain HTTP: +//! - `GET /api/identity` (alkane-os 0.1.2 and later): os, os_version, board, +//! sdk_revision, hostname, mac, kernel; +//! - otherwise the cgminer-style `GET /api/summary`, whose STATUS Description +//! is "alkane-os" (earlier images: found, but the board family is unknown). +//! +//! Both endpoints are public and read-only on the board. + +use crate::model::MinerRow; +use serde_json::{json, Value}; +use std::net::IpAddr; +use std::time::Duration; + +/// Firmware family shown for a board running Alkane OS. +pub const FIRMWARE: &str = "Alkane"; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); +const READ_TIMEOUT: Duration = Duration::from_secs(4); +const MAX_RESPONSE: usize = 64 * 1024; + +/// Probe `ip` for Alkane OS. Returns a row for the fleet table, or None when the +/// address is not an Alkane board (or does not answer on :80). +pub async fn detect(ip: IpAddr) -> Option { + if let Some(doc) = get_json(ip, "/api/identity").await { + if doc.get("os").and_then(Value::as_str) == Some("alkane-os") { + return Some(row_from_identity(ip, &doc)); + } + } + let summary = get_json(ip, "/api/summary").await?; + if is_alkane_summary(&summary) { + return Some(row_from_identity(ip, &json!({}))); + } + None +} + +/// The cgminer-style summary an Alkane board serves names "alkane-os" in its +/// STATUS Description. +fn is_alkane_summary(doc: &Value) -> bool { + doc.get("STATUS") + .and_then(Value::as_array) + .and_then(|status| status.first()) + .and_then(|entry| entry.get("Description")) + .and_then(Value::as_str) + == Some("alkane-os") +} + +/// Control-board labels (cpu, code) for an Alkane board family, matching the +/// labels the scan gives the same board on stock firmware. +fn board_labels(board: &str) -> (&'static str, &'static str) { + match board { + "zynq-7010" => ("XIL", "C49"), + "am335x" => ("BBB", "C77"), + "cv1835" => ("CVI", "C88"), + "a113d" => ("AML", "C76"), + _ => ("", ""), + } +} + +fn row_from_identity(ip: IpAddr, doc: &Value) -> MinerRow { + let text = |key: &str| { + doc.get(key) + .and_then(Value::as_str) + .unwrap_or("") + .trim() + .to_string() + }; + let board = text("board"); + let (cpu, code) = board_labels(&board); + let control_board = if cpu.is_empty() { + board.clone() + } else { + format!("{cpu} ({code})") + }; + MinerRow { + ip: ip.to_string(), + // The Alkane-supported control boards are all Bitmain (Antminer) boards. + brand: if cpu.is_empty() { + String::new() + } else { + "Antminer".to_string() + }, + firmware: FIRMWARE.to_string(), + fw_version: text("os_version"), + api_version: "alkane-os".to_string(), + mac: text("mac"), + hostname: text("hostname"), + control_board, + cpu: cpu.to_string(), + board_code: code.to_string(), + alkane_board: Some(board), + ..Default::default() + } +} + +/// HTTP/1.0 GET on :80 returning the JSON body of a 200 reply. +async fn get_json(ip: IpAddr, path: &str) -> Option { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let connect = tokio::net::TcpStream::connect((ip, 80)); + let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect) + .await + .ok()? + .ok()?; + let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.ok()?; + let mut raw = Vec::new(); + let _ = tokio::time::timeout(READ_TIMEOUT, async { + let mut chunk = [0u8; 4096]; + loop { + match stream.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + raw.extend_from_slice(&chunk[..n]); + if raw.len() > MAX_RESPONSE { + break; + } + } + } + } + }) + .await; + parse_http_json(&raw) +} + +fn parse_http_json(raw: &[u8]) -> Option { + let text = std::str::from_utf8(raw).ok()?; + let (head, body) = text.split_once("\r\n\r\n")?; + let status = head.lines().next()?; + if status.split_whitespace().nth(1) != Some("200") { + return None; + } + serde_json::from_str(body.trim()).ok() +} + +/// Whether the row is a board running Alkane OS (found by `detect`). +pub fn is_alkane(row: &MinerRow) -> bool { + row.alkane_board.is_some() +} + +/// The alkane-os board family the row's control board is, when it can be told: +/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17 +/// era, "XIL (C49)") control board. +pub fn board_family(row: &MinerRow) -> Option { + if let Some(board) = &row.alkane_board { + return (!board.is_empty()).then(|| board.clone()); + } + if !row.brand.to_ascii_lowercase().contains("antminer") { + return None; + } + if row.cpu == "XIL" && row.board_code == "C49" { + return Some("zynq-7010".to_string()); + } + // A stock S17 whose miner software is down (no hashboards attached: it + // restart-loops) reports its model but no control board. Its model then + // decides; a control board that IS reported always wins above. + if row.cpu.is_empty() && is_zynq_7010_model(&row.model) { + return Some("zynq-7010".to_string()); + } + None +} + +/// Stock models built only on the Zynq-7010 (XIL C49) control board. +fn is_zynq_7010_model(model: &str) -> bool { + matches!(model.trim(), "S17" | "S17 Pro" | "T17") +} + +/// Whether alkane-os can be installed on the row's board: its control board is +/// one the toolkit supports. +pub fn install_supported(row: &MinerRow) -> bool { + board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ip() -> IpAddr { + "10.0.0.5".parse().unwrap() + } + + #[test] + fn parses_a_200_json_reply_only() { + let ok = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"os\":\"alkane-os\"}"; + assert_eq!(parse_http_json(ok).unwrap()["os"], "alkane-os"); + let denied = b"HTTP/1.1 401 Unauthorized\r\n\r\n{\"os\":\"alkane-os\"}"; + assert!(parse_http_json(denied).is_none()); + let html = b"HTTP/1.1 200 OK\r\n\r\nx"; + assert!(parse_http_json(html).is_none()); + assert!(parse_http_json(b"garbage").is_none()); + } + + #[test] + fn recognises_the_alkane_summary() { + let alkane = json!({"STATUS":[{"Code":0,"Description":"alkane-os","STATUS":"S"}]}); + assert!(is_alkane_summary(&alkane)); + let cgminer = json!({"STATUS":[{"Description":"cgminer 4.11.1","STATUS":"S"}]}); + assert!(!is_alkane_summary(&cgminer)); + assert!(!is_alkane_summary(&json!({}))); + } + + #[test] + fn identity_becomes_a_supported_alkane_row() { + let doc = json!({ + "os": "alkane-os", "os_version": "0.1.2", "board": "zynq-7010", + "sdk_revision": "6a9080ac82c1", "hostname": "alkane-zynq", + "mac": "26:4e:52:8b:e2:48", "kernel": "6.18.48", + }); + let row = row_from_identity(ip(), &doc); + assert_eq!(row.ip, "10.0.0.5"); + assert_eq!(row.firmware, "Alkane"); + assert_eq!(row.fw_version, "0.1.2"); + assert_eq!(row.control_board, "XIL (C49)"); + assert_eq!(row.mac, "26:4e:52:8b:e2:48"); + assert!(is_alkane(&row)); + assert!(install_supported(&row)); + } + + #[test] + fn an_old_alkane_board_is_alkane_but_its_family_is_unknown() { + // Found via /api/summary only: uninstall applies, install cannot be + // confirmed as supported. + let row = row_from_identity(ip(), &json!({})); + assert!(is_alkane(&row)); + assert_eq!(board_family(&row), None); + assert!(!install_supported(&row)); + } + + #[test] + fn stock_antminers_are_supported_only_on_the_zynq_7010_board() { + let stock = |cpu: &str, code: &str| MinerRow { + brand: "Antminer".into(), + firmware: "Stock".into(), + cpu: cpu.into(), + board_code: code.into(), + ..Default::default() + }; + let s17 = stock("XIL", "C49"); + assert!(install_supported(&s17)); + assert!(!is_alkane(&s17)); + assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq + assert!(!install_supported(&stock("AML", "C76"))); + assert!(!install_supported(&stock("", ""))); + let whatsminer = MinerRow { + brand: "WhatsMiner".into(), + cpu: "XIL".into(), + board_code: "C49".into(), + ..Default::default() + }; + assert!(!install_supported(&whatsminer)); + } + + #[test] + fn a_stock_s17_without_a_reported_control_board_is_supported_by_model() { + // As seen live: stock S17, miner software down, control board blank. + let s17 = MinerRow { + brand: "Antminer".into(), + model: "S17".into(), + firmware: "Stock".into(), + ..Default::default() + }; + assert!(install_supported(&s17)); + let other = |model: &str| MinerRow { + brand: "Antminer".into(), + model: model.into(), + ..Default::default() + }; + assert!(install_supported(&other("S17 Pro"))); + assert!(install_supported(&other("T17"))); + assert!(!install_supported(&other("S19"))); + assert!(!install_supported(&other("S17+"))); + assert!(!install_supported(&other(""))); + // A reported control board overrides the model. + let s17_on_aml = MinerRow { + brand: "Antminer".into(), + model: "S17".into(), + cpu: "AML".into(), + board_code: "C76".into(), + ..Default::default() + }; + assert!(!install_supported(&s17_on_aml)); + } + + /// Live check against a real board: + /// `ALKANE_TEST_IP=10.255.1.111 cargo test -p alkane-gui live_detect -- --ignored --nocapture` + #[test] + #[ignore = "needs a board on the network (ALKANE_TEST_IP)"] + fn live_detect() { + let Ok(ip) = std::env::var("ALKANE_TEST_IP") else { + return; + }; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let row = rt.block_on(detect(ip.parse().unwrap())); + println!("{row:#?}"); + let row = row.expect("an Alkane board at ALKANE_TEST_IP"); + assert!(is_alkane(&row)); + } +} diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index bc92faec..02c53c5f 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -6,6 +6,7 @@ #![cfg_attr(windows, windows_subsystem = "windows")] mod access_probe; +mod alkane_detect; mod askpass; mod bug_report; mod credentials; diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 333c4f71..49157790 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -527,6 +527,10 @@ pub struct MinerRow { /// from whether any control capability is available: `None` = unknown, /// `Some(true)` = locked, `Some(false)` = unlocked/writable. pub write_locked: Option, + /// Set when the row is a board running Alkane OS (found by the toolkit's own + /// probe, `alkane_detect`, not asic-rs): the board family it reports + /// ("zynq-7010"), or an empty string for an older image that does not say. + pub alkane_board: Option, /// Structured error/event lines from the miner (severity + text), most /// severe first. Empty means none. The Error column shows a summary; the /// full list is the hover tooltip (added with the tooltip bridge support). diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 37af578e..352786a3 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -531,7 +531,10 @@ pub fn start_scan(lines: Vec, timeout_secs: u64) -> ScanHandle { .ok(); (ip, row) } - None => (ip, None), + // asic-rs does not recognise a board running Alkane + // OS (no cgminer socket or vendor web UI exposed); + // the toolkit's own probe finds it. + None => (ip, crate::alkane_detect::detect(ip).await), } } }) @@ -1229,6 +1232,8 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { .unwrap_or_default(), pic_present, write_locked, + // asic-rs identified this miner, so it is not running Alkane OS. + alkane_board: None, errors, faults, model, @@ -1917,13 +1922,25 @@ pub fn start_refresh(ips: Vec) -> RefreshHandle { ok += 1; RefreshMsg::Row(to_row(&*miner).await) } - Ok(None) => RefreshMsg::Failed { - ip: ip_s, - detail: "offline".to_string(), + Ok(None) => match crate::alkane_detect::detect(ip).await { + Some(row) => { + ok += 1; + RefreshMsg::Row(row) + } + None => RefreshMsg::Failed { + ip: ip_s, + detail: "offline".to_string(), + }, }, - Err(e) => RefreshMsg::Failed { - ip: ip_s, - detail: format!("{e}"), + Err(e) => match crate::alkane_detect::detect(ip).await { + Some(row) => { + ok += 1; + RefreshMsg::Row(row) + } + None => RefreshMsg::Failed { + ip: ip_s, + detail: format!("{e}"), + }, }, }, }; @@ -2615,3 +2632,41 @@ mod tests { std::env::remove_var(FAKE_SCAN_ENV); } } + +#[cfg(test)] +mod live_scan_tests { + /// Run the real fleet scan over a range and print, per row found, what the + /// alkane-os menu would offer: + /// `ALKANE_TEST_SCAN_RANGE=10.255.1.0/24 cargo test -p alkane-gui live_scan -- --ignored --nocapture` + #[test] + #[ignore = "needs a reachable miner network (ALKANE_TEST_SCAN_RANGE)"] + fn live_scan() { + let Ok(range) = std::env::var("ALKANE_TEST_SCAN_RANGE") else { + return; + }; + let handle = super::start_scan(vec![range], 10); + let mut rows = std::collections::BTreeMap::new(); + while let Ok(msg) = handle.rx.recv() { + match msg { + super::ScanMsg::Row(row) => { + rows.insert(row.ip.clone(), row); + } + super::ScanMsg::Done(_) | super::ScanMsg::Failed(_) => break, + _ => {} + } + } + for row in rows.values() { + println!( + "{:<15} brand={:<10} model={:<12} fw={:<8} {:<8} board={:<10} install={} uninstall={}", + row.ip, + row.brand, + row.model, + row.firmware, + row.fw_version, + row.control_board, + crate::alkane_detect::install_supported(row), + crate::alkane_detect::is_alkane(row), + ); + } + } +} diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index a46c9091..a38750dd 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -1,6 +1,7 @@ //! Primary view per docs/UI-SPEC.md: KPI header, scan-ranges editor, //! Excel-style filter panel, columns panel, sortable/drag-reorderable table. +use crate::alkane_detect; use crate::credentials; use crate::model::*; use crate::restore; @@ -103,6 +104,7 @@ const ID_POOLS_CANCEL: i32 = 789; // toolkit's own compiled-in network-only engine. Typed-FLASH confirmation. const ID_CTX_INSTALL_ALKANE: i32 = 770; const ID_CTX_UNINSTALL_ALKANE: i32 = 771; +const ID_CTX_UPDATE_ALKANE: i32 = 772; const ID_INSTALL_OK: i32 = 1006; const ID_INSTALL_CANCEL: i32 = 1007; const ID_INSTALL_RELEASE_CHOICE: i32 = 1008; @@ -1885,17 +1887,37 @@ impl App { // the vendor installers cover the current workflow. (ID_CTX_FLASH and the // flash dialog remain in the code, just not surfaced here.) let _ = ID_CTX_FLASH; - // Alkane OS install/uninstall via the toolkit's own self-contained, - // network-only engine (stock <-> alkane). Offered for any selection: the - // engine gates on board compatibility and a typed FLASH confirmation, so - // this is safe to surface without relying on asic-rs firmware detection - // (a board on genuine stock often does not identify cleanly). - menu.menu_append_separator(); - menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS (from stock)..."); - menu.menu_append( - ID_CTX_UNINSTALL_ALKANE, - "Uninstall alkane OS (restore to stock)...", - ); + // Alkane OS install / update / uninstall via the toolkit's own + // self-contained, network-only engine. Each is offered only when it + // applies to every selected board: + // - Install: a supported board (alkane-os has an image for its control + // board) that is not running Alkane OS yet; + // - Update: a supported board already running Alkane OS (updated in + // place); + // - Uninstall: a board running Alkane OS (restored to stock). + // A mixed stock/Alkane selection gets neither Install nor Update. The + // engine still gates on compatibility and a typed FLASH confirmation. + let supported = selected.iter().all(|r| alkane_detect::install_supported(r)); + let all_alkane = selected.iter().all(|r| alkane_detect::is_alkane(r)); + let none_alkane = selected.iter().all(|r| !alkane_detect::is_alkane(r)); + let install = supported && none_alkane; + let update = supported && all_alkane; + let uninstall = all_alkane; + if install || update || uninstall { + menu.menu_append_separator(); + } + if install { + menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS..."); + } + if update { + menu.menu_append(ID_CTX_UPDATE_ALKANE, "Update alkane OS..."); + } + if uninstall { + menu.menu_append( + ID_CTX_UNINSTALL_ALKANE, + "Uninstall alkane OS (restore to stock)...", + ); + } self.pending_popup = Some((t, menu)); } @@ -2596,11 +2618,12 @@ impl App { || self.stock_op.is_some() } - /// Build the "Install alkane OS (from stock)" dialog: a scanned list of + /// Build the "Install alkane OS" dialog (or, with `update`, the "Update + /// alkane OS" dialog for boards already running it): a scanned list of /// alkane-os releases to pick from, an optional board credential, the /// allow-unsigned (bench) toggle, and a typed FLASH confirmation. The install /// runs over the network via the toolkit's own compiled-in from-stock engine. - fn build_install_dialog(&mut self) -> Option { + fn build_install_dialog(&mut self, update: bool) -> Option { if self.hardware_busy() { wx_rs::set_status_text("busy -- try again once the current operation finishes"); return None; @@ -2630,16 +2653,28 @@ impl App { self.install_ips = ips.clone(); let frame = Widget::main_frame(); - let dlg = Widget::dialog(frame, "Install alkane OS (from stock)"); + let title = if update { + "Update alkane OS" + } else { + "Install alkane OS" + }; + let dlg = Widget::dialog(frame, title); let root = Widget::box_sizer(true); let n = ips.len(); root.add( Widget::static_text( dlg, - &format!( - "Install alkane OS onto {n} board(s) currently on stock:\n{}", - ips.join(", ") - ), + &if update { + format!( + "Update alkane OS on {n} board(s) already running it (updated in place; BOOT.bin is never written):\n{}", + ips.join(", ") + ) + } else { + format!( + "Install alkane OS onto {n} board(s) currently on stock:\n{}", + ips.join(", ") + ) + }, ), 0, sf::BORDER_ALL, @@ -2652,7 +2687,14 @@ impl App { 12, ); root.add( - Widget::static_text(dlg, "Release to install (newest first):"), + Widget::static_text( + dlg, + if update { + "Release to update to (newest first):" + } else { + "Release to install (newest first):" + }, + ), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, @@ -3127,7 +3169,8 @@ impl App { ID_CTX_ACCESS_PROBE => self.start_access_probe(), ID_CTX_VIEW_LOG => self.start_log_fetch(), ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(), - ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(), + ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false), + ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true), ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(), ID_CTX_POOLS => return self.build_pools_dialog(), ID_CTX_FLASH => { diff --git a/docs/install.md b/docs/install.md index e76917c8..3d001939 100644 --- a/docs/install.md +++ b/docs/install.md @@ -131,17 +131,30 @@ OS. ## GUI (right-click install / uninstall) The GUI binary is `alkane-toolkit`. Launch it, let the scan list the fleet, then -right-click one or more boards and choose: +right-click one or more boards. The scan finds boards running Alkane OS too +(Firmware column "Alkane"): they expose no cgminer socket or vendor web UI, so the +toolkit identifies them itself from the board's public read-only +`GET /api/identity` (alkane-os 0.1.2 and later; earlier images are found from +`/api/summary`). Each action below is offered only when it applies to every +selected board: -- "Install alkane OS (from stock)..." - scans the alkane-os releases on Gitea, - lets you pick one (newest first; pre-releases are marked), optionally takes a - board password and an "allow unsigned .afw (bench)" toggle, and - after you - type FLASH to confirm - downloads/verifies the `.afw` and installs it onto each - selected board over the network, via the same compiled-in from-stock engine the - CLI uses. -- "Uninstall alkane OS (restore to stock)..." - takes the board's alkane root - password and a typed FLASH confirmation, then restores each selected board to - genuine stock over the network. +- "Install alkane OS..." - for a supported board (one alkane-os has an image + for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane + OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first; + pre-releases are marked), optionally takes a board password and an "allow + unsigned .afw (bench)" toggle, and - after you type FLASH to confirm - + downloads/verifies the `.afw` and installs it onto each selected board over the + network, via the same compiled-in engine the CLI uses. +- "Update alkane OS..." - for a supported board already running Alkane OS: the + same release picker and confirmation; the board is updated in place (BOOT.bin + is never written). +- "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS: + takes the board's alkane root password, a genuine Bitmain firmware package and + a typed FLASH confirmation, then restores each selected board to genuine stock + over the network. + +A stock board the scan identifies but cannot place on a supported control board +(or a mixed stock/Alkane selection) gets neither Install nor Update. Progress and per-board results appear on the status bar; verify board state independently afterwards (the GUI does not claim liveness on its own).