//! Real PIC-vs-noPIC detection for Antminer control boards, over SSH + i2c-tools. //! //! asic-rs and the miner's network API cannot report PIC presence (see the //! project wiki, 30-power-thermal-and-board-identity/hashboard-eeprom-pic.md); //! the authoritative tell lives on the control board's I2C bus. On a //! PIC/MCU-equipped board, I2C 0x48 is a hashboard MCU exposing an 8-byte //! register file that WRAPS every 8 bytes (e.g. `17 00 4b 50 7f 00 00 00 ...`); //! on a noPIC board, 0x48 is a plain LM75 temperature sensor with a 4-register //! layout that wraps every 4 bytes. We read 0x48 with `i2cdump` over SSH and //! discriminate by that period. //! //! This is a slow, credentialed, opt-in probe (an SSH handshake + shell command //! per miner), never part of the fast network scan. We shell out to `ssh` //! (via `sshpass` for password auth) rather than pull in an SSH crate, so the //! offline/vendored build is unaffected. use std::process::Command; use std::time::Duration; /// SSH login for the miner's control board (distinct from the web/API creds). #[derive(Debug, Clone)] pub struct SshCreds { pub user: String, /// Empty means key-based auth (BatchMode); otherwise `sshpass` is used. pub pass: String, } /// I2C buses to probe for the hashboard MCU/LM75 at 0x48, most-likely first, /// chosen from the control-board family. `probe_pic` tries them in order and /// stops at the first bus that classifies definitively, so extra fallbacks only /// cost an SSH round-trip when earlier buses are absent/indeterminate. /// /// Confirmed live (2026-09-19): a VNish CVITek S19k Pro exposes the hashboard /// MCU on i2c-3 (i2c-4 is the second, usually empty); its buses are i2c-3/i2c-4, /// NOT i2c-0/i2c-1 -- the earlier CVITek -> [1,0] guess never found the MCU, /// which is why PIC detection appeared not to work. AMLogic=i2c-1 and /// BeagleBone=i2c-0 are from the wiki; buses vary across firmware, so each family /// also lists the others as fallbacks. pub fn bus_candidates(control_board: &str) -> Vec { let cb = control_board.to_lowercase(); if cb.contains("cvi") { vec![3, 4, 1, 0] } else if cb.contains("amlogic") || cb.contains("aml") { vec![1, 3, 4, 0] } else if cb.contains("beaglebone") || cb.contains("bb") { vec![0, 1, 3, 4] } else { // Xilinx / unknown: try the common buses. vec![1, 0, 3, 4] } } /// Classify an `i2cdump -y 0x48 b` dump: `Some(true)` = PIC (8-byte MCU /// register file), `Some(false)` = noPIC (4-register LM75), `None` = couldn't /// tell (address unresponsive, no periodicity, or unparseable). Conservative: /// anything ambiguous is `None`, never a guess. pub fn classify_i2cdump(stdout: &str) -> Option { let bytes = parse_dump_offset0(stdout)?; // An LM75's 4 registers repeat every 4 bytes; check that first because a // period-4 sequence is trivially also period-8. let period4 = (0..12).all(|i| bytes[i] == bytes[i + 4]); if period4 { return Some(false); // LM75 -> noPIC } let period8 = (0..8).all(|i| bytes[i] == bytes[i + 8]); if period8 { return Some(true); // 8-byte MCU register file -> PIC } None } /// Parse the 16 bytes of the `00:` row of an `i2cdump ... b` output. Returns /// `None` if the row is missing or any cell is unreadable ("XX"). fn parse_dump_offset0(stdout: &str) -> Option<[u8; 16]> { let line = stdout.lines().find_map(|l| { let l = l.trim(); l.strip_prefix("00:").map(str::trim_start) })?; // The row is "<16 hex/XX cells> "; take the first 16 cells. let mut out = [0u8; 16]; let mut n = 0; for tok in line.split_whitespace() { if n == 16 { break; } if tok.len() != 2 { break; // reached the ascii gutter } match u8::from_str_radix(tok, 16) { Ok(b) => { out[n] = b; n += 1; } Err(_) => return None, // "XX" = no response -> indeterminate } } (n == 16).then_some(out) } /// Build the ssh argv for one `i2cdump` on `bus`. Uses `sshpass -p ` when /// a password is set, else relies on key auth (BatchMode). fn ssh_command(ip: &str, bus: u8, creds: &SshCreds) -> Command { let remote = format!("i2cdump -y {bus} 0x48 b"); let target = format!("{}@{ip}", creds.user); let ssh_opts = [ "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "ConnectTimeout=6", "-o", "NumberOfPasswordPrompts=1", ]; if creds.pass.is_empty() { let mut c = Command::new("ssh"); c.arg("-o").arg("BatchMode=yes"); c.args(ssh_opts).arg(&target).arg(&remote); c } else { // sshpass reads the password from the env var named after -e's default, // but we use -p for simplicity; the password never reaches the argv of // a child that logs it (sshpass scrubs its own argv). let mut c = Command::new("sshpass"); c.arg("-p").arg(&creds.pass).arg("ssh"); c.args(ssh_opts).arg(&target).arg(&remote); c } } /// Probe one miner's PIC state over SSH. Returns `Ok(Some(true/false))` on a /// confident PIC/noPIC read, `Ok(None)` if reachable but indeterminate, or /// `Err` on an SSH/connection/auth failure. pub fn probe_pic(ip: &str, control_board: &str, creds: &SshCreds) -> Result, String> { let mut last_err = String::from("no i2c bus responded"); for bus in bus_candidates(control_board) { match run_probe(ip, bus, creds) { Ok(Some(v)) => return Ok(Some(v)), Ok(None) => last_err = format!("i2c-0x48 on bus {bus} was indeterminate"), Err(e) => return Err(e), // an auth/connection error won't improve on another bus } } // Reachable but couldn't classify on any candidate bus. let _ = last_err; Ok(None) } fn run_probe(ip: &str, bus: u8, creds: &SshCreds) -> Result, String> { let out = wait_with_timeout(ssh_command(ip, bus, creds), Duration::from_secs(12))?; if !out.status.success() { let err = String::from_utf8_lossy(&out.stderr); // A failed i2cdump on this bus (e.g. bus doesn't exist) is not fatal -- // let the caller try the next bus. But an SSH/auth failure is fatal. let e = err.trim().to_string(); if e.to_lowercase().contains("permission denied") || e.to_lowercase().contains("connection") || e.to_lowercase().contains("timed out") || e.to_lowercase().contains("no route") || e.to_lowercase().contains("host key") { return Err(if e.is_empty() { "ssh failed".into() } else { e }); } return Ok(None); } Ok(classify_i2cdump(&String::from_utf8_lossy(&out.stdout))) } /// Run a command with a wall-clock timeout (SSH can hang on a dead host). fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result { use std::io::Read; cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); let mut child = cmd.spawn().map_err(|e| format!("spawn ssh: {e}"))?; let start = std::time::Instant::now(); loop { match child.try_wait().map_err(|e| e.to_string())? { Some(status) => { let mut stdout = Vec::new(); let mut stderr = Vec::new(); if let Some(mut o) = child.stdout.take() { let _ = o.read_to_end(&mut stdout); } if let Some(mut e) = child.stderr.take() { let _ = e.read_to_end(&mut stderr); } return Ok(std::process::Output { status, stdout, stderr }); } None => { if start.elapsed() >= timeout { let _ = child.kill(); return Err("ssh timed out".into()); } std::thread::sleep(Duration::from_millis(100)); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn classify_pic_from_wiki_dump() { // The wiki's PIC/MCU board dump: 8-byte register file that wraps. let dump = "\ 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef 00: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................ 10: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................"; assert_eq!(classify_i2cdump(dump), Some(true), "8-byte wrap -> PIC"); } #[test] fn classify_nopic_from_lm75() { // An LM75 has 4 registers (temp/config/Thyst/Tos) that wrap every 4. let dump = "\ 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef 00: 19 00 4b 50 19 00 4b 50 19 00 4b 50 19 00 4b 50 ................"; assert_eq!(classify_i2cdump(dump), Some(false), "4-register LM75 -> noPIC"); } #[test] fn classify_indeterminate() { // No response (XX) or no periodicity -> None (never a guess). let xx = "00: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX"; assert_eq!(classify_i2cdump(xx), None); let noisy = "00: 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10"; assert_eq!(classify_i2cdump(noisy), None); assert_eq!(classify_i2cdump("no offset row here"), None); } #[test] fn bus_from_control_board() { // Most-likely bus first, then fallbacks. CVITek's i2c-3 first is the live // fix; AMLogic i2c-1 and BeagleBone i2c-0 keep their wiki-confirmed lead. assert_eq!(bus_candidates("CVI (C88)"), vec![3, 4, 1, 0]); assert_eq!(bus_candidates("CVITek"), vec![3, 4, 1, 0]); assert_eq!(bus_candidates("AMLogic")[0], 1); assert_eq!(bus_candidates("BeagleBone Black")[0], 0); assert_eq!(bus_candidates("Xilinx")[0], 1); assert_eq!(bus_candidates("")[0], 1); } }