Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ad8b56c1f | ||
|
|
28f8f9ce80 | ||
|
|
d35cedd056 | ||
|
|
a825299ebc | ||
|
|
a17f108050 | ||
|
|
3faa35ea70 | ||
|
|
16490dd3b9 | ||
|
|
e6ae9d9d50 | ||
|
|
fc1ed3e4e5 | ||
|
|
d7a914258e | ||
|
|
2108f47eea |
@@ -12,7 +12,9 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
runs-on: alkane-pages
|
runs-on: alkane-verify
|
||||||
|
container:
|
||||||
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
runs-on: alkane-fast
|
runs-on: alkane-verify
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
|
||||||
permissions:
|
permissions:
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ jobs:
|
|||||||
- name: Check runner image pins
|
- name: Check runner image pins
|
||||||
run: python3 ci/check-runner-image.py
|
run: python3 ci/check-runner-image.py
|
||||||
|
|
||||||
|
- name: Check first-party Rust formatting
|
||||||
|
run: |
|
||||||
|
rustup component add rustfmt >/dev/null
|
||||||
|
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -- --check
|
||||||
|
|
||||||
|
|
||||||
- name: Compute version
|
- name: Compute version
|
||||||
id: ver
|
id: ver
|
||||||
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
|
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
|
||||||
|
|||||||
@@ -43,11 +43,19 @@ jobs:
|
|||||||
else
|
else
|
||||||
status=$?
|
status=$?
|
||||||
[ "$status" -eq 1 ]
|
[ "$status" -eq 1 ]
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Check CI change surface
|
- name: Check CI change surface
|
||||||
if: steps.surface.outputs.surface != 'documentation'
|
if: steps.surface.outputs.surface != 'documentation'
|
||||||
run: python3 ci/test-pr-surface.py
|
run: python3 ci/test-pr-surface.py
|
||||||
|
|
||||||
|
- name: Check first-party Rust formatting
|
||||||
|
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
|
||||||
|
run: |
|
||||||
|
rustup component add rustfmt >/dev/null
|
||||||
|
cargo fmt -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli -p alkane-access -- --check
|
||||||
|
|
||||||
|
|
||||||
- name: Check workflow-only change
|
- name: Check workflow-only change
|
||||||
if: steps.surface.outputs.surface == 'workflow'
|
if: steps.surface.outputs.surface == 'workflow'
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -10,9 +10,12 @@
|
|||||||

|

|
||||||

|

