//! 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)); } }