Clears the rest of the second review round's confirmed findings: - HIGH the Boards numeric filter compared the composite sort score (online*100+ total) instead of the board count, so a filter like "Boards <= 3" matched nothing on healthy 3-board miners. num_value now returns the detected count; regression-tested with per-board health present (the path the old test missed). - HIGH the WhatsMiner access probe ignored the operator's saved scan password (tried only admin/super), mis-reporting writable miners as locked. It now tries the caller's password first. - HIGH firmware flash and config actions were not blocked during a restore-to- stock; start_action and both flash guards now refuse while a restore runs. - MED log tail() could panic slicing at a non-UTF8 char boundary -> nudge to a boundary first (regression-tested). - MED board_index_from_text grabbed an unrelated number far past the keyword (e.g. a temperature) -> only accept a number immediately after the keyword. - MED a restore worker-thread spawn failure wedged the restore subsystem forever -> emit Done on spawn failure and treat a disconnected channel as done. - MED LuxOS restore reported failure when the miner rebooted mid-reply -> an empty reply or dropped connection after a successful logon is the expected reboot. - MED two tests raced on the process-global $HOME -> a shared serialization lock. - LOW CSV export now neutralizes spreadsheet formula-injection prefixes on miner-supplied fields. - Made miner_probe's global-only credential resolution explicit (it can't share the GUI's per-firmware configured_factory across the bin boundary). 99 tests (+3 regression tests) + clippy-clean + selftest green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
196 lines
7.7 KiB
Rust
196 lines
7.7 KiB
Rust
//! CSV export of the full scan data (round 15 #14).
|
|
//!
|
|
//! Unlike the on-screen table (which packs several values into one cell, e.g.
|
|
//! "95T/96T" or a row of health icons), the export is one value per cell and
|
|
//! covers every scanned data point, so it is complete and machine-readable.
|
|
//! Variable-length fields (per-board temps, per-fan RPMs, per-board health, the
|
|
//! pool list) are expanded into indexed columns out to the widest miner in the
|
|
//! set, so every row has the same columns.
|
|
|
|
use crate::model::{BoardHealth, MinerRow};
|
|
|
|
/// Escape one CSV field: neutralise spreadsheet formula injection, then quote it
|
|
/// when it contains a comma, quote, CR or LF (doubling any embedded quotes).
|
|
///
|
|
/// Miner-supplied fields (hostname, worker, serial, ...) can start with a formula
|
|
/// trigger; prefixing a single quote makes Excel/Sheets treat the cell as text so
|
|
/// opening the export can't execute an injected formula (round 18 #12).
|
|
fn esc(s: &str) -> String {
|
|
let mut val = s.to_string();
|
|
if val.starts_with(['=', '+', '-', '@', '\t', '\r']) {
|
|
val.insert(0, '\'');
|
|
}
|
|
if val.contains([',', '"', '\n', '\r']) {
|
|
format!("\"{}\"", val.replace('"', "\"\""))
|
|
} else {
|
|
val
|
|
}
|
|
}
|
|
|
|
fn num(v: f64) -> String {
|
|
if v == 0.0 {
|
|
String::new()
|
|
} else if v.fract() == 0.0 {
|
|
format!("{v:.0}")
|
|
} else {
|
|
format!("{v:.3}")
|
|
}
|
|
}
|
|
|
|
fn opt_bool(v: Option<bool>, yes: &str, no: &str) -> String {
|
|
match v {
|
|
Some(true) => yes.to_string(),
|
|
Some(false) => no.to_string(),
|
|
None => String::new(),
|
|
}
|
|
}
|
|
|
|
fn board_health_str(h: &BoardHealth) -> &'static str {
|
|
match h {
|
|
BoardHealth::Ok => "ok",
|
|
BoardHealth::Fault => "fault",
|
|
BoardHealth::Missing => "missing",
|
|
}
|
|
}
|
|
|
|
/// The fixed scalar columns, in order: (header, extractor).
|
|
type Col = (&'static str, fn(&MinerRow) -> String);
|
|
|
|
fn scalar_columns() -> Vec<Col> {
|
|
vec![
|
|
("ip", |r| r.ip.clone()),
|
|
("model", |r| r.model.clone()),
|
|
("brand", |r| r.brand.clone()),
|
|
("submodel", |r| r.submodel.clone()),
|
|
("mac", |r| r.mac.clone()),
|
|
("hostname", |r| r.hostname.clone()),
|
|
("serial", |r| r.serial.clone()),
|
|
("firmware", |r| r.firmware.clone()),
|
|
("fw_version", |r| r.fw_version.clone()),
|
|
("api_version", |r| r.api_version.clone()),
|
|
("control_board", |r| r.control_board.clone()),
|
|
("cpu", |r| r.cpu.clone()),
|
|
("board_code", |r| r.board_code.clone()),
|
|
("algorithm", |r| r.algorithm.clone()),
|
|
("status", |r| r.status().to_string()),
|
|
("operating_state", |r| r.operating_state.clone()),
|
|
("is_mining", |r| r.is_mining.to_string()),
|
|
("slow", |r| r.slow.to_string()),
|
|
("paused", |r| r.paused.to_string()),
|
|
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
|
|
("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")),
|
|
("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")),
|
|
("hashrate_ths", |r| num(r.hashrate_ths)),
|
|
("expected_ths", |r| num(r.expected_ths)),
|
|
("efficiency_j_th", |r| num(r.efficiency)),
|
|
("power_w", |r| num(r.power_w)),
|
|
("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()),
|
|
("chip_temp_c", |r| num(r.chip_temp_c)),
|
|
("fluid_temp_c", |r| num(r.fluid_temp_c)),
|
|
("env_temp_c", |r| num(r.env_temp_c)),
|
|
("outlet_temp_c", |r| num(r.outlet_temp_c)),
|
|
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
|
|
("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()),
|
|
("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()),
|
|
("total_chips", |r| r.total_chips.map(|v| v.to_string()).unwrap_or_default()),
|
|
("expected_chips", |r| r.expected_chips.map(|v| v.to_string()).unwrap_or_default()),
|
|
("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()),
|
|
("expected_hashboards", |r| r.expected_hashboards.map(|v| v.to_string()).unwrap_or_default()),
|
|
("uptime_secs", |r| if r.uptime_secs > 0 { r.uptime_secs.to_string() } else { String::new() }),
|
|
("best_share", |r| r.best_share.map(num).unwrap_or_default()),
|
|
("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()),
|
|
("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()),
|
|
("pool_url", |r| r.pool_url.clone()),
|
|
("errors", |r| r.errors.join("; ")),
|
|
]
|
|
}
|
|
|
|
/// Build the full CSV for `rows`. Empty rows still emit a header line.
|
|
pub fn rows_to_csv(rows: &[MinerRow]) -> String {
|
|
let cols = scalar_columns();
|
|
// Widest variable-length fields across the set.
|
|
let max_board_temps = rows.iter().map(|r| r.board_temps.len()).max().unwrap_or(0);
|
|
let max_fans = rows.iter().map(|r| r.fan_rpms.len()).max().unwrap_or(0);
|
|
let max_boards = rows.iter().map(|r| r.board_status.len()).max().unwrap_or(0);
|
|
let max_pools = rows.iter().map(|r| r.pools.len()).max().unwrap_or(0);
|
|
|
|
// Header.
|
|
let mut headers: Vec<String> = cols.iter().map(|(h, _)| (*h).to_string()).collect();
|
|
for i in 1..=max_board_temps {
|
|
headers.push(format!("board_temp_{i}_c"));
|
|
}
|
|
for i in 1..=max_fans {
|
|
headers.push(format!("fan_{i}_rpm"));
|
|
}
|
|
for i in 1..=max_boards {
|
|
headers.push(format!("board_{i}_status"));
|
|
}
|
|
for i in 1..=max_pools {
|
|
headers.push(format!("pool_{i}_url"));
|
|
headers.push(format!("pool_{i}_worker"));
|
|
}
|
|
|
|
let mut out = String::new();
|
|
out.push_str(&headers.iter().map(|h| esc(h)).collect::<Vec<_>>().join(","));
|
|
out.push('\n');
|
|
|
|
for r in rows {
|
|
let mut vals: Vec<String> = cols.iter().map(|(_, f)| f(r)).collect();
|
|
for i in 0..max_board_temps {
|
|
vals.push(r.board_temps.get(i).map(|&t| num(t)).unwrap_or_default());
|
|
}
|
|
for i in 0..max_fans {
|
|
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
|
|
}
|
|
for i in 0..max_boards {
|
|
vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string());
|
|
}
|
|
for i in 0..max_pools {
|
|
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
|
|
vals.push(u);
|
|
vals.push(w);
|
|
}
|
|
out.push_str(&vals.iter().map(|v| esc(v)).collect::<Vec<_>>().join(","));
|
|
out.push('\n');
|
|
}
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn csv_has_header_and_one_row_per_miner() {
|
|
let rows = vec![
|
|
MinerRow {
|
|
ip: "10.0.0.1".into(),
|
|
model: "S19".into(),
|
|
hashrate_ths: 95.0,
|
|
expected_ths: 96.0,
|
|
board_temps: vec![77.0, 64.0, 74.0],
|
|
fan_rpms: vec![6000.0, 6100.0],
|
|
..Default::default()
|
|
},
|
|
MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() },
|
|
];
|
|
let csv = rows_to_csv(&rows);
|
|
let lines: Vec<&str> = csv.lines().collect();
|
|
assert_eq!(lines.len(), 3, "header + 2 rows");
|
|
assert!(lines[0].starts_with("ip,model,brand,"));
|
|
// Expanded columns out to the widest miner (3 board temps, 2 fans).
|
|
assert!(lines[0].contains("board_temp_3_c"));
|
|
assert!(lines[0].contains("fan_2_rpm"));
|
|
assert!(lines[1].starts_with("10.0.0.1,S19,"));
|
|
// One value per cell: hashrate and expected are separate columns.
|
|
assert!(lines[1].contains(",95,96,") || lines[1].contains("95,96"));
|
|
}
|
|
|
|
#[test]
|
|
fn csv_escapes_commas_and_quotes() {
|
|
assert_eq!(esc("a,b"), "\"a,b\"");
|
|
assert_eq!(esc("he said \"hi\""), "\"he said \"\"hi\"\"\"");
|
|
assert_eq!(esc("plain"), "plain");
|
|
}
|
|
}
|