|
||||||
|
|
||||||
|
The code quality grade reports GUI Clippy and first-party Rust formatting checks
|
||||||
|
from the last successful main build. Test coverage has a separate badge.
|
||||||
|
|
||||||
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
||||||
a patched [wx-rs bridge](thirdparty/wx-rs). Firmware installation is under
|
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
|
||||||
development.
|
while that path is reworked.
|
||||||
|
|
||||||
## Run locally
|
## Run locally
|
||||||
|
|
||||||
@@ -31,10 +34,12 @@ use the matching `scripts/build-gui-*.sh` script.
|
|||||||
- Discover miners by CIDR or IP range with vendored [asic-rs](vendor/asic-rs).
|
- Discover miners by CIDR or IP range with vendored [asic-rs](vendor/asic-rs).
|
||||||
- Show model, firmware, health, hashrate, temperatures, fans, PSU, and workers.
|
- Show model, firmware, health, hashrate, temperatures, fans, PSU, and workers.
|
||||||
- Filter and sort the desktop table; inspect probes with `miner_probe`.
|
- Filter and sort the desktop table; inspect probes with `miner_probe`.
|
||||||
|
- Use controls supported by the selected firmware and restore supported
|
||||||
|
aftermarket firmware to stock.
|
||||||
|
|
||||||
Discovery is read-only. The installer and operator actions remain in the
|
Discovery is read-only. Control and restore actions change miners. Check the
|
||||||
[implementation plan](docs/IMPLEMENTATION-PLAN.md) and
|
selected devices before applying them. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md)
|
||||||
[firmware matrix](docs/aftermarket-parity-roadmap.md).
|
and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ def main() -> int:
|
|||||||
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
|
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
|
||||||
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
|
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
|
||||||
for name, job in workflow.get("jobs", {}).items():
|
for name, job in workflow.get("jobs", {}).items():
|
||||||
|
if (job.get("runs-on") in {"alkane-fast", "alkane-pages"}
|
||||||
|
and "secrets." in str(job)):
|
||||||
|
print(f"{path.name}: {name} exposes a secret to the fast runner", file=sys.stderr)
|
||||||
|
return 1
|
||||||
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
|
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
|
||||||
continue
|
continue
|
||||||
if job.get("container", {}).get("image") != IMAGE:
|
if job.get("container", {}).get("image") != IMAGE:
|
||||||
@@ -32,8 +36,8 @@ def main() -> int:
|
|||||||
Loader=yaml.BaseLoader,
|
Loader=yaml.BaseLoader,
|
||||||
)
|
)
|
||||||
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
|
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
|
||||||
or pages["jobs"]["publish"].get("runs-on") != "alkane-pages"):
|
or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"):
|
||||||
print("Benchmark Pages must follow main CI on the Pages runner", file=sys.stderr)
|
print("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
release = yaml.load(
|
release = yaml.load(
|
||||||
(ROOT / ".gitea/workflows/release.yml").read_text(),
|
(ROOT / ".gitea/workflows/release.yml").read_text(),
|
||||||
|
|||||||
+9
-6
@@ -40,7 +40,8 @@ def text_width(s: str) -> float:
|
|||||||
return len(s) * CHAR_W + 2 * PAD
|
return len(s) * CHAR_W + 2 * PAD
|
||||||
|
|
||||||
|
|
||||||
def badge_svg(label: str, message: str, color: str) -> str:
|
def badge_svg(label: str, message: str, color: str,
|
||||||
|
description: str | None = None) -> str:
|
||||||
color = COLORS.get(color, color)
|
color = COLORS.get(color, color)
|
||||||
lw = round(text_width(label), 1)
|
lw = round(text_width(label), 1)
|
||||||
mw = round(text_width(message), 1)
|
mw = round(text_width(message), 1)
|
||||||
@@ -48,8 +49,9 @@ def badge_svg(label: str, message: str, color: str) -> str:
|
|||||||
lx = round(lw / 2, 1)
|
lx = round(lw / 2, 1)
|
||||||
mx = round(lw + mw / 2, 1)
|
mx = round(lw + mw / 2, 1)
|
||||||
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
|
# Text is drawn twice (a dark shadow then the light glyphs) for the shields look.
|
||||||
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{label}: {message}">
|
description = description or f"{label}: {message}"
|
||||||
<title>{label}: {message}</title>
|
return f'''<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{description}">
|
||||||
|
<title>{description}</title>
|
||||||
<linearGradient id="s" x2="0" y2="100%">
|
<linearGradient id="s" x2="0" y2="100%">
|
||||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||||
<stop offset="1" stop-opacity=".1"/>
|
<stop offset="1" stop-opacity=".1"/>
|
||||||
@@ -174,10 +176,10 @@ def main() -> int:
|
|||||||
|
|
||||||
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
|
os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
|
||||||
|
|
||||||
def write(name, label, message, color):
|
def write(name, label, message, color, description=None):
|
||||||
path = os.path.join(args.root, args.out, name + ".svg")
|
path = os.path.join(args.root, args.out, name + ".svg")
|
||||||
with open(path, "w", encoding="utf-8") as fh:
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
fh.write(badge_svg(label, message, color))
|
fh.write(badge_svg(label, message, color, description))
|
||||||
print(f"wrote {path}: {label}={message}")
|
print(f"wrote {path}: {label}={message}")
|
||||||
|
|
||||||
loc = count_loc(args.root)
|
loc = count_loc(args.root)
|
||||||
@@ -190,7 +192,8 @@ def main() -> int:
|
|||||||
grade = quality_grade(args.clippy)
|
grade = quality_grade(args.clippy)
|
||||||
write("quality", "code quality", grade,
|
write("quality", "code quality", grade,
|
||||||
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||||
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
|
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
|
||||||
|
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
|
||||||
if args.tests is not None:
|
if args.tests is not None:
|
||||||
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
||||||
if args.coverage is not None:
|
if args.coverage is not None:
|
||||||
|
|||||||
@@ -50,6 +50,17 @@ class BenchBadgeTests(unittest.TestCase):
|
|||||||
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
|
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
|
||||||
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
|
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
|
||||||
|
|
||||||
|
def test_quality_grade_is_only_the_clippy_result(self):
|
||||||
|
self.assertEqual(gen_badges.quality_grade("clean"), "A")
|
||||||
|
self.assertEqual(gen_badges.quality_grade("failed"), "F")
|
||||||
|
self.assertEqual(gen_badges.quality_grade(None), "pending")
|
||||||
|
svg = gen_badges.badge_svg(
|
||||||
|
"code quality", "A", "brightgreen",
|
||||||
|
"code quality: A (GUI Clippy and first-party rustfmt)",
|
||||||
|
)
|
||||||
|
self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg)
|
||||||
|
self.assertIn('>A</text>', svg)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -31,7 +31,8 @@ def check_workflow_contract() -> None:
|
|||||||
"""Keep the short workflow check from silently dropping release gates."""
|
"""Keep the short workflow check from silently dropping release gates."""
|
||||||
required = {
|
required = {
|
||||||
"release.yml": ("main", "release", (
|
"release.yml": ("main", "release", (
|
||||||
"Check runner image pins", "Clippy (our crate, warnings are errors)",
|
"Check runner image pins", "Check first-party Rust formatting",
|
||||||
|
"Clippy (our crate, warnings are errors)",
|
||||||
"Build release", "Unit tests", "Microbenchmarks",
|
"Build release", "Unit tests", "Microbenchmarks",
|
||||||
"Headless UI self-test", "Coverage", "Microbenchmark coverage",
|
"Headless UI self-test", "Coverage", "Microbenchmark coverage",
|
||||||
"Generate measured badges", "Publish measured badges",
|
"Generate measured badges", "Publish measured badges",
|
||||||
@@ -44,7 +45,8 @@ def check_workflow_contract() -> None:
|
|||||||
)),
|
)),
|
||||||
"verify.yml": ("main", "verify", (
|
"verify.yml": ("main", "verify", (
|
||||||
"Check runner image pins", "Detect changed surface",
|
"Check runner image pins", "Detect changed surface",
|
||||||
"Check CI change surface", "Check workflow-only change",
|
"Check CI change surface", "Check first-party Rust formatting",
|
||||||
|
"Check workflow-only change",
|
||||||
"Clippy (our crate, warnings are errors)", "Build", "Unit tests",
|
"Clippy (our crate, warnings are errors)", "Build", "Unit tests",
|
||||||
"Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build",
|
"Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build",
|
||||||
)),
|
)),
|
||||||
@@ -73,6 +75,9 @@ def check_workflow_contract() -> None:
|
|||||||
assert condition == "steps.surface.outputs.surface == 'full'", path
|
assert condition == "steps.surface.outputs.surface == 'full'", path
|
||||||
elif filename == "verify.yml" and gate == "Check CI change surface":
|
elif filename == "verify.yml" and gate == "Check CI change surface":
|
||||||
assert condition == "steps.surface.outputs.surface != 'documentation'", path
|
assert condition == "steps.surface.outputs.surface != 'documentation'", path
|
||||||
|
elif filename == "verify.yml" and gate == "Check first-party Rust formatting":
|
||||||
|
assert condition == ("steps.surface.outputs.surface == 'headless' || "
|
||||||
|
"steps.surface.outputs.surface == 'full'"), path
|
||||||
elif filename == "verify.yml" and gate == "Check workflow-only change":
|
elif filename == "verify.yml" and gate == "Check workflow-only change":
|
||||||
assert condition == "steps.surface.outputs.surface == 'workflow'", path
|
assert condition == "steps.surface.outputs.surface == 'workflow'", path
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -29,10 +29,10 @@ use std::net::{SocketAddr, TcpStream};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use aes::cipher::{block_padding::ZeroPadding, BlockEncryptMut, KeyInit};
|
||||||
use aes::Aes256;
|
use aes::Aes256;
|
||||||
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
|
|
||||||
use base64::Engine;
|
|
||||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||||
|
use base64::Engine;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
||||||
@@ -42,9 +42,9 @@ type Aes256EcbEnc = ecb::Encryptor<Aes256>;
|
|||||||
/// authenticated/unauthorized answer is `None`.
|
/// authenticated/unauthorized answer is `None`.
|
||||||
pub fn classify_http_code(code: &str) -> Option<bool> {
|
pub fn classify_http_code(code: &str) -> Option<bool> {
|
||||||
match code.trim() {
|
match code.trim() {
|
||||||
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
||||||
"401" | "403" => Some(true), // rejected -> locked/view-only
|
"401" | "403" => Some(true), // rejected -> locked/view-only
|
||||||
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +95,10 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Opti
|
|||||||
]);
|
]);
|
||||||
// The user:pass goes through a curl config on stdin, never argv, so it can't
|
// The user:pass goes through a curl config on stdin, never argv, so it can't
|
||||||
// be read from the process list (round 18 #12).
|
// be read from the process list (round 18 #12).
|
||||||
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
|
let config = format!(
|
||||||
|
"user = \"{}\"\n",
|
||||||
|
curl_config_quote(&format!("{user}:{pass}"))
|
||||||
|
);
|
||||||
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
|
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
|
||||||
// curl prints the status code to stdout regardless of exit status (000 on a
|
// curl prints the status code to stdout regardless of exit status (000 on a
|
||||||
// connection failure), so classify the code rather than the exit status.
|
// connection failure), so classify the code rather than the exit status.
|
||||||
@@ -113,7 +116,8 @@ fn wait_with_timeout(
|
|||||||
stdin_data: Option<&[u8]>,
|
stdin_data: Option<&[u8]>,
|
||||||
) -> Result<std::process::Output, String> {
|
) -> Result<std::process::Output, String> {
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
|
cmd.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::piped());
|
||||||
if stdin_data.is_some() {
|
if stdin_data.is_some() {
|
||||||
cmd.stdin(std::process::Stdio::piped());
|
cmd.stdin(std::process::Stdio::piped());
|
||||||
}
|
}
|
||||||
@@ -135,7 +139,11 @@ fn wait_with_timeout(
|
|||||||
if let Some(mut e) = child.stderr.take() {
|
if let Some(mut e) = child.stderr.take() {
|
||||||
let _ = e.read_to_end(&mut stderr);
|
let _ = e.read_to_end(&mut stderr);
|
||||||
}
|
}
|
||||||
return Ok(std::process::Output { status, stdout, stderr });
|
return Ok(std::process::Output {
|
||||||
|
status,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
if start.elapsed() >= timeout {
|
if start.elapsed() >= timeout {
|
||||||
@@ -158,7 +166,8 @@ fn curl_config_quote(s: &str) -> String {
|
|||||||
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
|
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
|
||||||
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
|
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
|
||||||
fn whatsminer_password_candidates() -> Vec<String> {
|
fn whatsminer_password_candidates() -> Vec<String> {
|
||||||
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") {
|
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock")
|
||||||
|
{
|
||||||
if !pass.is_empty() {
|
if !pass.is_empty() {
|
||||||
return vec![pass.clone()];
|
return vec![pass.clone()];
|
||||||
}
|
}
|
||||||
@@ -170,9 +179,17 @@ fn whatsminer_password_candidates() -> Vec<String> {
|
|||||||
/// get_error_code command and format them one per line for the log viewer
|
/// get_error_code command and format them one per line for the log viewer
|
||||||
/// (round 12 #12). Returns None if the miner does not answer.
|
/// (round 12 #12). Returns None if the miner does not answer.
|
||||||
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
|
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
|
||||||
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
|
let resp = wm_rpc(
|
||||||
|
ip,
|
||||||
|
"{\"command\":\"get_error_code\"}",
|
||||||
|
Duration::from_secs(6),
|
||||||
|
)
|
||||||
|
.ok()?;
|
||||||
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
|
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
|
||||||
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
|
let codes = v
|
||||||
|
.get("Msg")
|
||||||
|
.and_then(|m| m.get("error_code"))
|
||||||
|
.and_then(|c| c.as_array());
|
||||||
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
|
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
|
||||||
match codes {
|
match codes {
|
||||||
Some(arr) if !arr.is_empty() => {
|
Some(arr) if !arr.is_empty() => {
|
||||||
@@ -198,7 +215,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
|
|||||||
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
|
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
|
||||||
stream.set_read_timeout(Some(timeout)).ok();
|
stream.set_read_timeout(Some(timeout)).ok();
|
||||||
stream.set_write_timeout(Some(timeout)).ok();
|
stream.set_write_timeout(Some(timeout)).ok();
|
||||||
stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
|
stream
|
||||||
|
.write_all(payload.as_bytes())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
let mut chunk = [0u8; 4096];
|
let mut chunk = [0u8; 4096];
|
||||||
loop {
|
loop {
|
||||||
@@ -213,7 +232,9 @@ fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String>
|
|||||||
Err(_) => break,
|
Err(_) => break,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
Ok(String::from_utf8_lossy(&buf)
|
||||||
|
.trim_matches('\u{0}')
|
||||||
|
.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
|
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
|
||||||
@@ -278,15 +299,20 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
|
|||||||
// 2. Derive the md5crypt password hash + write-token from the password.
|
// 2. Derive the md5crypt password hash + write-token from the password.
|
||||||
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
|
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
|
||||||
let full = String::from_utf8_lossy(&crypted);
|
let full = String::from_utf8_lossy(&crypted);
|
||||||
let Some(pwd_md5) = full.split('$').nth(3) else { continue };
|
let Some(pwd_md5) = full.split('$').nth(3) else {
|
||||||
let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
|
continue;
|
||||||
|
};
|
||||||
|
let sign_crypted =
|
||||||
|
md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
|
||||||
let sign_full = String::from_utf8_lossy(&sign_crypted);
|
let sign_full = String::from_utf8_lossy(&sign_crypted);
|
||||||
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
|
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
|
||||||
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
|
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
|
||||||
// password) is right the miner replies encrypted; if wrong it returns
|
// password) is right the miner replies encrypted; if wrong it returns
|
||||||
// a plaintext "enc json load err".
|
// a plaintext "enc json load err".
|
||||||
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
|
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
|
||||||
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue };
|
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
|
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
|
||||||
let resp = match wm_rpc(ip, &payload, timeout) {
|
let resp = match wm_rpc(ip, &payload, timeout) {
|
||||||
Ok(s) => s,
|
Ok(s) => s,
|
||||||
@@ -302,7 +328,11 @@ fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
|
|||||||
}
|
}
|
||||||
// Only report "locked" when we cleanly reached the miner and every candidate
|
// Only report "locked" when we cleanly reached the miner and every candidate
|
||||||
// was rejected with no transient errors; otherwise the result is indeterminate.
|
// was rejected with no transient errors; otherwise the result is indeterminate.
|
||||||
if reachable && !errored { Some(true) } else { None }
|
if reachable && !errored {
|
||||||
|
Some(true)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -311,14 +341,30 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn classify_codes() {
|
fn classify_codes() {
|
||||||
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
|
assert_eq!(
|
||||||
|
classify_http_code("200"),
|
||||||
|
Some(false),
|
||||||
|
"authenticated -> unlocked"
|
||||||
|
);
|
||||||
assert_eq!(classify_http_code("204"), Some(false));
|
assert_eq!(classify_http_code("204"), Some(false));
|
||||||
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
|
assert_eq!(
|
||||||
|
classify_http_code("401"),
|
||||||
|
Some(true),
|
||||||
|
"unauthorized -> locked"
|
||||||
|
);
|
||||||
assert_eq!(classify_http_code("403"), Some(true));
|
assert_eq!(classify_http_code("403"), Some(true));
|
||||||
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
||||||
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
|
assert_eq!(
|
||||||
|
classify_http_code("404"),
|
||||||
|
None,
|
||||||
|
"endpoint absent -> unknown"
|
||||||
|
);
|
||||||
assert_eq!(classify_http_code("500"), None);
|
assert_eq!(classify_http_code("500"), None);
|
||||||
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
|
assert_eq!(
|
||||||
|
classify_http_code(" 200 "),
|
||||||
|
Some(false),
|
||||||
|
"whitespace tolerated"
|
||||||
|
);
|
||||||
assert_eq!(classify_http_code(""), None);
|
assert_eq!(classify_http_code(""), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,18 +19,20 @@
|
|||||||
//! ALKANE_PROBE_USER / ALKANE_PROBE_PASS if set (so a test can authenticate
|
//! ALKANE_PROBE_USER / ALKANE_PROBE_PASS if set (so a test can authenticate
|
||||||
//! without touching the app's saved config).
|
//! without touching the app's saved config).
|
||||||
|
|
||||||
use asic_rs::MinerFactory;
|
|
||||||
use asic_rs::core::traits::miner::MinerAuth;
|
use asic_rs::core::traits::miner::MinerAuth;
|
||||||
|
use asic_rs::MinerFactory;
|
||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
use measurements::Power;
|
use measurements::Power;
|
||||||
|
|
||||||
fn load_creds() -> Option<(String, String)> {
|
fn load_creds() -> Option<(String, String)> {
|
||||||
if let (Ok(u), Ok(pw)) = (std::env::var("ALKANE_PROBE_USER"), std::env::var("ALKANE_PROBE_PASS")) {
|
if let (Ok(u), Ok(pw)) = (
|
||||||
|
std::env::var("ALKANE_PROBE_USER"),
|
||||||
|
std::env::var("ALKANE_PROBE_PASS"),
|
||||||
|
) {
|
||||||
return Some((u, pw));
|
return Some((u, pw));
|
||||||
}
|
}
|
||||||
let home = std::env::var("HOME").ok()?;
|
let home = std::env::var("HOME").ok()?;
|
||||||
let p = std::path::PathBuf::from(home)
|
let p = std::path::PathBuf::from(home).join(".config/alkane-toolkit/scan-credentials.txt");
|
||||||
.join(".config/alkane-toolkit/scan-credentials.txt");
|
|
||||||
let s = std::fs::read_to_string(p).ok()?;
|
let s = std::fs::read_to_string(p).ok()?;
|
||||||
let mut l = s.lines();
|
let mut l = s.lines();
|
||||||
let u = l.next()?.to_string();
|
let u = l.next()?.to_string();
|
||||||
@@ -92,8 +94,14 @@ async fn scan(cidrs: &[String]) {
|
|||||||
.map(|c| c.to_string())
|
.map(|c| c.to_string())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let fw_ver = data.firmware_version.clone().unwrap_or_default();
|
let fw_ver = data.firmware_version.clone().unwrap_or_default();
|
||||||
let bs = data.best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
|
let bs = data
|
||||||
let sbs = data.session_best_share.map(|v| format!("{v:.0}")).unwrap_or_default();
|
.best_share
|
||||||
|
.map(|v| format!("{v:.0}"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let sbs = data
|
||||||
|
.session_best_share
|
||||||
|
.map(|v| format!("{v:.0}"))
|
||||||
|
.unwrap_or_default();
|
||||||
println!(
|
println!(
|
||||||
"{ip}\t{}\t{}\t{}\t{}\t{}\t{watts:.0}\t{}\t{}\t{bs}\t{sbs}",
|
"{ip}\t{}\t{}\t{}\t{}\t{}\t{watts:.0}\t{}\t{}\t{bs}\t{sbs}",
|
||||||
data.device_info.make,
|
data.device_info.make,
|
||||||
@@ -281,7 +289,10 @@ async fn msgs(ip_s: &str) {
|
|||||||
Ok(Some(m)) => {
|
Ok(Some(m)) => {
|
||||||
let d = m.get_data().await;
|
let d = m.get_data().await;
|
||||||
let th = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
|
let th = |h: &Option<asic_rs::core::data::hashrate::HashRate>| {
|
||||||
h.clone().map(|x| x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
|
h.clone().map(|x| {
|
||||||
|
x.as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash)
|
||||||
|
.value
|
||||||
|
})
|
||||||
};
|
};
|
||||||
println!(
|
println!(
|
||||||
"{ip}: {} {} hashboards={:?} expected={:?}",
|
"{ip}: {} {} hashboards={:?} expected={:?}",
|
||||||
@@ -389,7 +400,7 @@ async fn lifecycle(ip_s: &str, verb: &str) {
|
|||||||
|
|
||||||
/// Read (no tz arg) or set the miner's timezone (round 16 / G10). Capability-gated.
|
/// Read (no tz arg) or set the miner's timezone (round 16 / G10). Capability-gated.
|
||||||
async fn timezone(ip_s: &str, tz: Option<&str>) {
|
async fn timezone(ip_s: &str, tz: Option<&str>) {
|
||||||
use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
|
use asic_rs::core::config::timezone::{TimezoneConfig, Tz};
|
||||||
let Ok(ip) = ip_s.parse::<std::net::IpAddr>() else {
|
let Ok(ip) = ip_s.parse::<std::net::IpAddr>() else {
|
||||||
eprintln!("bad ip {ip_s}");
|
eprintln!("bad ip {ip_s}");
|
||||||
return;
|
return;
|
||||||
@@ -566,7 +577,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
|
|||||||
TuningTarget::HashRate(hr)
|
TuningTarget::HashRate(hr)
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
eprintln!("miner reports no current hashrate; cannot build a hashrate target");
|
eprintln!(
|
||||||
|
"miner reports no current hashrate; cannot build a hashrate target"
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -593,7 +606,9 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
|
|||||||
}
|
}
|
||||||
} else if kind == "power" && m.supports_set_power_limit() {
|
} else if kind == "power" && m.supports_set_power_limit() {
|
||||||
match m.set_power_limit(Power::from_watts(value)).await {
|
match m.set_power_limit(Power::from_watts(value)).await {
|
||||||
Ok(v) => println!("set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"),
|
Ok(v) => println!(
|
||||||
|
"set_power_limit({value} W) -> Ok({v}) [tuning_config unsupported]"
|
||||||
|
),
|
||||||
Err(e) => println!("set_power_limit({value} W) -> Err: {e:#}"),
|
Err(e) => println!("set_power_limit({value} W) -> Err: {e:#}"),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -680,7 +695,10 @@ async fn setpreset(ip_s: &str, name: &str) {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let args: Vec<String> = std::env::args().collect();
|
let args: Vec<String> = std::env::args().collect();
|
||||||
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
|
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
{
|
||||||
Ok(rt) => rt,
|
Ok(rt) => rt,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("tokio runtime: {e}");
|
eprintln!("tokio runtime: {e}");
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ use std::collections::HashMap;
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||||
|
|
||||||
use asic_rs::MinerFactory;
|
|
||||||
use asic_rs::core::traits::miner::MinerAuth;
|
use asic_rs::core::traits::miner::MinerAuth;
|
||||||
|
use asic_rs::MinerFactory;
|
||||||
|
|
||||||
use crate::scan::config_path;
|
use crate::scan::config_path;
|
||||||
|
|
||||||
@@ -195,8 +195,8 @@ pub fn configured_factory() -> MinerFactory {
|
|||||||
// (round 18 #12: config actions / refresh / pools / flash previously used
|
// (round 18 #12: config actions / refresh / pools / flash previously used
|
||||||
// asic-rs's 10s default, so on a slow link they could fail to reach miners a
|
// asic-rs's 10s default, so on a slow link they could fail to reach miners a
|
||||||
// longer-timeout scan had found). start_scan may still override it explicitly.
|
// longer-timeout scan had found). start_scan may still override it explicitly.
|
||||||
let mut factory =
|
let mut factory = MinerFactory::new()
|
||||||
MinerFactory::new().with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
|
.with_identification_timeout_secs(crate::scan::load_scan_timeout().max(1));
|
||||||
let global = load_credentials();
|
let global = load_credentials();
|
||||||
let per_fw = load_firmware_credentials();
|
let per_fw = load_firmware_credentials();
|
||||||
if global.is_none() && per_fw.is_empty() {
|
if global.is_none() && per_fw.is_empty() {
|
||||||
@@ -223,7 +223,9 @@ mod tests {
|
|||||||
// config_path() reads $HOME; point it at a private temp dir. HOME is
|
// config_path() reads $HOME; point it at a private temp dir. HOME is
|
||||||
// process-global, so serialise against other HOME-mutating tests via the
|
// process-global, so serialise against other HOME-mutating tests via the
|
||||||
// shared lock and restore HOME afterward (round 18 #12).
|
// shared lock and restore HOME afterward (round 18 #12).
|
||||||
let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
let _home = crate::model::HOME_TEST_LOCK
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner());
|
||||||
let prev = std::env::var_os("HOME");
|
let prev = std::env::var_os("HOME");
|
||||||
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
@@ -233,10 +235,17 @@ mod tests {
|
|||||||
assert_eq!(load_credentials(), None, "no file -> None");
|
assert_eq!(load_credentials(), None, "no file -> None");
|
||||||
|
|
||||||
save_credentials("admin", "hunter2").unwrap();
|
save_credentials("admin", "hunter2").unwrap();
|
||||||
assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string())));
|
assert_eq!(
|
||||||
|
load_credentials(),
|
||||||
|
Some(("admin".to_string(), "hunter2".to_string()))
|
||||||
|
);
|
||||||
|
|
||||||
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
|
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
|
||||||
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
|
assert_eq!(
|
||||||
|
meta.permissions().mode() & 0o777,
|
||||||
|
0o600,
|
||||||
|
"credentials file must be 0600"
|
||||||
|
);
|
||||||
|
|
||||||
// configured_factory() must construct in both branches without panicking:
|
// configured_factory() must construct in both branches without panicking:
|
||||||
// with saved credentials (fans auth across every firmware backend) ...
|
// with saved credentials (fans auth across every firmware backend) ...
|
||||||
@@ -254,7 +263,10 @@ mod tests {
|
|||||||
0o600,
|
0o600,
|
||||||
"save over a pre-existing 0644 file must re-tighten to 0600"
|
"save over a pre-existing 0644 file must re-tighten to 0600"
|
||||||
);
|
);
|
||||||
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
|
assert_eq!(
|
||||||
|
load_credentials(),
|
||||||
|
Some(("admin2".to_string(), "s3cr3t".to_string()))
|
||||||
|
);
|
||||||
|
|
||||||
clear_credentials().unwrap();
|
clear_credentials().unwrap();
|
||||||
// ... and with no saved credentials (plain MinerFactory::new()).
|
// ... and with no saved credentials (plain MinerFactory::new()).
|
||||||
@@ -265,9 +277,15 @@ mod tests {
|
|||||||
// Per-firmware overrides (round 12 #13). Kept in this same test because
|
// Per-firmware overrides (round 12 #13). Kept in this same test because
|
||||||
// HOME is process-global: a second #[test] mutating it would race under
|
// HOME is process-global: a second #[test] mutating it would race under
|
||||||
// cargo's default parallel runner.
|
// cargo's default parallel runner.
|
||||||
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
|
assert!(
|
||||||
|
load_firmware_credentials().is_empty(),
|
||||||
|
"no file -> empty map"
|
||||||
|
);
|
||||||
let mut fw = HashMap::new();
|
let mut fw = HashMap::new();
|
||||||
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
|
fw.insert(
|
||||||
|
"WhatsMiner Stock".to_string(),
|
||||||
|
("super".to_string(), "sup3r".to_string()),
|
||||||
|
);
|
||||||
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
|
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
|
||||||
save_firmware_credentials(&fw).unwrap();
|
save_firmware_credentials(&fw).unwrap();
|
||||||
// 0600, and it round-trips (an empty username survives the tab format).
|
// 0600, and it round-trips (an empty username survives the tab format).
|
||||||
@@ -278,17 +296,29 @@ mod tests {
|
|||||||
"per-firmware creds file must be 0600"
|
"per-firmware creds file must be 0600"
|
||||||
);
|
);
|
||||||
let back = load_firmware_credentials();
|
let back = load_firmware_credentials();
|
||||||
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
|
assert_eq!(
|
||||||
|
back.get("WhatsMiner Stock"),
|
||||||
|
Some(&("super".into(), "sup3r".into()))
|
||||||
|
);
|
||||||
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
|
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
|
||||||
assert_eq!(back.len(), 2);
|
assert_eq!(back.len(), 2);
|
||||||
// Shipped-default lookup: known firmware resolves, unknown blanks.
|
// Shipped-default lookup: known firmware resolves, unknown blanks.
|
||||||
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
|
assert_eq!(
|
||||||
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
|
firmware_default_for("AntMiner Stock"),
|
||||||
|
("root".into(), "root".into())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
firmware_default_for("nonexistent"),
|
||||||
|
(String::new(), String::new())
|
||||||
|
);
|
||||||
// Overrides + no global still builds a factory.
|
// Overrides + no global still builds a factory.
|
||||||
let _ = configured_factory();
|
let _ = configured_factory();
|
||||||
// Saving an empty map clears the file (no stale overrides linger).
|
// Saving an empty map clears the file (no stale overrides linger).
|
||||||
save_firmware_credentials(&HashMap::new()).unwrap();
|
save_firmware_credentials(&HashMap::new()).unwrap();
|
||||||
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
|
assert!(
|
||||||
|
load_firmware_credentials().is_empty(),
|
||||||
|
"empty save -> cleared"
|
||||||
|
);
|
||||||
clear_firmware_credentials().unwrap(); // idempotent
|
clear_firmware_credentials().unwrap(); // idempotent
|
||||||
|
|
||||||
match prev {
|
match prev {
|
||||||
|
|||||||
@@ -100,28 +100,62 @@ fn scalar_columns() -> Vec<Col> {
|
|||||||
("slow", |r| r.slow.to_string()),
|
("slow", |r| r.slow.to_string()),
|
||||||
("paused", |r| r.paused.to_string()),
|
("paused", |r| r.paused.to_string()),
|
||||||
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
|
("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")),
|
||||||
("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")),
|
("write_locked", |r| {
|
||||||
("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")),
|
opt_bool(r.write_locked, "locked", "unlocked")
|
||||||
|
}),
|
||||||
|
("light_flashing", |r| {
|
||||||
|
opt_bool(r.light_flashing, "on", "off")
|
||||||
|
}),
|
||||||
("hashrate_ths", |r| num(r.hashrate_ths)),
|
("hashrate_ths", |r| num(r.hashrate_ths)),
|
||||||
("expected_ths", |r| num(r.expected_ths)),
|
("expected_ths", |r| num(r.expected_ths)),
|
||||||
("efficiency_j_th", |r| num(r.efficiency)),
|
("efficiency_j_th", |r| num(r.efficiency)),
|
||||||
("power_w", |r| num(r.power_w)),
|
("power_w", |r| num(r.power_w)),
|
||||||
("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()),
|
("tuning_percent", |r| {
|
||||||
|
r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()
|
||||||
|
}),
|
||||||
("chip_temp_c", |r| num(r.chip_temp_c)),
|
("chip_temp_c", |r| num(r.chip_temp_c)),
|
||||||
("fluid_temp_c", |r| num(r.fluid_temp_c)),
|
("fluid_temp_c", |r| num(r.fluid_temp_c)),
|
||||||
("env_temp_c", |r| num(r.env_temp_c)),
|
("env_temp_c", |r| num(r.env_temp_c)),
|
||||||
("outlet_temp_c", |r| num(r.outlet_temp_c)),
|
("outlet_temp_c", |r| num(r.outlet_temp_c)),
|
||||||
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
|
("psu_fan_rpm", |r| num(r.psu_fan_rpm)),
|
||||||
("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()),
|
("fan_count", |r| {
|
||||||
("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()),
|
r.fan_count.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()),
|
("expected_fans", |r| {
|
||||||
("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()),
|
r.expected_fans.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() }),
|
("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()),
|
("best_share", |r| r.best_share.map(num).unwrap_or_default()),
|
||||||
("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()),
|
("session_best_share", |r| {
|
||||||
("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()),
|
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()),
|
("pool_url", |r| r.pool_url.clone()),
|
||||||
("errors", |r| r.errors.join("; ")),
|
("errors", |r| r.errors.join("; ")),
|
||||||
]
|
]
|
||||||
@@ -137,7 +171,10 @@ pub const GROUP_POOLS: &str = "pools";
|
|||||||
/// Every selectable export field, in output order: each scalar column header,
|
/// Every selectable export field, in output order: each scalar column header,
|
||||||
/// then the four variable-length group keys.
|
/// then the four variable-length group keys.
|
||||||
pub fn export_field_names() -> Vec<String> {
|
pub fn export_field_names() -> Vec<String> {
|
||||||
let mut v: Vec<String> = scalar_columns().iter().map(|(h, _)| (*h).to_string()).collect();
|
let mut v: Vec<String> = scalar_columns()
|
||||||
|
.iter()
|
||||||
|
.map(|(h, _)| (*h).to_string())
|
||||||
|
.collect();
|
||||||
v.push(GROUP_BOARD_TEMPS.to_string());
|
v.push(GROUP_BOARD_TEMPS.to_string());
|
||||||
v.push(GROUP_FANS.to_string());
|
v.push(GROUP_FANS.to_string());
|
||||||
v.push(GROUP_BOARD_STATUS.to_string());
|
v.push(GROUP_BOARD_STATUS.to_string());
|
||||||
@@ -152,16 +189,26 @@ pub fn rows_to_csv_selected(
|
|||||||
rows: &[MinerRow],
|
rows: &[MinerRow],
|
||||||
selected: &std::collections::HashSet<String>,
|
selected: &std::collections::HashSet<String>,
|
||||||
) -> String {
|
) -> String {
|
||||||
let cols: Vec<Col> =
|
let cols: Vec<Col> = scalar_columns()
|
||||||
scalar_columns().into_iter().filter(|(h, _)| selected.contains(*h)).collect();
|
.into_iter()
|
||||||
|
.filter(|(h, _)| selected.contains(*h))
|
||||||
|
.collect();
|
||||||
// A group's columns appear only when it is selected; an unselected group's
|
// A group's columns appear only when it is selected; an unselected group's
|
||||||
// width stays 0, so the header/value loops below emit nothing for it.
|
// width stays 0, so the header/value loops below emit nothing for it.
|
||||||
let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize {
|
let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize {
|
||||||
if want { rows.iter().map(f).max().unwrap_or(0) } else { 0 }
|
if want {
|
||||||
|
rows.iter().map(f).max().unwrap_or(0)
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| r.board_temps.len());
|
let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| {
|
||||||
|
r.board_temps.len()
|
||||||
|
});
|
||||||
let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len());
|
let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len());
|
||||||
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| r.board_status.len());
|
let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| {
|
||||||
|
r.board_status.len()
|
||||||
|
});
|
||||||
let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len());
|
let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len());
|
||||||
|
|
||||||
// Header.
|
// Header.
|
||||||
@@ -193,7 +240,13 @@ pub fn rows_to_csv_selected(
|
|||||||
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
|
vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default());
|
||||||
}
|
}
|
||||||
for i in 0..max_boards {
|
for i in 0..max_boards {
|
||||||
vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string());
|
vals.push(
|
||||||
|
r.board_status
|
||||||
|
.get(i)
|
||||||
|
.map(board_health_str)
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for i in 0..max_pools {
|
for i in 0..max_pools {
|
||||||
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
|
let (u, w) = r.pools.get(i).cloned().unwrap_or_default();
|
||||||
@@ -222,7 +275,11 @@ mod tests {
|
|||||||
fan_rpms: vec![6000.0, 6100.0],
|
fan_rpms: vec![6000.0, 6100.0],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() },
|
MinerRow {
|
||||||
|
ip: "10.0.0.2".into(),
|
||||||
|
model: "M30S".into(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
];
|
];
|
||||||
let all: std::collections::HashSet<String> = export_field_names().into_iter().collect();
|
let all: std::collections::HashSet<String> = export_field_names().into_iter().collect();
|
||||||
let csv = rows_to_csv_selected(&rows, &all);
|
let csv = rows_to_csv_selected(&rows, &all);
|
||||||
|
|||||||
@@ -42,9 +42,22 @@ impl Board {
|
|||||||
let slow = is_slow(self.mining, self.hashrate, self.expected);
|
let slow = is_slow(self.mining, self.hashrate, self.expected);
|
||||||
// A few extra metrics so the demo/offline mode shows non-empty values
|
// A few extra metrics so the demo/offline mode shows non-empty values
|
||||||
// for some of the additional columns.
|
// for some of the additional columns.
|
||||||
let last_octet: u8 = self.ip.rsplit('.').next().and_then(|s| s.parse().ok()).unwrap_or(0);
|
let last_octet: u8 = self
|
||||||
|
.ip
|
||||||
|
.rsplit('.')
|
||||||
|
.next()
|
||||||
|
.and_then(|s| s.parse().ok())
|
||||||
|
.unwrap_or(0);
|
||||||
let (boards, chips, efficiency) = if self.mining {
|
let (boards, chips, efficiency) = if self.mining {
|
||||||
(Some(3u32), Some(210u32), if self.hashrate > 0.0 { self.power / self.hashrate } else { 0.0 })
|
(
|
||||||
|
Some(3u32),
|
||||||
|
Some(210u32),
|
||||||
|
if self.hashrate > 0.0 {
|
||||||
|
self.power / self.hashrate
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
},
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
(None, None, 0.0)
|
(None, None, 0.0)
|
||||||
};
|
};
|
||||||
@@ -63,7 +76,11 @@ impl Board {
|
|||||||
// Per-board hashrate for the R2 Health tooltip demo: split the total three
|
// Per-board hashrate for the R2 Health tooltip demo: split the total three
|
||||||
// ways with a little variety (index-aligned with the 3 boards).
|
// ways with a little variety (index-aligned with the 3 boards).
|
||||||
let board_hashrates = if self.mining && self.hashrate > 0.0 {
|
let board_hashrates = if self.mining && self.hashrate > 0.0 {
|
||||||
vec![self.hashrate * 0.34, self.hashrate * 0.35, self.hashrate * 0.31]
|
vec![
|
||||||
|
self.hashrate * 0.34,
|
||||||
|
self.hashrate * 0.35,
|
||||||
|
self.hashrate * 0.31,
|
||||||
|
]
|
||||||
} else {
|
} else {
|
||||||
vec![]
|
vec![]
|
||||||
};
|
};
|
||||||
@@ -147,7 +164,10 @@ impl Board {
|
|||||||
slow,
|
slow,
|
||||||
paused: self.paused,
|
paused: self.paused,
|
||||||
// offline defaults to false (online); these bench rows are reachable.
|
// offline defaults to false (online); these bench rows are reachable.
|
||||||
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
|
mac: format!(
|
||||||
|
"AA:BB:CC:00:{:02X}:{last_octet:02X}",
|
||||||
|
last_octet.wrapping_mul(3)
|
||||||
|
),
|
||||||
hostname: format!("miner-{last_octet}"),
|
hostname: format!("miner-{last_octet}"),
|
||||||
hashboards: boards,
|
hashboards: boards,
|
||||||
expected_hashboards: Some(3),
|
expected_hashboards: Some(3),
|
||||||
@@ -156,22 +176,40 @@ impl Board {
|
|||||||
psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 },
|
psu_fan_rpm: if self.mining { self.fan * 0.9 } else { 0.0 },
|
||||||
// PSU info demo (round 17 R5): mining units show a version + rated
|
// PSU info demo (round 17 R5): mining units show a version + rated
|
||||||
// envelope + live output, so the columns and the R2 PSU tooltip render.
|
// envelope + live output, so the columns and the R2 PSU tooltip render.
|
||||||
psu_version: if self.mining { "22 (117)".to_string() } else { String::new() },
|
psu_version: if self.mining {
|
||||||
|
"22 (117)".to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
psu_voltage_min_v: self.mining.then_some(11.88),
|
psu_voltage_min_v: self.mining.then_some(11.88),
|
||||||
psu_voltage_max_v: self.mining.then_some(15.18),
|
psu_voltage_max_v: self.mining.then_some(15.18),
|
||||||
psu_out_voltage_v: self.mining.then_some(13.2),
|
psu_out_voltage_v: self.mining.then_some(13.2),
|
||||||
psu_out_current_a: self.mining.then_some(210.0),
|
psu_out_current_a: self.mining.then_some(210.0),
|
||||||
uptime_secs: if self.mining { 3600 * 24 * 2 + 3600 * 5 } else { 0 },
|
uptime_secs: if self.mining {
|
||||||
|
3600 * 24 * 2 + 3600 * 5
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
},
|
||||||
// One unit is "being located" so the Light column's yellow dot is
|
// One unit is "being located" so the Light column's yellow dot is
|
||||||
// demonstrable offline (round 11 #10).
|
// demonstrable offline (round 11 #10).
|
||||||
light_flashing: Some(self.ip == "10.255.1.167"),
|
light_flashing: Some(self.ip == "10.255.1.167"),
|
||||||
pool_url: if self.worker.is_empty() { String::new() } else { "stratum+tcp://pool.blueflare:3333".to_string() },
|
pool_url: if self.worker.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
"stratum+tcp://pool.blueflare:3333".to_string()
|
||||||
|
},
|
||||||
pools: if self.worker.is_empty() {
|
pools: if self.worker.is_empty() {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
} else {
|
} else {
|
||||||
vec![
|
vec![
|
||||||
("stratum+tcp://pool.blueflare:3333".to_string(), self.worker.to_string()),
|
(
|
||||||
("stratum+tcp://backup.blueflare:3333".to_string(), format!("{}_bak", self.worker)),
|
"stratum+tcp://pool.blueflare:3333".to_string(),
|
||||||
|
self.worker.to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"stratum+tcp://backup.blueflare:3333".to_string(),
|
||||||
|
format!("{}_bak", self.worker),
|
||||||
|
),
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
operating_state: if self.paused {
|
operating_state: if self.paused {
|
||||||
@@ -223,9 +261,18 @@ impl Board {
|
|||||||
// is exercisable offline on units that advertise preset support.
|
// is exercisable offline on units that advertise preset support.
|
||||||
presets: if self.mining {
|
presets: if self.mining {
|
||||||
vec![
|
vec![
|
||||||
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
|
crate::model::MinerPreset {
|
||||||
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
|
name: "default".into(),
|
||||||
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
|
pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()),
|
||||||
|
},
|
||||||
|
crate::model::MinerPreset {
|
||||||
|
name: "540MHz".into(),
|
||||||
|
pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()),
|
||||||
|
},
|
||||||
|
crate::model::MinerPreset {
|
||||||
|
name: "490MHz".into(),
|
||||||
|
pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()),
|
||||||
|
},
|
||||||
]
|
]
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
@@ -247,35 +294,152 @@ pub fn bench_fleet() -> Vec<MinerRow> {
|
|||||||
let boards = [
|
let boards = [
|
||||||
// firmware families span the palette (Stock/VNish/Braiins/LuxOS/ePIC/
|
// firmware families span the palette (Stock/VNish/Braiins/LuxOS/ePIC/
|
||||||
// Hive/BixBit/Alkane) so the offline demo shows the Firmware colouring.
|
// Hive/BixBit/Alkane) so the offline demo shows the Firmware colouring.
|
||||||
Board { ip: "10.255.1.112", make: "Antminer", model_id: "S17", board: "Xilinx", firmware: "Stock", fw_version: "",
|
Board {
|
||||||
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
|
ip: "10.255.1.112",
|
||||||
worker: "", mining: false, paused: false },
|
make: "Antminer",
|
||||||
Board { ip: "10.255.1.166", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "VNish", fw_version: "1.2.8",
|
model_id: "S17",
|
||||||
hashrate: 95.0, expected: 96.0, power: 3250.0, temp: 65.0, fan: 4200.0,
|
board: "Xilinx",
|
||||||
worker: "blueflare.s19", mining: true, paused: false },
|
firmware: "Stock",
|
||||||
Board { ip: "10.255.1.152", make: "Antminer", model_id: "S19jPro", board: "AMLogic", firmware: "Braiins", fw_version: "25.05.1",
|
fw_version: "",
|
||||||
hashrate: 100.0, expected: 104.0, power: 3100.0, temp: 62.0, fan: 3900.0,
|
hashrate: 0.0,
|
||||||
worker: "blueflare.s19jpro", mining: true, paused: false },
|
expected: 0.0,
|
||||||
Board { ip: "10.255.1.167", make: "Antminer", model_id: "S19KPro", board: "AMLogic", firmware: "LuxOS", fw_version: "2024.9.0",
|
power: 0.0,
|
||||||
hashrate: 120.0, expected: 128.0, power: 3300.0, temp: 68.0, fan: 4500.0,
|
temp: 0.0,
|
||||||
worker: "blueflare.s19kpro", mining: true, paused: false },
|
fan: 0.0,
|
||||||
Board { ip: "10.255.1.149", make: "Antminer", model_id: "S21Pro", board: "CVITek", firmware: "ePIC", fw_version: "1.0.3",
|
worker: "",
|
||||||
hashrate: 60.0, expected: 200.0, power: 1500.0, temp: 55.0, fan: 3000.0,
|
mining: false,
|
||||||
worker: "blueflare.s21pro", mining: true, paused: false }, // slow: 60/200 = 30%
|
paused: false,
|
||||||
Board { ip: "10.255.1.126", make: "Whatsminer", model_id: "M30SVE40", board: "H3", firmware: "Stock", fw_version: "H3.0.1",
|
},
|
||||||
hashrate: 92.0, expected: 96.0, power: 3400.0, temp: 70.0, fan: 4800.0,
|
Board {
|
||||||
worker: "blueflare.h3", mining: true, paused: false },
|
ip: "10.255.1.166",
|
||||||
Board { ip: "10.255.1.131", make: "Whatsminer", model_id: "M30SPlusVE40", board: "H616", firmware: "Hiveon", fw_version: "1.05",
|
make: "Antminer",
|
||||||
hashrate: 100.0, expected: 100.0, power: 3450.0, temp: 71.0, fan: 4900.0,
|
model_id: "S19",
|
||||||
worker: "blueflare.h616", mining: true, paused: false },
|
board: "BeagleBoneBlack",
|
||||||
Board { ip: "10.255.1.148", make: "Whatsminer", model_id: "M50VH50", board: "H6", firmware: "Bixbit", fw_version: "0.9.9.4",
|
firmware: "VNish",
|
||||||
hashrate: 118.0, expected: 122.0, power: 3300.0, temp: 66.0, fan: 4600.0,
|
fw_version: "1.2.8",
|
||||||
worker: "blueflare.m50", mining: true, paused: false },
|
hashrate: 95.0,
|
||||||
|
expected: 96.0,
|
||||||
|
power: 3250.0,
|
||||||
|
temp: 65.0,
|
||||||
|
fan: 4200.0,
|
||||||
|
worker: "blueflare.s19",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.152",
|
||||||
|
make: "Antminer",
|
||||||
|
model_id: "S19jPro",
|
||||||
|
board: "AMLogic",
|
||||||
|
firmware: "Braiins",
|
||||||
|
fw_version: "25.05.1",
|
||||||
|
hashrate: 100.0,
|
||||||
|
expected: 104.0,
|
||||||
|
power: 3100.0,
|
||||||
|
temp: 62.0,
|
||||||
|
fan: 3900.0,
|
||||||
|
worker: "blueflare.s19jpro",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.167",
|
||||||
|
make: "Antminer",
|
||||||
|
model_id: "S19KPro",
|
||||||
|
board: "AMLogic",
|
||||||
|
firmware: "LuxOS",
|
||||||
|
fw_version: "2024.9.0",
|
||||||
|
hashrate: 120.0,
|
||||||
|
expected: 128.0,
|
||||||
|
power: 3300.0,
|
||||||
|
temp: 68.0,
|
||||||
|
fan: 4500.0,
|
||||||
|
worker: "blueflare.s19kpro",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.149",
|
||||||
|
make: "Antminer",
|
||||||
|
model_id: "S21Pro",
|
||||||
|
board: "CVITek",
|
||||||
|
firmware: "ePIC",
|
||||||
|
fw_version: "1.0.3",
|
||||||
|
hashrate: 60.0,
|
||||||
|
expected: 200.0,
|
||||||
|
power: 1500.0,
|
||||||
|
temp: 55.0,
|
||||||
|
fan: 3000.0,
|
||||||
|
worker: "blueflare.s21pro",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
}, // slow: 60/200 = 30%
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.126",
|
||||||
|
make: "Whatsminer",
|
||||||
|
model_id: "M30SVE40",
|
||||||
|
board: "H3",
|
||||||
|
firmware: "Stock",
|
||||||
|
fw_version: "H3.0.1",
|
||||||
|
hashrate: 92.0,
|
||||||
|
expected: 96.0,
|
||||||
|
power: 3400.0,
|
||||||
|
temp: 70.0,
|
||||||
|
fan: 4800.0,
|
||||||
|
worker: "blueflare.h3",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.131",
|
||||||
|
make: "Whatsminer",
|
||||||
|
model_id: "M30SPlusVE40",
|
||||||
|
board: "H616",
|
||||||
|
firmware: "Hiveon",
|
||||||
|
fw_version: "1.05",
|
||||||
|
hashrate: 100.0,
|
||||||
|
expected: 100.0,
|
||||||
|
power: 3450.0,
|
||||||
|
temp: 71.0,
|
||||||
|
fan: 4900.0,
|
||||||
|
worker: "blueflare.h616",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
|
Board {
|
||||||
|
ip: "10.255.1.148",
|
||||||
|
make: "Whatsminer",
|
||||||
|
model_id: "M50VH50",
|
||||||
|
board: "H6",
|
||||||
|
firmware: "Bixbit",
|
||||||
|
fw_version: "0.9.9.4",
|
||||||
|
hashrate: 118.0,
|
||||||
|
expected: 122.0,
|
||||||
|
power: 3300.0,
|
||||||
|
temp: 66.0,
|
||||||
|
fan: 4600.0,
|
||||||
|
worker: "blueflare.m50",
|
||||||
|
mining: true,
|
||||||
|
paused: false,
|
||||||
|
},
|
||||||
// Rebucketed from idle/not-hashing to paused so the "paused"
|
// Rebucketed from idle/not-hashing to paused so the "paused"
|
||||||
// status/KPI bucket is exercisable in the fake-scan/offline demo.
|
// status/KPI bucket is exercisable in the fake-scan/offline demo.
|
||||||
Board { ip: "10.255.1.115", make: "Antminer", model_id: "S19", board: "BeagleBoneBlack", firmware: "Alkane", fw_version: "0.1",
|
Board {
|
||||||
hashrate: 0.0, expected: 0.0, power: 0.0, temp: 0.0, fan: 0.0,
|
ip: "10.255.1.115",
|
||||||
worker: "", mining: false, paused: true },
|
make: "Antminer",
|
||||||
|
model_id: "S19",
|
||||||
|
board: "BeagleBoneBlack",
|
||||||
|
firmware: "Alkane",
|
||||||
|
fw_version: "0.1",
|
||||||
|
hashrate: 0.0,
|
||||||
|
expected: 0.0,
|
||||||
|
power: 0.0,
|
||||||
|
temp: 0.0,
|
||||||
|
fan: 0.0,
|
||||||
|
worker: "",
|
||||||
|
mining: false,
|
||||||
|
paused: true,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
boards.into_iter().map(Board::into_row).collect()
|
boards.into_iter().map(Board::into_row).collect()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ impl Lang {
|
|||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Lang::En => "English",
|
Lang::En => "English",
|
||||||
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
|
Lang::Zh => "\u{4e2d}\u{6587}", // 中文
|
||||||
Lang::Ru => "\u{0420}\u{0443}\u{0441}\u{0441}\u{043a}\u{0438}\u{0439}", // Русский
|
Lang::Ru => "\u{0420}\u{0443}\u{0441}\u{0441}\u{043a}\u{0438}\u{0439}", // Русский
|
||||||
Lang::Fr => "Fran\u{e7}ais",
|
Lang::Fr => "Fran\u{e7}ais",
|
||||||
Lang::Es => "Espa\u{f1}ol",
|
Lang::Es => "Espa\u{f1}ol",
|
||||||
@@ -72,7 +72,9 @@ const LANG_FILE: &str = "language.txt";
|
|||||||
|
|
||||||
fn config_path() -> PathBuf {
|
fn config_path() -> PathBuf {
|
||||||
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
|
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
|
||||||
PathBuf::from(home).join(".config/alkane-toolkit").join(LANG_FILE)
|
PathBuf::from(home)
|
||||||
|
.join(".config/alkane-toolkit")
|
||||||
|
.join(LANG_FILE)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load the saved language into the global (call once at startup).
|
/// Load the saved language into the global (call once at startup).
|
||||||
|
|||||||
@@ -32,13 +32,17 @@ pub fn scan_log(ip: &str, brand: &str, timeout_secs: u64) -> Result<LogScan, Str
|
|||||||
if brand.eq_ignore_ascii_case("whatsminer") {
|
if brand.eq_ignore_ascii_case("whatsminer") {
|
||||||
let resp = crate::access_probe::whatsminer_get_error_code(ip)
|
let resp = crate::access_probe::whatsminer_get_error_code(ip)
|
||||||
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
|
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
|
||||||
return Ok(LogScan { text: tail(&resp, MAX_LOG_BYTES) });
|
return Ok(LogScan {
|
||||||
|
text: tail(&resp, MAX_LOG_BYTES),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
let text = crate::scan::fetch_log(ip, timeout_secs)?;
|
let text = crate::scan::fetch_log(ip, timeout_secs)?;
|
||||||
if text.trim().is_empty() {
|
if text.trim().is_empty() {
|
||||||
return Err("the miner returned an empty log".to_string());
|
return Err("the miner returned an empty log".to_string());
|
||||||
}
|
}
|
||||||
Ok(LogScan { text: tail(&text, MAX_LOG_BYTES) })
|
Ok(LogScan {
|
||||||
|
text: tail(&text, MAX_LOG_BYTES),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
|
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
|
||||||
@@ -55,7 +59,10 @@ fn tail(s: &str, max: usize) -> String {
|
|||||||
start += 1;
|
start += 1;
|
||||||
}
|
}
|
||||||
// then advance to the next line boundary so we don't cut a line in half
|
// then advance to the next line boundary so we don't cut a line in half
|
||||||
let start = s[start..].find('\n').map(|i| start + i + 1).unwrap_or(start);
|
let start = s[start..]
|
||||||
|
.find('\n')
|
||||||
|
.map(|i| start + i + 1)
|
||||||
|
.unwrap_or(start);
|
||||||
format!("[... earlier log trimmed ...]\n{}", &s[start..])
|
format!("[... earlier log trimmed ...]\n{}", &s[start..])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
|||||||
/// Local wall-clock HH:MM:SS for a log line. Uses the system clock offset from
|
/// Local wall-clock HH:MM:SS for a log line. Uses the system clock offset from
|
||||||
/// UTC via the TZ-less epoch; good enough for an activity log timestamp.
|
/// UTC via the TZ-less epoch; good enough for an activity log timestamp.
|
||||||
fn stamp() -> String {
|
fn stamp() -> String {
|
||||||
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
let secs = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0);
|
||||||
let t = secs % 86_400;
|
let t = secs % 86_400;
|
||||||
format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60)
|
format!("{:02}:{:02}:{:02}", t / 3600, (t % 3600) / 60, t % 60)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
|
//! alkane-toolkit: primary view (docs/UI-SPEC.md).
|
||||||
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
||||||
|
|
||||||
mod access_probe;
|
mod access_probe;
|
||||||
@@ -6,8 +6,8 @@ mod credentials;
|
|||||||
mod export;
|
mod export;
|
||||||
mod fixtures;
|
mod fixtures;
|
||||||
mod i18n;
|
mod i18n;
|
||||||
mod logs;
|
|
||||||
mod log_scan;
|
mod log_scan;
|
||||||
|
mod logs;
|
||||||
mod model;
|
mod model;
|
||||||
mod naming;
|
mod naming;
|
||||||
mod pool_prefs;
|
mod pool_prefs;
|
||||||
@@ -16,7 +16,6 @@ mod restore;
|
|||||||
mod scan;
|
mod scan;
|
||||||
mod ui;
|
mod ui;
|
||||||
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// Headless workflow self-test: render the bench-fleet fixtures through the
|
// Headless workflow self-test: render the bench-fleet fixtures through the
|
||||||
// real widgets and check the table + KPIs against the expected hardware
|
// real widgets and check the table + KPIs against the expected hardware
|
||||||
|
|||||||
+684
-175
File diff suppressed because it is too large
Load Diff
@@ -234,7 +234,10 @@ fn clean_antminer(id: &str) -> String {
|
|||||||
/// Normalise a raw control-board name for matching: drop spaces/punctuation and
|
/// Normalise a raw control-board name for matching: drop spaces/punctuation and
|
||||||
/// uppercase, so "BeagleBone Black", "BeagleBoneBlack" and "BBB" all collapse.
|
/// uppercase, so "BeagleBone Black", "BeagleBoneBlack" and "BBB" all collapse.
|
||||||
fn compact_upper(s: &str) -> String {
|
fn compact_upper(s: &str) -> String {
|
||||||
s.chars().filter(|c| c.is_ascii_alphanumeric()).flat_map(|c| c.to_uppercase()).collect()
|
s.chars()
|
||||||
|
.filter(|c| c.is_ascii_alphanumeric())
|
||||||
|
.flat_map(|c| c.to_uppercase())
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The control-board short code for the Control-board column, e.g.
|
/// The control-board short code for the Control-board column, e.g.
|
||||||
@@ -365,7 +368,10 @@ mod tests {
|
|||||||
assert_eq!(chip_type_for_model("Antminer", "S19"), Some("BM1398"));
|
assert_eq!(chip_type_for_model("Antminer", "S19"), Some("BM1398"));
|
||||||
assert_eq!(chip_type_for_model("Antminer", "T19"), Some("BM1398"));
|
assert_eq!(chip_type_for_model("Antminer", "T19"), Some("BM1398"));
|
||||||
// Raw "Unknown" passthrough with brand + parenthetical normalizes to S19.
|
// Raw "Unknown" passthrough with brand + parenthetical normalizes to S19.
|
||||||
assert_eq!(chip_type_for_model("Antminer", "ANTMINER S19 (88)"), Some("BM1398"));
|
assert_eq!(
|
||||||
|
chip_type_for_model("Antminer", "ANTMINER S19 (88)"),
|
||||||
|
Some("BM1398")
|
||||||
|
);
|
||||||
// WhatsMiner chips are not cleanly named -> never derived.
|
// WhatsMiner chips are not cleanly named -> never derived.
|
||||||
assert_eq!(chip_type_for_model("Whatsminer", "M30S+VE40"), None);
|
assert_eq!(chip_type_for_model("Whatsminer", "M30S+VE40"), None);
|
||||||
// Unknown Antminer model -> None (no guess).
|
// Unknown Antminer model -> None (no guess).
|
||||||
@@ -431,23 +437,56 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn control_board_short_codes() {
|
fn control_board_short_codes() {
|
||||||
// Antminer families (board name as asic-rs renders the enum variant).
|
// Antminer families (board name as asic-rs renders the enum variant).
|
||||||
assert_eq!(control_board_code("Antminer", "BeagleBoneBlack", "S19"), "BBB (C77)");
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "BeagleBoneBlack", "S19"),
|
||||||
|
"BBB (C77)"
|
||||||
|
);
|
||||||
// Also accept the spaced form some layers produce.
|
// Also accept the spaced form some layers produce.
|
||||||
assert_eq!(control_board_code("Antminer", "BeagleBone Black", "S19"), "BBB (C77)");
|
assert_eq!(
|
||||||
assert_eq!(control_board_code("Antminer", "CVITek", "S21 Pro"), "CVI (C88)");
|
control_board_code("Antminer", "BeagleBone Black", "S19"),
|
||||||
assert_eq!(control_board_code("Antminer", "Xilinx", "S17 Pro"), "XIL (C49)");
|
"BBB (C77)"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "CVITek", "S21 Pro"),
|
||||||
|
"CVI (C88)"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "Xilinx", "S17 Pro"),
|
||||||
|
"XIL (C49)"
|
||||||
|
);
|
||||||
assert_eq!(control_board_code("Antminer", "Xilinx", "T17"), "XIL (C49)");
|
assert_eq!(control_board_code("Antminer", "Xilinx", "T17"), "XIL (C49)");
|
||||||
assert_eq!(control_board_code("Antminer", "Xilinx", "S19 Pro"), "XIL (C55)");
|
assert_eq!(
|
||||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19j Pro"), "AML (C76)");
|
control_board_code("Antminer", "Xilinx", "S19 Pro"),
|
||||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19k Pro"), "AML (CBE)");
|
"XIL (C55)"
|
||||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S19 XP"), "AML (CBE)");
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "AMLogic", "S19j Pro"),
|
||||||
|
"AML (C76)"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "AMLogic", "S19k Pro"),
|
||||||
|
"AML (CBE)"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "AMLogic", "S19 XP"),
|
||||||
|
"AML (CBE)"
|
||||||
|
);
|
||||||
// WhatsMiner families.
|
// WhatsMiner families.
|
||||||
assert_eq!(control_board_code("Whatsminer", "H3", "M30S"), "H3 (CB2)");
|
assert_eq!(control_board_code("Whatsminer", "H3", "M30S"), "H3 (CB2)");
|
||||||
assert_eq!(control_board_code("Whatsminer", "H6", "M50"), "H6 (CB4)");
|
assert_eq!(control_board_code("Whatsminer", "H6", "M50"), "H6 (CB4)");
|
||||||
assert_eq!(control_board_code("Whatsminer", "H6OS", "M50"), "H6os (CB4)");
|
assert_eq!(
|
||||||
assert_eq!(control_board_code("Whatsminer", "H616", "M30S+"), "H616 (CB6)");
|
control_board_code("Whatsminer", "H6OS", "M50"),
|
||||||
|
"H6os (CB4)"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
control_board_code("Whatsminer", "H616", "M30S+"),
|
||||||
|
"H616 (CB6)"
|
||||||
|
);
|
||||||
// Unknown / blank pass through.
|
// Unknown / blank pass through.
|
||||||
assert_eq!(control_board_code("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "Unknown: FOO", "S19"),
|
||||||
|
"Unknown: FOO"
|
||||||
|
);
|
||||||
assert_eq!(control_board_code("Antminer", "", "S19"), "");
|
assert_eq!(control_board_code("Antminer", "", "S19"), "");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -455,23 +494,35 @@ mod tests {
|
|||||||
fn control_board_cpu_and_board_split() {
|
fn control_board_cpu_and_board_split() {
|
||||||
// CPU column vs board-code column.
|
// CPU column vs board-code column.
|
||||||
assert_eq!(control_board_cpu("Antminer", "AMLogic", "S19j Pro"), "AML");
|
assert_eq!(control_board_cpu("Antminer", "AMLogic", "S19j Pro"), "AML");
|
||||||
assert_eq!(control_board_board("Antminer", "AMLogic", "S19j Pro"), "C76");
|
assert_eq!(
|
||||||
|
control_board_board("Antminer", "AMLogic", "S19j Pro"),
|
||||||
|
"C76"
|
||||||
|
);
|
||||||
assert_eq!(control_board_cpu("Antminer", "CVITek", "S21 Pro"), "CVI");
|
assert_eq!(control_board_cpu("Antminer", "CVITek", "S21 Pro"), "CVI");
|
||||||
assert_eq!(control_board_board("Antminer", "CVITek", "S21 Pro"), "C88");
|
assert_eq!(control_board_board("Antminer", "CVITek", "S21 Pro"), "C88");
|
||||||
assert_eq!(control_board_cpu("Whatsminer", "H616", "M30S+"), "H616");
|
assert_eq!(control_board_cpu("Whatsminer", "H616", "M30S+"), "H616");
|
||||||
assert_eq!(control_board_board("Whatsminer", "H616", "M30S+"), "CB6");
|
assert_eq!(control_board_board("Whatsminer", "H616", "M30S+"), "CB6");
|
||||||
// S21 Pro on an AMLogic board is the 140mm CBE, not C76.
|
// S21 Pro on an AMLogic board is the 140mm CBE, not C76.
|
||||||
assert_eq!(control_board_board("Antminer", "AMLogic", "S21 Pro"), "CBE");
|
assert_eq!(control_board_board("Antminer", "AMLogic", "S21 Pro"), "CBE");
|
||||||
assert_eq!(control_board_code("Antminer", "AMLogic", "S21 Pro"), "AML (CBE)");
|
assert_eq!(
|
||||||
|
control_board_code("Antminer", "AMLogic", "S21 Pro"),
|
||||||
|
"AML (CBE)"
|
||||||
|
);
|
||||||
// Unknown -> cpu holds the raw string, no board code.
|
// Unknown -> cpu holds the raw string, no board code.
|
||||||
assert_eq!(control_board_cpu("Antminer", "Unknown: FOO", "S19"), "Unknown: FOO");
|
assert_eq!(
|
||||||
|
control_board_cpu("Antminer", "Unknown: FOO", "S19"),
|
||||||
|
"Unknown: FOO"
|
||||||
|
);
|
||||||
assert_eq!(control_board_board("Antminer", "Unknown: FOO", "S19"), "");
|
assert_eq!(control_board_board("Antminer", "Unknown: FOO", "S19"), "");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn firmware_family_splits_vendor_prefix() {
|
fn firmware_family_splits_vendor_prefix() {
|
||||||
// Stock firmware: vendor word moves out of the family word (round 11 #6).
|
// Stock firmware: vendor word moves out of the family word (round 11 #6).
|
||||||
assert_eq!(firmware_family("AntMiner Stock"), ("Stock".to_string(), Some("AntMiner".to_string())));
|
assert_eq!(
|
||||||
|
firmware_family("AntMiner Stock"),
|
||||||
|
("Stock".to_string(), Some("AntMiner".to_string()))
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
firmware_family("WhatsMiner Stock"),
|
firmware_family("WhatsMiner Stock"),
|
||||||
("Stock".to_string(), Some("WhatsMiner".to_string()))
|
("Stock".to_string(), Some("WhatsMiner".to_string()))
|
||||||
|
|||||||
@@ -36,8 +36,20 @@ impl PoolField {
|
|||||||
PoolField::Account => Vec::new(),
|
PoolField::Account => Vec::new(),
|
||||||
// Per-miner worker-name placeholders (see MinerRow::expand_worker_template).
|
// Per-miner worker-name placeholders (see MinerRow::expand_worker_template).
|
||||||
PoolField::Worker => vec![
|
PoolField::Worker => vec![
|
||||||
"{ip1}", "{ip2}", "{ip3}", "{ip4}", "{serial}", "{mac}", "{nameplate-hr}",
|
"{ip1}",
|
||||||
"{brand}", "{model}", "{submodel}", "{cpu}", "{cb}", "{firmware}", "{hostname}",
|
"{ip2}",
|
||||||
|
"{ip3}",
|
||||||
|
"{ip4}",
|
||||||
|
"{serial}",
|
||||||
|
"{mac}",
|
||||||
|
"{nameplate-hr}",
|
||||||
|
"{brand}",
|
||||||
|
"{model}",
|
||||||
|
"{submodel}",
|
||||||
|
"{cpu}",
|
||||||
|
"{cb}",
|
||||||
|
"{firmware}",
|
||||||
|
"{hostname}",
|
||||||
],
|
],
|
||||||
PoolField::Password => vec!["x"],
|
PoolField::Password => vec!["x"],
|
||||||
}
|
}
|
||||||
@@ -68,7 +80,13 @@ fn config_path(file: &str) -> PathBuf {
|
|||||||
pub fn load_saved(field: PoolField) -> Vec<String> {
|
pub fn load_saved(field: PoolField) -> Vec<String> {
|
||||||
std::fs::read_to_string(config_path(field.saved_file()))
|
std::fs::read_to_string(config_path(field.saved_file()))
|
||||||
.ok()
|
.ok()
|
||||||
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect())
|
.map(|s| {
|
||||||
|
s.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.map(String::from)
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,13 +171,18 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
|
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
|
||||||
let presets = ["x", "{ip1}"];
|
let presets = ["x", "{ip1}"];
|
||||||
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
|
let vals: Vec<String> = [
|
||||||
.iter()
|
" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep",
|
||||||
.map(|s| s.to_string())
|
]
|
||||||
.collect();
|
.iter()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.collect();
|
||||||
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
|
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
|
||||||
// "keep" all drop; " keep " is trimmed and kept.
|
// "keep" all drop; " keep " is trimmed and kept.
|
||||||
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
|
assert_eq!(
|
||||||
|
dedupe_saved(&presets, &vals),
|
||||||
|
vec!["myworker".to_string(), "keep".to_string()]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -43,7 +43,12 @@ impl PresetView {
|
|||||||
PresetView {
|
PresetView {
|
||||||
order: v.order.clone(),
|
order: v.order.clone(),
|
||||||
// keep the visible columns in display order for stability
|
// keep the visible columns in display order for stability
|
||||||
visible: v.order.iter().copied().filter(|c| v.visible.contains(c)).collect(),
|
visible: v
|
||||||
|
.order
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|c| v.visible.contains(c))
|
||||||
|
.collect(),
|
||||||
sort: v.sort,
|
sort: v.sort,
|
||||||
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
|
filters: v.filters.iter().map(|(k, f)| (*k, f.clone())).collect(),
|
||||||
}
|
}
|
||||||
@@ -62,7 +67,12 @@ impl PresetView {
|
|||||||
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
|
let mut visible: HashSet<Column> = self.visible.iter().copied().collect();
|
||||||
visible.insert(Column::Ip); // IP is always shown
|
visible.insert(Column::Ip); // IP is always shown
|
||||||
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
|
let filters: HashMap<Column, ColFilter> = self.filters.iter().cloned().collect();
|
||||||
ViewState { order, visible, sort: self.sort, filters }
|
ViewState {
|
||||||
|
order,
|
||||||
|
visible,
|
||||||
|
sort: self.sort,
|
||||||
|
filters,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,8 +144,14 @@ mod tests {
|
|||||||
// The Health column (round 13 #3) replaced these in the default profile.
|
// The Health column (round 13 #3) replaced these in the default profile.
|
||||||
assert!(!view.visible.contains(&Column::Error));
|
assert!(!view.visible.contains(&Column::Error));
|
||||||
// Columns dropped from the default profile in round 11.
|
// Columns dropped from the default profile in round 11.
|
||||||
assert!(!view.visible.contains(&Column::BoardCode), "not in the default profile");
|
assert!(
|
||||||
assert!(!view.visible.contains(&Column::Fan1), "not in the default profile");
|
!view.visible.contains(&Column::BoardCode),
|
||||||
|
"not in the default profile"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!view.visible.contains(&Column::Fan1),
|
||||||
|
"not in the default profile"
|
||||||
|
);
|
||||||
// to_view covers every column in `order`.
|
// to_view covers every column in `order`.
|
||||||
assert_eq!(view.order.len(), ALL_COLUMNS.len());
|
assert_eq!(view.order.len(), ALL_COLUMNS.len());
|
||||||
// Round-trip a snapshot back out.
|
// Round-trip a snapshot back out.
|
||||||
|
|||||||
@@ -16,16 +16,20 @@
|
|||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::net::{SocketAddr, TcpStream};
|
use std::net::{SocketAddr, TcpStream};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::mpsc::{Receiver, channel};
|
use std::sync::mpsc::{channel, Receiver};
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::scan::fake_scan_enabled;
|
use crate::scan::fake_scan_enabled;
|
||||||
|
|
||||||
pub enum RestoreMsg {
|
pub enum RestoreMsg {
|
||||||
Started,
|
Started,
|
||||||
Result { ip: String, ok: bool, detail: String },
|
Result {
|
||||||
|
ip: String,
|
||||||
|
ok: bool,
|
||||||
|
detail: String,
|
||||||
|
},
|
||||||
Done,
|
Done,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +91,14 @@ pub fn start_restore(
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass);
|
let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass);
|
||||||
if tx.send(RestoreMsg::Result { ip: t.ip, ok, detail }).is_err() {
|
if tx
|
||||||
|
.send(RestoreMsg::Result {
|
||||||
|
ip: t.ip,
|
||||||
|
ok,
|
||||||
|
detail,
|
||||||
|
})
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,7 +117,12 @@ pub fn start_restore(
|
|||||||
RestoreHandle { rx, cancel }
|
RestoreHandle { rx, cancel }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &str) -> (bool, String) {
|
fn restore_one(
|
||||||
|
t: &RestoreTarget,
|
||||||
|
vnish_pass: &str,
|
||||||
|
ssh_user: &str,
|
||||||
|
ssh_pass: &str,
|
||||||
|
) -> (bool, String) {
|
||||||
let fw = t.firmware.to_ascii_lowercase();
|
let fw = t.firmware.to_ascii_lowercase();
|
||||||
if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") {
|
if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") {
|
||||||
restore_vnish(&t.ip, vnish_pass)
|
restore_vnish(&t.ip, vnish_pass)
|
||||||
@@ -115,7 +131,10 @@ fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &s
|
|||||||
} else if fw.contains("braiins") || fw.contains("bos") {
|
} else if fw.contains("braiins") || fw.contains("bos") {
|
||||||
restore_braiins(&t.ip, ssh_user, ssh_pass)
|
restore_braiins(&t.ip, ssh_user, ssh_pass)
|
||||||
} else {
|
} else {
|
||||||
(false, format!("no restore-to-stock path for firmware '{}'", t.firmware))
|
(
|
||||||
|
false,
|
||||||
|
format!("no restore-to-stock path for firmware '{}'", t.firmware),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,9 +146,17 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
|
|||||||
let body = serde_json::json!({ "pw": pass }).to_string();
|
let body = serde_json::json!({ "pw": pass }).to_string();
|
||||||
let unlock = match curl(
|
let unlock = match curl(
|
||||||
&[
|
&[
|
||||||
"-s", "--connect-timeout", "5", "--max-time", "9",
|
"-s",
|
||||||
"-X", "POST", "-H", "Content-Type: application/json",
|
"--connect-timeout",
|
||||||
"-d", "@-",
|
"5",
|
||||||
|
"--max-time",
|
||||||
|
"9",
|
||||||
|
"-X",
|
||||||
|
"POST",
|
||||||
|
"-H",
|
||||||
|
"Content-Type: application/json",
|
||||||
|
"-d",
|
||||||
|
"@-",
|
||||||
&format!("http://{ip}/api/v1/unlock"),
|
&format!("http://{ip}/api/v1/unlock"),
|
||||||
],
|
],
|
||||||
Some(body.as_bytes()),
|
Some(body.as_bytes()),
|
||||||
@@ -146,8 +173,15 @@ fn restore_vnish(ip: &str, pass: &str) -> (bool, String) {
|
|||||||
};
|
};
|
||||||
match curl(
|
match curl(
|
||||||
&[
|
&[
|
||||||
"-s", "--connect-timeout", "5", "--max-time", "12",
|
"-s",
|
||||||
"-X", "POST", "-H", &format!("Authorization: Bearer {token}"),
|
"--connect-timeout",
|
||||||
|
"5",
|
||||||
|
"--max-time",
|
||||||
|
"12",
|
||||||
|
"-X",
|
||||||
|
"POST",
|
||||||
|
"-H",
|
||||||
|
&format!("Authorization: Bearer {token}"),
|
||||||
&format!("http://{ip}/api/v1/firmware/remove"),
|
&format!("http://{ip}/api/v1/firmware/remove"),
|
||||||
],
|
],
|
||||||
None,
|
None,
|
||||||
@@ -174,7 +208,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
|
|||||||
.map(str::to_string)
|
.map(str::to_string)
|
||||||
});
|
});
|
||||||
let Some(session) = session.filter(|s| !s.is_empty()) else {
|
let Some(session) = session.filter(|s| !s.is_empty()) else {
|
||||||
return (false, format!("no SessionID in logon response: {}", logon.trim()));
|
return (
|
||||||
|
false,
|
||||||
|
format!("no SessionID in logon response: {}", logon.trim()),
|
||||||
|
);
|
||||||
};
|
};
|
||||||
// serde-encode so the miner-supplied SessionID can't break or inject into the
|
// serde-encode so the miner-supplied SessionID can't break or inject into the
|
||||||
// JSON-RPC command (round 18 #12).
|
// JSON-RPC command (round 18 #12).
|
||||||
@@ -206,7 +243,10 @@ fn restore_luxos(ip: &str) -> (bool, String) {
|
|||||||
/// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup).
|
/// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup).
|
||||||
fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||||
if pass.is_empty() {
|
if pass.is_empty() {
|
||||||
return (false, "Braiins restore needs an SSH password (set the SSH login)".into());
|
return (
|
||||||
|
false,
|
||||||
|
"Braiins restore needs an SSH password (set the SSH login)".into(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let target = format!("{user}@{ip}");
|
let target = format!("{user}@{ip}");
|
||||||
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
|
// sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it
|
||||||
@@ -218,10 +258,14 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
|||||||
cmd.env("SSHPASS", pass);
|
cmd.env("SSHPASS", pass);
|
||||||
cmd.arg("-e").arg("ssh");
|
cmd.arg("-e").arg("ssh");
|
||||||
cmd.args([
|
cmd.args([
|
||||||
"-o", "StrictHostKeyChecking=no",
|
"-o",
|
||||||
"-o", "UserKnownHostsFile=/dev/null",
|
"StrictHostKeyChecking=no",
|
||||||
"-o", "BatchMode=yes",
|
"-o",
|
||||||
"-o", "ConnectTimeout=8",
|
"UserKnownHostsFile=/dev/null",
|
||||||
|
"-o",
|
||||||
|
"BatchMode=yes",
|
||||||
|
"-o",
|
||||||
|
"ConnectTimeout=8",
|
||||||
&target,
|
&target,
|
||||||
"uninstall.sh || /sbin/uninstall.sh",
|
"uninstall.sh || /sbin/uninstall.sh",
|
||||||
]);
|
]);
|
||||||
@@ -247,7 +291,12 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
|||||||
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
|
/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be
|
||||||
/// reported as a FAILURE, never a false success. A dropped connection or a
|
/// reported as a FAILURE, never a false success. A dropped connection or a
|
||||||
/// timeout after the command started is the expected signature of the reboot.
|
/// timeout after the command started is the expected signature of the reboot.
|
||||||
fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bool) -> (bool, String) {
|
fn classify_braiins(
|
||||||
|
stdout: &str,
|
||||||
|
stderr: &str,
|
||||||
|
code: Option<i32>,
|
||||||
|
timed_out: bool,
|
||||||
|
) -> (bool, String) {
|
||||||
let err = stderr.to_lowercase();
|
let err = stderr.to_lowercase();
|
||||||
// ssh's own connection/auth failures (exit 255) never reach the remote command.
|
// ssh's own connection/auth failures (exit 255) never reach the remote command.
|
||||||
let conn_fail = [
|
let conn_fail = [
|
||||||
@@ -264,7 +313,10 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
|
|||||||
.any(|m| err.contains(m));
|
.any(|m| err.contains(m));
|
||||||
if conn_fail {
|
if conn_fail {
|
||||||
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
|
let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty());
|
||||||
return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error")));
|
return (
|
||||||
|
false,
|
||||||
|
format!("SSH failed: {}", why.unwrap_or("connection/auth error")),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let out = stdout.to_lowercase();
|
let out = stdout.to_lowercase();
|
||||||
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
|
if out.contains("not found") || out.contains("no such") || err.contains("not found") {
|
||||||
@@ -273,14 +325,19 @@ fn classify_braiins(stdout: &str, stderr: &str, code: Option<i32>, timed_out: bo
|
|||||||
match code {
|
match code {
|
||||||
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
|
Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()),
|
||||||
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
|
None => (true, "SSH dropped (miner likely rebooting to stock)".into()),
|
||||||
_ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()),
|
_ if timed_out => (
|
||||||
|
true,
|
||||||
|
"SSH timed out (miner likely rebooting to stock)".into(),
|
||||||
|
),
|
||||||
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
|
Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
|
/// One luxminer :4028 request/response (line-framed, socket closes after reply).
|
||||||
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
|
fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
|
||||||
let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?;
|
let addr: SocketAddr = format!("{ip}:4028")
|
||||||
|
.parse()
|
||||||
|
.map_err(|e| format!("bad addr: {e}"))?;
|
||||||
let t = Duration::from_secs(8);
|
let t = Duration::from_secs(8);
|
||||||
let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?;
|
let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?;
|
||||||
s.set_read_timeout(Some(t)).ok();
|
s.set_read_timeout(Some(t)).ok();
|
||||||
@@ -300,7 +357,9 @@ fn lux_rpc(ip: &str, payload: &str) -> Result<String, String> {
|
|||||||
Err(_) => break,
|
Err(_) => break,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
|
Ok(String::from_utf8_lossy(&buf)
|
||||||
|
.trim_matches('\u{0}')
|
||||||
|
.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The captured result of a timed subprocess run.
|
/// The captured result of a timed subprocess run.
|
||||||
@@ -391,24 +450,45 @@ mod tests {
|
|||||||
// The critical regression guard (round 18 #12): a wrong password or an
|
// The critical regression guard (round 18 #12): a wrong password or an
|
||||||
// unreachable miner writes to stderr, leaves stdout empty, and exits
|
// unreachable miner writes to stderr, leaves stdout empty, and exits
|
||||||
// non-zero -- it must report failure, never "restored".
|
// non-zero -- it must report failure, never "restored".
|
||||||
let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false);
|
let (ok, msg) =
|
||||||
|
classify_braiins("", "Permission denied, please try again.", Some(255), false);
|
||||||
assert!(!ok, "wrong password must not report success");
|
assert!(!ok, "wrong password must not report success");
|
||||||
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
|
assert!(msg.to_lowercase().contains("ssh failed"), "{msg}");
|
||||||
|
|
||||||
let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false);
|
let (ok, _) = classify_braiins(
|
||||||
|
"",
|
||||||
|
"ssh: connect to host 10.0.0.9 port 22: Connection refused",
|
||||||
|
Some(255),
|
||||||
|
false,
|
||||||
|
);
|
||||||
assert!(!ok, "unreachable miner must not report success");
|
assert!(!ok, "unreachable miner must not report success");
|
||||||
|
|
||||||
let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false);
|
let (ok, _) = classify_braiins(
|
||||||
|
"",
|
||||||
|
"ssh: Could not resolve hostname miner: Name or service not known",
|
||||||
|
Some(255),
|
||||||
|
false,
|
||||||
|
);
|
||||||
assert!(!ok, "unresolvable host must not report success");
|
assert!(!ok, "unresolvable host must not report success");
|
||||||
|
|
||||||
// Genuine outcomes.
|
// Genuine outcomes.
|
||||||
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
|
let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false);
|
||||||
assert!(ok, "clean exit 0 is success");
|
assert!(ok, "clean exit 0 is success");
|
||||||
let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false);
|
let (ok, _) = classify_braiins(
|
||||||
|
"",
|
||||||
|
"Connection to 10.0.0.5 closed by remote host.",
|
||||||
|
None,
|
||||||
|
false,
|
||||||
|
);
|
||||||
assert!(ok, "connection dropped mid-command (reboot) is success");
|
assert!(ok, "connection dropped mid-command (reboot) is success");
|
||||||
let (ok, _) = classify_braiins("", "", None, true);
|
let (ok, _) = classify_braiins("", "", None, true);
|
||||||
assert!(ok, "timeout after the command started (reboot) is success");
|
assert!(ok, "timeout after the command started (reboot) is success");
|
||||||
let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false);
|
let (ok, _) = classify_braiins(
|
||||||
|
"bash: uninstall.sh: command not found\n",
|
||||||
|
"",
|
||||||
|
Some(127),
|
||||||
|
false,
|
||||||
|
);
|
||||||
assert!(!ok, "missing uninstall.sh is a failure");
|
assert!(!ok, "missing uninstall.sh is a failure");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -416,7 +496,10 @@ mod tests {
|
|||||||
fn firmware_selects_the_right_flow() {
|
fn firmware_selects_the_right_flow() {
|
||||||
// The dispatcher only recognises the three revertible aftermarket
|
// The dispatcher only recognises the three revertible aftermarket
|
||||||
// families; anything else has no restore path.
|
// families; anything else has no restore path.
|
||||||
let mk = |fw: &str| RestoreTarget { ip: "0.0.0.0".into(), firmware: fw.into() };
|
let mk = |fw: &str| RestoreTarget {
|
||||||
|
ip: "0.0.0.0".into(),
|
||||||
|
firmware: fw.into(),
|
||||||
|
};
|
||||||
// Unknown firmware is rejected cleanly (no network attempt in the branch).
|
// Unknown firmware is rejected cleanly (no network attempt in the branch).
|
||||||
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
|
let (ok, detail) = restore_one(&mk("Stock"), "", "", "");
|
||||||
assert!(!ok);
|
assert!(!ok);
|
||||||
|
|||||||
+790
-452
File diff suppressed because it is too large
Load Diff
+960
-293
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user