Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
086c883c4a | ||
|
|
4324d3046e | ||
|
|
de5c1a5a15 | ||
|
|
d22ee79159 | ||
|
|
3d1fd36811 | ||
|
|
7f2ea8a8dc | ||
|
|
b26f389460 | ||
|
|
b46f15b340 | ||
|
|
c9d32f9793 | ||
|
|
5cf9d44d7e | ||
|
|
d9dc60918c | ||
|
|
bb31a7befc | ||
|
|
b1b7a3dbc0 | ||
|
|
8275f893dd | ||
|
|
36f12d6d4e | ||
|
|
a4d82bf45b | ||
|
|
d925414bc8 | ||
|
|
9f9fe18926 | ||
|
|
d8d044f439 | ||
|
|
517bee9b9e | ||
|
|
10d7fd6d95 | ||
|
|
9b440a46e3 |
@@ -1,35 +0,0 @@
|
||||
name: public-benchmark-pages
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [build-test-release]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-public-benchmark-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install SSH client
|
||||
run: bash ci/ensure-build-deps.sh ssh
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Publish public benchmark page
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
|
||||
run: python3 ci/publish-bench-pages.py toolkit
|
||||
- name: Clean generated page
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -0,0 +1,47 @@
|
||||
name: pages
|
||||
|
||||
# The project site, https://blueflare.gitea.bluefla.re/alkane-toolkit/ :
|
||||
# overview, user manual (docs/manual), code-quality dashboard (from the
|
||||
# quality record main CI publishes with the badges) and benchmark history.
|
||||
# Rebuilt after every main build-test-release run and published to this
|
||||
# repository's gh-pages branch.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [build-test-release]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install page tools
|
||||
run: bash ci/ensure-build-deps.sh pages
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Fetch measured quality record
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/fetch-quality.py quality.json
|
||||
- name: Build site
|
||||
run: |
|
||||
python3 ci/build-pages.py --out site --quality quality.json \
|
||||
--bench bench-site/index.html --sha "$GITHUB_SHA"
|
||||
- name: Publish site
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/publish-pages.py site
|
||||
- name: Clean generated site
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -271,8 +271,10 @@ jobs:
|
||||
set -euo pipefail
|
||||
rustup component add llvm-tools-preview >/dev/null 2>&1 || true
|
||||
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
|
||||
PCT=$(bash ci/coverage.sh --summary-only \
|
||||
| awk '/^TOTAL/{gsub(/%/,"",$10); print $10}')
|
||||
# Keep the whole table: gen-badges turns it into the per-crate and
|
||||
# per-file breakdown on the Pages quality dashboard.
|
||||
bash ci/coverage.sh --summary-only | tee coverage-summary.txt
|
||||
PCT=$(awk '/^TOTAL/{gsub(/%/,"",$10); print $10}' coverage-summary.txt)
|
||||
[ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; }
|
||||
echo "pct=${PCT}" >> "$GITHUB_OUTPUT"
|
||||
echo "line coverage (tests + self-test): ${PCT}%"
|
||||
@@ -300,7 +302,8 @@ jobs:
|
||||
python3 ci/gen-badges.py --tests "$PASS" \
|
||||
--coverage "${{ steps.cov.outputs.pct }}" \
|
||||
--bench-coverage "${{ steps.benchcov.outputs.pct }}" \
|
||||
--bench-delta "$BENCH_DELTA" --clippy clean
|
||||
--bench-delta "$BENCH_DELTA" --clippy clean \
|
||||
--coverage-summary coverage-summary.txt
|
||||
|
||||
- name: Publish measured badges
|
||||
env:
|
||||
|
||||
@@ -159,6 +159,7 @@ jobs:
|
||||
run: |
|
||||
cargo test -p alkane-gui --offline
|
||||
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
|
||||
python3 tools/report-relay/test_relay.py
|
||||
|
||||
- name: Microbenchmarks
|
||||
if: steps.surface.outputs.surface == 'full'
|
||||
|
||||
@@ -2,3 +2,8 @@
|
||||
**/target
|
||||
.claude/
|
||||
__pycache__/
|
||||
# Internal working notes live outside this public repository.
|
||||
/AGENTS.md
|
||||
/HANDOFF.md
|
||||
/CLAUDE.md
|
||||
code-review-report*.md
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Blueflare
|
||||
Copyright (c) 2026 BlueFlare Energy Solutions Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
# Alkane Toolkit
|
||||
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/#coverage)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/)
|
||||
[](LICENSE)
|
||||
|
||||
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.
|
||||
The badges link to the [project site](https://blueflare.gitea.bluefla.re/alkane-toolkit/): the [manual](https://blueflare.gitea.bluefla.re/alkane-toolkit/manual/),
|
||||
the [code-quality dashboard](https://blueflare.gitea.bluefla.re/alkane-toolkit/quality/) (how the grade is set, coverage by
|
||||
crate and file) and the [benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/).
|
||||
|
||||
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
||||
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
|
||||
@@ -31,7 +32,9 @@ uses offline fixtures and does not contact hardware.
|
||||
Windows 10/11 builds are cross-compiled on Linux (`scripts/build-wx-windows.sh`,
|
||||
then `scripts/build-gui-windows.sh`) and attached to every release as a
|
||||
self-contained `alkane-toolkit.exe`; see [docs/windows.md](docs/windows.md).
|
||||
macOS is not built.
|
||||
macOS builds run on a Mac (`scripts/build-wx-macos.sh`, then
|
||||
`scripts/build-gui-macos.sh`) and produce one universal app for Apple Silicon
|
||||
and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md).
|
||||
|
||||
## Current scope
|
||||
|
||||
@@ -42,8 +45,7 @@ macOS is not built.
|
||||
aftermarket firmware to stock.
|
||||
|
||||
Discovery is read-only. Control and restore actions change miners. Check the
|
||||
selected devices before applying them. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md)
|
||||
and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage.
|
||||
selected devices before applying them.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -55,8 +57,8 @@ WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \
|
||||
|
||||
Keep build output off the source share. `main` runs full CI and publishes
|
||||
qualifying releases; `next` builds `-rc` candidates. Badges measure host
|
||||
code, not installation support. See the public
|
||||
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/toolkit/).
|
||||
code, not installation support. See the
|
||||
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-toolkit/bench/).
|
||||
|
||||
## Firmware safety
|
||||
|
||||
|
||||
Executable
+293
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Build the Alkane Toolkit Pages site (served from this repo's gh-pages).
|
||||
|
||||
build-pages.py --out site [--manual docs/manual] [--quality quality.json]
|
||||
[--bench bench-site/index.html] [--sha SHA]
|
||||
|
||||
Pages:
|
||||
/ overview and downloads
|
||||
/manual/ the user manual, one page per docs/manual/NN-name.md chapter
|
||||
/quality/ code-quality dashboard from the measured quality.json that main
|
||||
CI publishes next to the badges (ci/gen-badges.py)
|
||||
/bench/ the measured benchmark history (ci/bench_history.py render)
|
||||
|
||||
Every value taken from CI data is HTML-escaped; the manual is Markdown written
|
||||
in this repository.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import markdown
|
||||
|
||||
REPO = "https://gitea.bluefla.re/blueflare/alkane-toolkit"
|
||||
RELEASES = REPO + "/releases"
|
||||
SECTIONS = (("", "Overview"), ("manual/", "Manual"), ("quality/", "Code quality"),
|
||||
("bench/", "Benchmarks"))
|
||||
|
||||
CSS = """
|
||||
:root { --bg:#ffffff; --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --card:#f6f8fa;
|
||||
--accent:#d9822b; --link:#0969da; --good:#1a7f37; --warn:#9a6700; --bad:#cf222e; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --fg:#e6edf3; --muted:#9198a1;
|
||||
--line:#30363d; --card:#151b23; --link:#4493f8; --good:#3fb950; --warn:#d29922; --bad:#f85149; } }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--fg);
|
||||
font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,sans-serif; }
|
||||
a { color:var(--link); text-decoration:none; } a:hover { text-decoration:underline; }
|
||||
header { border-bottom:1px solid var(--line); }
|
||||
header .bar, main { max-width:1040px; margin:0 auto; padding:0 16px; }
|
||||
header .bar { display:flex; align-items:center; gap:24px; height:56px; flex-wrap:wrap; }
|
||||
header .brand { font-weight:700; color:var(--fg); display:flex; gap:8px; align-items:center; }
|
||||
header .brand i { width:20px; height:20px; border-radius:5px; background:var(--accent); display:inline-block; }
|
||||
header nav { display:flex; gap:18px; flex-wrap:wrap; }
|
||||
header nav a { color:var(--muted); } header nav a.on { color:var(--fg); font-weight:600; }
|
||||
main { padding:28px 16px 64px; }
|
||||
h1 { font-size:1.9rem; margin:.2em 0 .4em; } h2 { margin-top:1.8em; border-bottom:1px solid var(--line); padding-bottom:.25em; }
|
||||
code { background:var(--card); border:1px solid var(--line); border-radius:5px; padding:.1em .35em; font-size:.92em; }
|
||||
pre { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:12px; overflow:auto; }
|
||||
pre code { border:0; padding:0; }
|
||||
table { border-collapse:collapse; width:100%; margin:1em 0; display:block; overflow-x:auto; }
|
||||
th, td { border:1px solid var(--line); padding:6px 10px; text-align:left; vertical-align:top; }
|
||||
th { background:var(--card); }
|
||||
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; margin:1.2em 0; }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px; }
|
||||
.card b { display:block; font-size:1.6rem; } .card span { color:var(--muted); font-size:.9rem; }
|
||||
.good { color:var(--good); } .warn { color:var(--warn); } .bad { color:var(--bad); }
|
||||
.bar-cell { min-width:120px; } .meter { height:8px; background:var(--line); border-radius:4px; overflow:hidden; }
|
||||
.meter i { display:block; height:100%; }
|
||||
.layout { display:grid; grid-template-columns:220px 1fr; gap:32px; }
|
||||
.layout aside ol { padding-left:1.2em; margin:0; } .layout aside li { margin:.3em 0; }
|
||||
.layout aside a.on { font-weight:600; color:var(--fg); }
|
||||
@media (max-width:760px) { .layout { grid-template-columns:1fr; } }
|
||||
.buttons a { display:inline-block; margin:4px 8px 4px 0; padding:8px 14px; border-radius:8px;
|
||||
border:1px solid var(--line); background:var(--card); color:var(--fg); }
|
||||
.buttons a.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
|
||||
footer { color:var(--muted); font-size:.85rem; margin-top:48px; }
|
||||
"""
|
||||
|
||||
|
||||
def page(title: str, body: str, depth: int, current: str, sha: str) -> str:
|
||||
up = "../" * depth
|
||||
nav = "".join(
|
||||
f'<a href="{up}{path}"{" class=on" if path == current else ""}>{label}</a>'
|
||||
for path, label in SECTIONS)
|
||||
built = f"Built from {html.escape(sha[:10])}. " if sha else ""
|
||||
return f"""<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{html.escape(title)} - Alkane Toolkit</title>
|
||||
<link rel="stylesheet" href="{up}style.css"></head>
|
||||
<body><header><div class="bar"><a class="brand" href="{up}"><i></i>Alkane Toolkit</a>
|
||||
<nav>{nav}<a href="{RELEASES}">Downloads</a><a href="{REPO}">Source</a></nav></div></header>
|
||||
<main>{body}
|
||||
<footer>{built}Alkane Toolkit is MIT licensed.</footer></main></body></html>
|
||||
"""
|
||||
|
||||
|
||||
def write(out: Path, rel: str, text: str) -> None:
|
||||
path = out / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
# ---- manual -----------------------------------------------------------------
|
||||
|
||||
def chapters(manual: Path) -> list[tuple[str, str, str]]:
|
||||
"""(slug, title, markdown) for docs/manual/NN-slug.md, in file-name order."""
|
||||
out = []
|
||||
for path in sorted(manual.glob("[0-9][0-9]-*.md")):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
m = re.search(r"^# (.+)$", text, re.M)
|
||||
title = m.group(1).strip() if m else path.stem
|
||||
out.append((path.stem[3:], title, text))
|
||||
return out
|
||||
|
||||
|
||||
def build_manual(out: Path, manual: Path, sha: str) -> None:
|
||||
items = chapters(manual)
|
||||
if not items:
|
||||
raise SystemExit(f"no manual chapters in {manual}")
|
||||
|
||||
def toc(current: str) -> str:
|
||||
links = "".join(
|
||||
f'<li><a href="{slug}.html"{" class=on" if slug == current else ""}>'
|
||||
f"{html.escape(title)}</a></li>" for slug, title, _ in items)
|
||||
return f"<aside><ol>{links}</ol></aside>"
|
||||
|
||||
for slug, title, text in items:
|
||||
# Chapters link to each other as NN-name.md in the repo; on the site
|
||||
# they are name.html.
|
||||
text = re.sub(r"\]\((?:\./)?[0-9][0-9]-([a-z0-9-]+)\.md(#[^)]*)?\)", r"](\1.html\2)", text)
|
||||
body_html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"])
|
||||
write(out, f"manual/{slug}.html",
|
||||
page(title, f'<div class="layout">{toc(slug)}<article>{body_html}</article></div>',
|
||||
1, "manual/", sha))
|
||||
first = items[0][0]
|
||||
listing = "".join(f'<li><a href="{s}.html">{html.escape(t)}</a></li>' for s, t, _ in items)
|
||||
write(out, "manual/index.html",
|
||||
page("Manual", f"<h1>Manual</h1><p>Start with "
|
||||
f'<a href="{first}.html">{html.escape(items[0][1])}</a>.</p><ol>{listing}</ol>',
|
||||
1, "manual/", sha))
|
||||
|
||||
|
||||
# ---- quality dashboard ---------------------------------------------------------
|
||||
|
||||
def pct_class(pct: float | None) -> str:
|
||||
if pct is None:
|
||||
return ""
|
||||
return "good" if pct >= 80 else "warn" if pct >= 40 else "bad"
|
||||
|
||||
|
||||
def meter(pct: float) -> str:
|
||||
colour = {"good": "var(--good)", "warn": "var(--warn)", "bad": "var(--bad)"}[pct_class(pct)]
|
||||
return f'<div class="meter"><i style="width:{max(0.0, min(pct, 100.0)):.1f}%;background:{colour}"></i></div>'
|
||||
|
||||
|
||||
def build_quality(out: Path, quality: dict | None, sha: str) -> None:
|
||||
e = html.escape
|
||||
if not quality:
|
||||
write(out, "quality/index.html", page(
|
||||
"Code quality", "<h1>Code quality</h1><p>No measurement has been published yet; "
|
||||
"the next main build will fill this page.</p>", 1, "quality/", sha))
|
||||
return
|
||||
grade = str(quality.get("grade", "pending"))
|
||||
cov = quality.get("coverage_pct")
|
||||
bench_cov = quality.get("bench_coverage_pct")
|
||||
delta = quality.get("bench_delta_pct")
|
||||
|
||||
def card(value: str, label: str, cls: str = "") -> str:
|
||||
return f'<div class="card"><b class="{cls}">{value}</b><span>{label}</span></div>'
|
||||
|
||||
cards = "".join([
|
||||
card(e(grade), "Quality grade", {"A": "good", "B": "good", "C": "warn"}.get(grade, "bad")),
|
||||
card(e(str(quality.get("tests_passed", "-"))), "Tests passing", "good"),
|
||||
card(f"{cov:.1f}%" if cov is not None else "-", "Line coverage", pct_class(cov)),
|
||||
card(f"{bench_cov:.1f}%" if bench_cov is not None else "-", "Benchmark coverage", pct_class(bench_cov)),
|
||||
card(e(str(quality.get("clippy") or "-")), "Clippy (warnings are errors)",
|
||||
"good" if quality.get("clippy") == "clean" else "bad"),
|
||||
card(e(str(quality.get("rustfmt") or "-")), "rustfmt", "good" if quality.get("rustfmt") == "clean" else ""),
|
||||
card(f"{quality.get('loc', 0):,}", "Lines of Rust"),
|
||||
card(e(str(quality.get("dependencies", "-"))), "Crates in Cargo.lock"),
|
||||
card((f"{'+' if delta > 0 else ''}{delta:.1f}%" if delta is not None else "-"),
|
||||
"Benchmarks vs previous" + (" (same inputs)" if quality.get("bench_same_inputs") else ""),
|
||||
"" if delta is None else "good" if delta >= 2 else "" if delta > -2 else "warn"),
|
||||
])
|
||||
bands = ", ".join(f"{e(str(letter))} at {floor:.0f}% or more"
|
||||
for floor, letter in quality.get("grade_bands", []))
|
||||
grade_rule = (f"<p>The grade is F if Clippy or rustfmt fails on main. Otherwise it is the "
|
||||
f"line-coverage band: {bands}, and F below that. The coverage badge uses the "
|
||||
f"same bands for its colour, so the two never disagree.</p>")
|
||||
|
||||
crates = quality.get("coverage_by_crate", {})
|
||||
loc = quality.get("loc_by_crate", {})
|
||||
rows = []
|
||||
for name in sorted(set(crates) | set(loc)):
|
||||
c = crates.get(name)
|
||||
if c and c["lines"]:
|
||||
pct = 100.0 * (c["lines"] - c["missed"]) / c["lines"]
|
||||
cov_cells = (f'<td class="num {pct_class(pct)}">{pct:.1f}%</td>'
|
||||
f'<td class="bar-cell">{meter(pct)}</td>'
|
||||
f'<td class="num">{c["lines"] - c["missed"]:,} / {c["lines"]:,}</td>')
|
||||
else:
|
||||
cov_cells = '<td class="num">-</td><td></td><td class="num">-</td>'
|
||||
rows.append(f"<tr><td>{e(name)}</td>{cov_cells}<td class='num'>{loc.get(name, 0):,}</td></tr>")
|
||||
crate_table = ("<table><tr><th>Crate</th><th class=num>Line coverage</th><th></th>"
|
||||
"<th class=num>Covered lines</th><th class=num>Lines of Rust</th></tr>"
|
||||
+ "".join(rows) + "</table>")
|
||||
|
||||
files = sorted(quality.get("coverage_by_file", []),
|
||||
key=lambda r: (r["lines"] - r["missed"]) / r["lines"] if r["lines"] else 1)
|
||||
file_rows = "".join(
|
||||
f"<tr><td><code>{e(r['file'])}</code></td>"
|
||||
f"<td class='num {pct_class(100.0 * (r['lines'] - r['missed']) / r['lines'])}'>"
|
||||
f"{100.0 * (r['lines'] - r['missed']) / r['lines']:.1f}%</td>"
|
||||
f"<td class='num'>{r['missed']:,}</td><td class='num'>{r['lines']:,}</td></tr>"
|
||||
for r in files if r["lines"])
|
||||
file_table = ("<table><tr><th>File (least covered first)</th><th class=num>Coverage</th>"
|
||||
"<th class=num>Uncovered lines</th><th class=num>Lines</th></tr>"
|
||||
+ file_rows + "</table>") if file_rows else ""
|
||||
|
||||
measured = str(quality.get("sha", ""))[:10]
|
||||
of_build = f" (this page: <code>{e(measured)}</code>)" if measured else ""
|
||||
body = f"""<h1>Code quality</h1>
|
||||
<p>Measured by main CI on every build{of_build}:
|
||||
unit tests, line coverage (unit tests plus the headless UI self-test), Clippy with
|
||||
warnings as errors, and rustfmt. Windows builds run the same tests under Wine and
|
||||
on real Windows 11.</p>
|
||||
<div class="cards">{cards}</div>
|
||||
<h2 id="grade">How the grade is set</h2>{grade_rule}
|
||||
<h2 id="coverage">Coverage by crate</h2>{crate_table}
|
||||
<h2 id="files">Coverage by file</h2>{file_table}
|
||||
<p>The dependency count is every package in <code>Cargo.lock</code>, direct and
|
||||
transitive. Lines of Rust count every <code>.rs</code> line under <code>crates/</code>,
|
||||
tests included.</p>"""
|
||||
write(out, "quality/index.html", page("Code quality", body, 1, "quality/", sha))
|
||||
|
||||
|
||||
# ---- benchmarks + overview -------------------------------------------------------
|
||||
|
||||
def build_bench(out: Path, bench: Path | None, sha: str) -> None:
|
||||
if bench is None or not bench.is_file():
|
||||
write(out, "bench/index.html", page(
|
||||
"Benchmarks", "<h1>Benchmarks</h1><p>No benchmark history yet.</p>", 1, "bench/", sha))
|
||||
return
|
||||
rendered = bench.read_text(encoding="utf-8")
|
||||
# The history renderer emits a complete document; keep its body (and its
|
||||
# own styles) under the site's header.
|
||||
styles = "".join(re.findall(r"<style[^>]*>.*?</style>", rendered, re.S | re.I))
|
||||
m = re.search(r"<body[^>]*>(.*)</body>", rendered, re.S | re.I)
|
||||
inner = m.group(1) if m else rendered
|
||||
text = page("Benchmarks", inner, 1, "bench/", sha)
|
||||
write(out, "bench/index.html", text.replace("</head>", styles + "</head>", 1))
|
||||
|
||||
|
||||
def build_index(out: Path, quality: dict | None, sha: str) -> None:
|
||||
grade = html.escape(str((quality or {}).get("grade", "pending")))
|
||||
body = f"""<h1>Alkane Toolkit</h1>
|
||||
<p>Desktop discovery and monitoring for ASIC miners on your network: find every
|
||||
miner in your IP ranges, see hashrate, power, temperatures, fans and hashboard
|
||||
health at a glance, and run the controls each firmware supports.</p>
|
||||
<div class="buttons"><a class="primary" href="{RELEASES}">Download for Windows or Linux</a>
|
||||
<a href="manual/">Read the manual</a><a href="quality/">Code quality: {grade}</a>
|
||||
<a href="bench/">Benchmarks</a></div>
|
||||
<h2>Platforms</h2>
|
||||
<ul><li><b>Windows 10 and 11</b> (x86_64): one signed, self-contained <code>alkane-toolkit.exe</code>.</li>
|
||||
<li><b>Linux</b> (x86_64, GTK 3): one binary.</li></ul>
|
||||
<p>Every release is built, tested and signed by CI from the public source.</p>"""
|
||||
write(out, "index.html", page("Overview", body, 0, "", sha))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--manual", default="docs/manual")
|
||||
ap.add_argument("--quality", default=None)
|
||||
ap.add_argument("--bench", default=None)
|
||||
ap.add_argument("--sha", default="")
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out)
|
||||
if out.exists():
|
||||
shutil.rmtree(out)
|
||||
out.mkdir(parents=True)
|
||||
quality = None
|
||||
if args.quality and Path(args.quality).is_file():
|
||||
quality = json.loads(Path(args.quality).read_text())
|
||||
if not isinstance(quality, dict) or quality.get("schema") != 1:
|
||||
raise SystemExit("unsupported quality.json")
|
||||
(out / "style.css").write_text(CSS.strip() + "\n", encoding="utf-8")
|
||||
build_index(out, quality, args.sha)
|
||||
build_manual(out, Path(args.manual), args.sha)
|
||||
build_quality(out, quality, args.sha)
|
||||
build_bench(out, Path(args.bench) if args.bench else None, args.sha)
|
||||
print(f"built {sum(1 for _ in out.rglob('*.html'))} pages in {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -32,12 +32,12 @@ def main() -> int:
|
||||
print(f"{path.name}: {name} has a different runner image", file=sys.stderr)
|
||||
return 1
|
||||
pages = yaml.load(
|
||||
(ROOT / ".gitea/workflows/bench-pages.yml").read_text(),
|
||||
(ROOT / ".gitea/workflows/pages.yml").read_text(),
|
||||
Loader=yaml.BaseLoader,
|
||||
)
|
||||
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
|
||||
or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"):
|
||||
print("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr)
|
||||
print("Pages must follow main CI on the trusted verifier", file=sys.stderr)
|
||||
return 1
|
||||
release = yaml.load(
|
||||
(ROOT / ".gitea/workflows/release.yml").read_text(),
|
||||
@@ -46,7 +46,7 @@ def main() -> int:
|
||||
if release["jobs"]["release"].get("runs-on") != "alkane-ci":
|
||||
print("Main release must use the dedicated Alkane build pool", file=sys.stderr)
|
||||
return 1
|
||||
if any("ci/publish-bench-pages.py" in step.get("run", "")
|
||||
if any("ci/publish-pages.py" in step.get("run", "")
|
||||
for step in release["jobs"]["release"]["steps"]):
|
||||
print("Main release must not publish Pages from GARM", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -9,9 +9,9 @@ import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
|
||||
FILES = ("bench-current.txt",)
|
||||
BADGE_FILES = ("bench-baseline.json", "bench-context.json")
|
||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site", "site")
|
||||
FILES = ("bench-current.txt", "coverage-summary.txt", "quality.json")
|
||||
BADGE_FILES = ("bench-baseline.json", "bench-context.json", "quality.json")
|
||||
|
||||
|
||||
def cleanup() -> None:
|
||||
|
||||
@@ -46,7 +46,7 @@ vendor/*|thirdparty/asic-rs/*)
|
||||
# resources, embedded assets). ui.rs/fixtures.rs/bin
|
||||
# match the UI arm above first, so they still bump Z, not Y.
|
||||
backend=true ;;
|
||||
*) : ;; # docs, HANDOFF, README, thirdparty/wxwidgets tree: no bump
|
||||
*) : ;; # docs, README, thirdparty/wxwidgets tree: no bump
|
||||
esac
|
||||
done <<< "$changed"
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
# Use the preinstalled CI image or install missing packages on older runners.
|
||||
set -euo pipefail
|
||||
|
||||
mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows}"
|
||||
mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows|pages}"
|
||||
case "$mode" in
|
||||
base) packages=(libssl-dev pkg-config ca-certificates) ;;
|
||||
ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;;
|
||||
ssh) packages=(openssh-client) ;;
|
||||
pages) packages=(python3-markdown) ;;
|
||||
all) packages=(libssl-dev pkg-config ca-certificates openssh-client
|
||||
xvfb xauth dbus-x11 fonts-dejavu-core) ;;
|
||||
# Windows cross build (mingw-w64, posix threads) + Wine for its tests.
|
||||
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Download the measured quality record (badges/quality.json on ci-badges).
|
||||
|
||||
fetch-quality.py OUT.json
|
||||
|
||||
Writes nothing (and exits 0) when main CI has not published one yet, so the
|
||||
Pages build shows a "not measured yet" dashboard instead of failing.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def main() -> None:
|
||||
out = Path(sys.argv[1])
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
url = f"{api}/repos/{repo}/contents/badges/quality.json?ref=ci-badges"
|
||||
request = Request(url, headers={"Authorization": f"token {os.environ['GITEA_TOKEN']}"})
|
||||
try:
|
||||
with urlopen(request, timeout=20) as response:
|
||||
content = base64.b64decode(json.load(response)["content"])
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
print("No quality record published yet")
|
||||
return
|
||||
raise
|
||||
if not isinstance(json.loads(content), dict):
|
||||
sys.exit("invalid quality record")
|
||||
out.write_bytes(content)
|
||||
print(f"Fetched quality record ({len(content)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+103
-8
@@ -135,10 +135,72 @@ def cov_color(pct: float) -> str:
|
||||
return "red"
|
||||
|
||||
|
||||
def quality_grade(clippy: str | None) -> str:
|
||||
if clippy is None:
|
||||
# Code-quality grade (shown on the badge and explained on the Pages quality
|
||||
# dashboard). Lint failures fail the grade outright; otherwise the grade is the
|
||||
# measured line-coverage band, using the same bands as the coverage badge
|
||||
# colour, so the two badges can never disagree.
|
||||
GRADE_BANDS = ((80.0, "A"), (60.0, "B"), (40.0, "C"), (20.0, "D"))
|
||||
GRADE_COLORS = {"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||
"D": "orange", "F": "red", "pending": "lightgrey"}
|
||||
|
||||
|
||||
def quality_grade(clippy: str | None, coverage: float | None = None) -> str:
|
||||
if clippy is None or (clippy == "clean" and coverage is None):
|
||||
return "pending"
|
||||
return "A" if clippy == "clean" else "F"
|
||||
if clippy != "clean":
|
||||
return "F"
|
||||
for floor, grade in GRADE_BANDS:
|
||||
if coverage >= floor:
|
||||
return grade
|
||||
return "F"
|
||||
|
||||
|
||||
def coverage_by_file(summary_path: str | None, root: str) -> list[dict]:
|
||||
"""Per-file line coverage from a `cargo llvm-cov --summary-only` table.
|
||||
|
||||
Columns: Filename, Regions, Missed Regions, Cover, Functions, Missed
|
||||
Functions, Executed, Lines, Missed Lines, Cover, ...
|
||||
"""
|
||||
if not summary_path:
|
||||
return []
|
||||
rows = []
|
||||
root_abs = os.path.abspath(root).rstrip("/") + "/"
|
||||
for line in Path(summary_path).read_text(errors="replace").splitlines():
|
||||
cols = line.split()
|
||||
if len(cols) < 10 or cols[0] in ("Filename", "TOTAL") or not cols[0].endswith(".rs"):
|
||||
continue
|
||||
try:
|
||||
lines, missed = int(cols[7]), int(cols[8])
|
||||
except ValueError:
|
||||
continue
|
||||
name = cols[0][len(root_abs):] if cols[0].startswith(root_abs) else cols[0]
|
||||
# llvm-cov drops the prefix every file shares, so when only workspace
|
||||
# crates are measured "crates/alkane-gui/src/x.rs" is printed as
|
||||
# "alkane-gui/src/x.rs". Put the prefix back.
|
||||
first = Path(name).parts[0] if Path(name).parts else ""
|
||||
if not name.startswith("crates/") and (Path(root) / "crates" / first).is_dir():
|
||||
name = f"crates/{name}"
|
||||
rows.append({"file": name, "lines": lines, "missed": missed})
|
||||
return rows
|
||||
|
||||
|
||||
def crate_of(path: str) -> str:
|
||||
parts = Path(path).parts
|
||||
if "crates" in parts and parts.index("crates") + 1 < len(parts):
|
||||
return parts[parts.index("crates") + 1]
|
||||
if "wx-rs-0.2.0-patched" in parts:
|
||||
return "wx-rs (bridge)"
|
||||
return "other"
|
||||
|
||||
|
||||
def loc_by_crate(root: str) -> dict[str, int]:
|
||||
out: dict[str, int] = {}
|
||||
crates = Path(root) / "crates"
|
||||
for path in sorted(crates.glob("*/**/*.rs")):
|
||||
crate = path.relative_to(crates).parts[0]
|
||||
with open(path, encoding="utf-8", errors="ignore") as fh:
|
||||
out[crate] = out.get(crate, 0) + sum(1 for _ in fh)
|
||||
return out
|
||||
|
||||
|
||||
def human(n: int) -> str:
|
||||
@@ -169,6 +231,9 @@ def main() -> int:
|
||||
# percentage string, or "NEW" when there is no baseline.
|
||||
ap.add_argument("--bench-delta", default=None)
|
||||
ap.add_argument("--clippy", choices=("clean", "failed"))
|
||||
# The full `cargo llvm-cov --summary-only` table, for the per-crate and
|
||||
# per-file breakdown in quality.json (the Pages quality dashboard).
|
||||
ap.add_argument("--coverage-summary", default=None)
|
||||
args = ap.parse_args()
|
||||
for value in (args.coverage, args.bench_coverage):
|
||||
if value is not None and (not math.isfinite(value) or not 0 <= value <= 100):
|
||||
@@ -189,11 +254,9 @@ def main() -> int:
|
||||
write("loc", "lines of code", human(loc), loc_color(loc))
|
||||
write("license", "license", lic, "blue")
|
||||
write("dependencies", "dependencies", str(deps), "blue")
|
||||
grade = quality_grade(args.clippy)
|
||||
write("quality", "code quality", grade,
|
||||
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
|
||||
"D": "orange", "F": "red", "pending": "lightgrey"}[grade],
|
||||
f"code quality: {grade} (GUI Clippy and first-party rustfmt)")
|
||||
grade = quality_grade(args.clippy, args.coverage)
|
||||
write("quality", "code quality", grade, GRADE_COLORS[grade],
|
||||
f"code quality: {grade} (Clippy, rustfmt and line coverage)")
|
||||
if args.tests is not None:
|
||||
write("tests", "tests", f"{args.tests} passing", "brightgreen")
|
||||
if args.coverage is not None:
|
||||
@@ -228,6 +291,38 @@ def main() -> int:
|
||||
write("bench", "bench", "baseline set", "blue")
|
||||
elif args.bench is not None:
|
||||
write("bench", "bench", args.bench, "blue")
|
||||
|
||||
# Everything above, plus the per-crate breakdowns, for the Pages quality
|
||||
# dashboard (ci/build-pages.py).
|
||||
files = coverage_by_file(args.coverage_summary, args.root)
|
||||
crates: dict[str, dict] = {}
|
||||
for row in files:
|
||||
c = crates.setdefault(crate_of(row["file"]), {"lines": 0, "missed": 0})
|
||||
c["lines"] += row["lines"]
|
||||
c["missed"] += row["missed"]
|
||||
quality = {
|
||||
"schema": 1,
|
||||
"sha": os.environ.get("GITHUB_SHA", ""),
|
||||
"grade": grade,
|
||||
"grade_bands": [[floor, letter] for floor, letter in GRADE_BANDS],
|
||||
"clippy": args.clippy,
|
||||
"rustfmt": "clean" if args.clippy is not None else None,
|
||||
"tests_passed": args.tests,
|
||||
"coverage_pct": args.coverage,
|
||||
"bench_coverage_pct": args.bench_coverage,
|
||||
"bench_delta_pct": delta,
|
||||
"bench_same_inputs": same_inputs,
|
||||
"loc": loc,
|
||||
"loc_by_crate": loc_by_crate(args.root),
|
||||
"dependencies": deps,
|
||||
"license": lic,
|
||||
"coverage_by_crate": crates,
|
||||
"coverage_by_file": files,
|
||||
}
|
||||
path = os.path.join(args.root, args.out, "quality.json")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(quality, fh, indent=1, sort_keys=True)
|
||||
print(f"wrote {path}")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Package the universal macOS build as an app bundle, for release.
|
||||
|
||||
package-macos.py VERSION BINARY OUT_DIR
|
||||
|
||||
BINARY is the universal (arm64 + x86_64) alkane-toolkit executable made by
|
||||
scripts/build-gui-macos.sh. Writes
|
||||
dist/alkane-toolkit-vVERSION-macos-universal.zip holding "Alkane Toolkit.app",
|
||||
LICENSE and README.txt, and prints its path. Runs on macOS (lipo, codesign,
|
||||
ditto).
|
||||
|
||||
The bundle is ad-hoc signed only (Apple Silicon refuses to run unsigned
|
||||
code); it is not signed with a Developer ID or notarized, so Gatekeeper asks
|
||||
the user to confirm the first launch. README.txt says how.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
APP = "Alkane Toolkit.app"
|
||||
BUNDLE_ID = "re.bluefla.alkane-toolkit"
|
||||
MIN_MACOS = "11.0"
|
||||
|
||||
|
||||
def run(*args: str) -> str:
|
||||
return subprocess.run(args, check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def build_app(version: str, binary: pathlib.Path, dest: pathlib.Path) -> pathlib.Path:
|
||||
archs = run("lipo", "-archs", str(binary)).split()
|
||||
if sorted(archs) != ["arm64", "x86_64"]:
|
||||
sys.exit(f"{binary} is not a universal arm64 + x86_64 binary: {archs}")
|
||||
app = dest / APP
|
||||
macos = app / "Contents" / "MacOS"
|
||||
resources = app / "Contents" / "Resources"
|
||||
macos.mkdir(parents=True)
|
||||
resources.mkdir()
|
||||
shutil.copy2(binary, macos / "alkane-toolkit")
|
||||
shutil.copy2(ROOT / "crates/alkane-gui/macos/alkane-toolkit.icns", resources)
|
||||
info = {
|
||||
"CFBundleName": "Alkane Toolkit",
|
||||
"CFBundleDisplayName": "Alkane Toolkit",
|
||||
"CFBundleIdentifier": BUNDLE_ID,
|
||||
"CFBundleExecutable": "alkane-toolkit",
|
||||
"CFBundleIconFile": "alkane-toolkit",
|
||||
"CFBundlePackageType": "APPL",
|
||||
"CFBundleShortVersionString": version,
|
||||
"CFBundleVersion": version,
|
||||
"CFBundleInfoDictionaryVersion": "6.0",
|
||||
"LSMinimumSystemVersion": MIN_MACOS,
|
||||
"NSHighResolutionCapable": True,
|
||||
"NSPrincipalClass": "NSApplication",
|
||||
# The scanner talks to miners on the local network.
|
||||
"NSLocalNetworkUsageDescription":
|
||||
"Alkane Toolkit scans your local network to find and manage miners.",
|
||||
"NSHumanReadableCopyright":
|
||||
"Copyright (c) 2026 BlueFlare Energy Solutions Inc. (MIT License)",
|
||||
}
|
||||
with open(app / "Contents" / "Info.plist", "wb") as fh:
|
||||
plistlib.dump(info, fh)
|
||||
(app / "Contents" / "PkgInfo").write_text("APPL????")
|
||||
# Ad-hoc signature over the whole bundle (the linker's per-slice
|
||||
# signatures do not cover Info.plist or the resources).
|
||||
run("codesign", "--force", "--sign", "-", "--timestamp=none", str(app))
|
||||
run("codesign", "--verify", "--strict", str(app))
|
||||
return app
|
||||
|
||||
|
||||
def release(version: str, binary: str, out_dir: str) -> None:
|
||||
name = f"alkane-toolkit-v{version}-macos-universal"
|
||||
out = pathlib.Path(out_dir).resolve() / f"{name}.zip"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
readme = (
|
||||
f"alkane-toolkit v{version} (macOS, Apple Silicon and Intel)\n"
|
||||
"\n"
|
||||
f"Runs on macOS {MIN_MACOS} (Big Sur) or later. Drag \"Alkane Toolkit\"\n"
|
||||
"to Applications, then open it.\n"
|
||||
"\n"
|
||||
"The app is not notarized by Apple, so the first launch is blocked\n"
|
||||
"with a warning. To allow it once:\n"
|
||||
" - macOS 15 or later: try to open it, then System Settings >\n"
|
||||
" Privacy & Security > \"Open Anyway\" for Alkane Toolkit.\n"
|
||||
" - macOS 11 to 14: Control-click the app, choose Open, then Open.\n"
|
||||
"Or, in Terminal: xattr -dr com.apple.quarantine \"/Applications/Alkane Toolkit.app\"\n"
|
||||
"\n"
|
||||
"Settings are stored in ~/.config/alkane-toolkit/.\n"
|
||||
"Manual: https://blueflare.gitea.bluefla.re/alkane-toolkit/manual/\n"
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-macos-") as tmp:
|
||||
folder = pathlib.Path(tmp) / name
|
||||
folder.mkdir()
|
||||
build_app(version, pathlib.Path(binary), folder)
|
||||
shutil.copy2(ROOT / "LICENSE", folder / "LICENSE")
|
||||
(folder / "README.txt").write_text(readme)
|
||||
out.unlink(missing_ok=True)
|
||||
run("ditto", "-c", "-k", "--keepParent", str(folder), str(out))
|
||||
print(out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 4:
|
||||
sys.exit(__doc__)
|
||||
release(*sys.argv[1:])
|
||||
@@ -38,7 +38,7 @@ def release(version: str, exe: str, out_dir: str) -> None:
|
||||
"the executable is self-contained and runs on Windows 10 and 11.\r\n"
|
||||
"\r\n"
|
||||
+ (
|
||||
"The executable is signed by Blueflare (Azure Artifact Signing). To check:\r\n"
|
||||
"The executable is signed by BlueFlare Energy Solutions Inc. (Azure Artifact Signing). To check:\r\n"
|
||||
"right-click alkane-toolkit.exe > Properties > Digital Signatures.\r\n"
|
||||
if signed else
|
||||
"This build is not code-signed, so Windows SmartScreen may warn on first\r\n"
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish a measured benchmark page to the public, data-only Pages repo."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
|
||||
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
|
||||
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
|
||||
PAGES_HOST = "gitea.bluefla.re"
|
||||
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
|
||||
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
|
||||
|
||||
|
||||
def run(*args: str, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=True)
|
||||
|
||||
|
||||
def current_main_sha() -> str:
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
branch = json.load(response)
|
||||
return branch["commit"]["id"]
|
||||
|
||||
|
||||
def publish(site: str) -> None:
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
raise ValueError("benchmark Pages publication requires main")
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
page = Path("bench-site/index.html").read_bytes()
|
||||
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
|
||||
raise ValueError("invalid benchmark page")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
temporary = Path(directory)
|
||||
guard_checkout = temporary / "guard"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
|
||||
GUARD_REPO, str(guard_checkout))
|
||||
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
|
||||
cwd=guard_checkout).stdout
|
||||
guard_script = temporary / "validate_site.py"
|
||||
guard_script.write_text(guard_source)
|
||||
run("python3", str(guard_script), "--page", site,
|
||||
str(Path("bench-site/index.html").resolve()))
|
||||
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
|
||||
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
|
||||
raise ValueError("missing benchmark Pages deploy key")
|
||||
key_path = temporary / "deploy_key"
|
||||
key_path.write_text(key.rstrip("\n") + "\n")
|
||||
key_path.chmod(0o600)
|
||||
known_hosts = temporary / "known_hosts"
|
||||
known_hosts.write_text(PAGES_HOST_KEY + "\n")
|
||||
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
|
||||
if fingerprint != PAGES_HOST_FINGERPRINT:
|
||||
raise ValueError("benchmark Pages SSH host key changed")
|
||||
git_env = os.environ.copy()
|
||||
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
|
||||
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
|
||||
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
|
||||
git_env["GIT_SSH_COMMAND"] = ssh_command
|
||||
git_env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
checkout = temporary / "site"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
|
||||
PAGES_REPO, str(checkout), env=git_env)
|
||||
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
|
||||
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
|
||||
for attempt in range(3):
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
|
||||
cwd=checkout)
|
||||
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
|
||||
cwd=checkout)
|
||||
destination = checkout / site / "index.html"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
destination.write_bytes(page)
|
||||
run("git", "add", f"{site}/index.html", cwd=checkout)
|
||||
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
|
||||
cwd=checkout, check=False)
|
||||
if changed.returncode == 0:
|
||||
print(f"{site} benchmark page is already current")
|
||||
return
|
||||
if changed.returncode != 1:
|
||||
raise RuntimeError("cannot compare benchmark page")
|
||||
run("git", "commit", "-q", "-m",
|
||||
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
|
||||
pushed = subprocess.run(("git", "push", "--quiet", "origin",
|
||||
"HEAD:gh-pages"), env=git_env, cwd=checkout,
|
||||
text=True, capture_output=True, check=False)
|
||||
if pushed.returncode == 0:
|
||||
print(f"Published {site} benchmark page for {sha[:10]}")
|
||||
return
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
|
||||
raise RuntimeError("benchmark Pages publication did not complete")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
|
||||
publish(parser.parse_args().site)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish measured toolkit badges to the private Gitea badge branch."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
@@ -22,7 +23,14 @@ def main() -> None:
|
||||
raise ValueError(f"invalid {name} SVG")
|
||||
publish_file(api, repo, f"badges/{name}.svg", data, token,
|
||||
f"Update measured {name} badge")
|
||||
print(f"Published {len(NAMES)} measured badge SVGs")
|
||||
# The full measurement record behind the badges, read by the Pages
|
||||
# quality dashboard (ci/build-pages.py).
|
||||
data = (ROOT / "badges" / "quality.json").read_bytes()
|
||||
if not isinstance(json.loads(data), dict):
|
||||
raise ValueError("invalid quality.json")
|
||||
publish_file(api, repo, "badges/quality.json", data, token,
|
||||
"Update measured quality record", max_bytes=262_144)
|
||||
print(f"Published {len(NAMES)} measured badge SVGs and quality.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish the built Pages site to this repository's gh-pages branch.
|
||||
|
||||
publish-pages.py SITE_DIR
|
||||
|
||||
Served at https://blueflare.gitea.bluefla.re/alkane-toolkit/ by the Pages
|
||||
server, which serves the gh-pages branch of public repositories. Each publish
|
||||
is one orphan commit (force-pushed), so the branch never accumulates history.
|
||||
Only main may publish, and a run for a superseded main commit skips.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BRANCH = "gh-pages"
|
||||
MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
|
||||
def current_main_sha(api: str, repo: str, token: str) -> str:
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
return json.load(response)["commit"]["id"]
|
||||
|
||||
|
||||
def git(*args: str, cwd: Path, env: dict | None = None) -> None:
|
||||
subprocess.run(("git", *args), cwd=cwd, env=env, check=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit(__doc__)
|
||||
site = Path(sys.argv[1])
|
||||
if not (site / "index.html").is_file():
|
||||
sys.exit(f"{site} has no index.html")
|
||||
size = sum(p.stat().st_size for p in site.rglob("*") if p.is_file())
|
||||
if size > MAX_BYTES:
|
||||
sys.exit(f"site is {size} bytes, over the {MAX_BYTES} byte limit")
|
||||
for path in site.rglob("*"):
|
||||
if path.is_file() and path.suffix not in {".html", ".css", ".svg", ".png", ".json"}:
|
||||
sys.exit(f"unexpected file type on the site: {path}")
|
||||
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
sys.exit("Pages publication requires main")
|
||||
if current_main_sha(api, repo, token) != sha:
|
||||
print("Skipping Pages for a superseded main commit")
|
||||
return
|
||||
|
||||
server = api.removesuffix("/api/v1")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
work = Path(directory)
|
||||
shutil.copytree(site, work, dirs_exist_ok=True)
|
||||
env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
|
||||
git("init", "-q", "-b", BRANCH, cwd=work)
|
||||
git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re",
|
||||
"add", "-A", cwd=work)
|
||||
git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re",
|
||||
"commit", "-q", "-m", f"Publish site for {sha[:10]} [skip ci]", cwd=work)
|
||||
# The token is read from the environment by the credential helper at
|
||||
# push time; it never appears on a command line or in the remote URL.
|
||||
helper = '!f() { echo username=alkane-ci; echo "password=$GITEA_TOKEN"; }; f'
|
||||
git("-c", f"credential.helper={helper}", "push", "-q", "--force",
|
||||
f"{server}/{repo}.git", f"HEAD:refs/heads/{BRANCH}", cwd=work, env=env)
|
||||
print(f"Published Pages for {sha[:10]} to {BRANCH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+41
-10
@@ -5,6 +5,7 @@
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@@ -50,16 +51,46 @@ class BenchBadgeTests(unittest.TestCase):
|
||||
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
|
||||
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)
|
||||
def test_quality_grade_follows_lint_and_coverage(self):
|
||||
# A lint failure fails the grade; otherwise it is the coverage band,
|
||||
# with the same floors as the coverage badge colour.
|
||||
self.assertEqual(gen_badges.quality_grade("failed", 95.0), "F")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 85.0), "A")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 65.6), "B")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 48.0), "C")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 25.0), "D")
|
||||
self.assertEqual(gen_badges.quality_grade("clean", 5.0), "F")
|
||||
self.assertEqual(gen_badges.quality_grade("clean"), "pending")
|
||||
self.assertEqual(gen_badges.quality_grade(None, 90.0), "pending")
|
||||
for pct in (85.0, 65.6, 48.0, 25.0):
|
||||
grade = gen_badges.quality_grade("clean", pct)
|
||||
self.assertEqual(gen_badges.GRADE_COLORS[grade], gen_badges.cov_color(pct))
|
||||
|
||||
def test_coverage_table_is_split_by_crate(self):
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory:
|
||||
summary = Path(directory) / "summary.txt"
|
||||
summary.write_text(
|
||||
"Filename Regions Missed Regions Cover Functions Missed Functions "
|
||||
"Executed Lines Missed Lines Cover\n"
|
||||
"crates/alkane-gui/src/ui.rs 10 5 50.00% 4 2 50.00% 100 60 40.00%\n"
|
||||
"crates/alkane-core/src/platform.rs 4 0 100.00% 2 0 100.00% 50 5 90.00%\n"
|
||||
"TOTAL 14 5 64.29% 6 2 66.67% 150 65 56.67%\n")
|
||||
rows = gen_badges.coverage_by_file(str(summary), directory)
|
||||
self.assertEqual([r["file"] for r in rows],
|
||||
["crates/alkane-gui/src/ui.rs", "crates/alkane-core/src/platform.rs"])
|
||||
self.assertEqual(rows[0]["missed"], 60)
|
||||
self.assertEqual(gen_badges.crate_of(rows[1]["file"]), "alkane-core")
|
||||
|
||||
def test_coverage_table_restores_the_stripped_crates_prefix(self):
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory:
|
||||
(Path(directory) / "crates" / "alkane-cli").mkdir(parents=True)
|
||||
summary = Path(directory) / "summary.txt"
|
||||
summary.write_text(
|
||||
"alkane-cli/src/main.rs 4 4 0.00% 1 1 0.00% 23 23 0.00%\n")
|
||||
rows = gen_badges.coverage_by_file(str(summary), directory)
|
||||
self.assertEqual(rows[0], {"file": "crates/alkane-cli/src/main.rs",
|
||||
"lines": 23, "missed": 23})
|
||||
self.assertEqual(gen_badges.crate_of(rows[0]["file"]), "alkane-cli")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Binary file not shown.
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# Regenerate alkane-toolkit.icns (the macOS app icon) from the in-repo
|
||||
# microchip glyph: the same white chip on a rounded amber tile as the Windows
|
||||
# icon, at the sizes macOS asks for (16-1024 px). Needs rsvg-convert,
|
||||
# ImageMagick and python3; the .icns is committed, so a build never runs this.
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
GLYPH=../assets/icons/microchip-solid-full.svg
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' 0
|
||||
sed 's/currentColor/#ffffff/g; s/<svg /<svg fill="#ffffff" /' "$GLYPH" > "$TMP/glyph.svg"
|
||||
for s in 16 32 64 128 256 512 1024; do
|
||||
# Apple's grid: the tile fills ~80% of the canvas, centred.
|
||||
t=$((s * 80 / 100)); m=$(((s - t) / 2)); r=$((t * 22 / 100))
|
||||
g=$((t * 60 / 100)); o=$(((s - g) / 2))
|
||||
rsvg-convert -w "$g" -h "$g" "$TMP/glyph.svg" -o "$TMP/g$s.png"
|
||||
convert -size "${s}x${s}" xc:none -fill '#d9822b' \
|
||||
-draw "roundrectangle $m,$m $((m + t - 1)),$((m + t - 1)) $r,$r" \
|
||||
"$TMP/g$s.png" -geometry "+$o+$o" -composite "PNG32:$TMP/i$s.png"
|
||||
done
|
||||
python3 - "$TMP" alkane-toolkit.icns <<'PY'
|
||||
import pathlib, struct, sys
|
||||
tmp, out = pathlib.Path(sys.argv[1]), sys.argv[2]
|
||||
# ICNS element types that hold PNG data, by pixel size.
|
||||
types = [("icp4", 16), ("icp5", 32), ("icp6", 64), ("ic07", 128), ("ic08", 256),
|
||||
("ic09", 512), ("ic10", 1024), ("ic11", 32), ("ic12", 64), ("ic13", 256),
|
||||
("ic14", 512)]
|
||||
body = b""
|
||||
for kind, size in types:
|
||||
data = (tmp / f"i{size}.png").read_bytes()
|
||||
body += kind.encode() + struct.pack(">I", len(data) + 8) + data
|
||||
pathlib.Path(out).write_bytes(b"icns" + struct.pack(">I", len(body) + 8) + body)
|
||||
PY
|
||||
echo "wrote $(pwd)/alkane-toolkit.icns"
|
||||
@@ -0,0 +1,437 @@
|
||||
//! Bug reports and feature requests from the toolbar's Bug report button.
|
||||
//!
|
||||
//! The app posts the report to the report relay (see tools/report-relay),
|
||||
//! which holds the Gitea token and files the issue in blueflare/alkane-toolkit.
|
||||
//! The app itself holds no secret. A report carries its type, the user's text,
|
||||
//! what the app knows about itself (version, OS, appearance, language, window
|
||||
//! size) and, if the user leaves it ticked, the recent activity log with
|
||||
//! credentials scrubbed. Nothing is stored locally.
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
use std::sync::mpsc::{channel, Receiver};
|
||||
|
||||
/// Where reports go. `ALKANE_REPORT_URL` overrides it (tests, staging).
|
||||
pub const DEFAULT_URL: &str = "https://gitea.bluefla.re/alkane-report/v1/report";
|
||||
/// Longest report text the relay accepts.
|
||||
pub const MAX_TEXT_CHARS: usize = 8000;
|
||||
/// Log sent with a report: at most this many of the newest lines...
|
||||
const LOG_LINES: usize = 80;
|
||||
/// ...cut to this many bytes on a line boundary.
|
||||
const LOG_BYTES: usize = 16 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Bug,
|
||||
Ui,
|
||||
Feature,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// In the order the dialog's type choice lists them.
|
||||
pub const ALL: [Kind; 3] = [Kind::Bug, Kind::Ui, Kind::Feature];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Bug => "Bug",
|
||||
Kind::Ui => "UI change",
|
||||
Kind::Feature => "Feature request",
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire value, which is also the issue label.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Bug => "bug",
|
||||
Kind::Ui => "ui",
|
||||
Kind::Feature => "feature",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app knows about itself, sent with every report.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Context {
|
||||
pub app_version: String,
|
||||
pub platform: String,
|
||||
pub os: String,
|
||||
pub appearance: String,
|
||||
pub language: String,
|
||||
pub window: String,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
/// The running app's context. `window` is the main window's size.
|
||||
pub fn current(dark: bool, language: &str, window: (i32, i32)) -> Context {
|
||||
Context {
|
||||
app_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
|
||||
os: os_version(),
|
||||
appearance: if dark { "dark" } else { "light" }.to_string(),
|
||||
language: language.to_string(),
|
||||
window: format!("{}x{}", window.0, window.1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A human-readable OS name and version, best effort.
|
||||
fn os_version() -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if let Ok(s) = std::fs::read_to_string("/etc/os-release") {
|
||||
for line in s.lines() {
|
||||
if let Some(v) = line.strip_prefix("PRETTY_NAME=") {
|
||||
return v.trim_matches('"').to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
"Linux".to_string()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let out = alkane_core::platform::quiet_command("sw_vers")
|
||||
.arg("-productVersion")
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
format!("macOS {}", String::from_utf8_lossy(&o.stdout).trim())
|
||||
}
|
||||
_ => "macOS".to_string(),
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let out = alkane_core::platform::quiet_command("cmd")
|
||||
.args(["/C", "ver"])
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
let v = String::from_utf8_lossy(&o.stdout).trim().to_string();
|
||||
if v.is_empty() {
|
||||
"Windows".to_string()
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
_ => "Windows".to_string(),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
|
||||
{
|
||||
std::env::consts::OS.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Names whose values are secrets: `name=value`, `name: value` and
|
||||
/// `"name": "value"` have the value replaced.
|
||||
const SECRET_NAMES: [&str; 12] = [
|
||||
"password",
|
||||
"passwd",
|
||||
"pass",
|
||||
"pwd",
|
||||
"secret",
|
||||
"token",
|
||||
"apikey",
|
||||
"api_key",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"psk",
|
||||
"credential",
|
||||
];
|
||||
|
||||
/// Remove credentials from log text before it leaves the machine: values of
|
||||
/// secret-looking names, `user:password@` in URLs, and PEM private keys.
|
||||
/// What is removed becomes `[redacted]`.
|
||||
pub fn scrub(text: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
let mut in_pem = false;
|
||||
for line in text.lines() {
|
||||
if line.contains("-----BEGIN") && line.contains("PRIVATE KEY") {
|
||||
in_pem = true;
|
||||
out.push("[redacted]".to_string());
|
||||
continue;
|
||||
}
|
||||
if in_pem {
|
||||
if line.contains("-----END") {
|
||||
in_pem = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(scrub_line(line));
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
fn scrub_line(line: &str) -> String {
|
||||
let mut s = scrub_url_userinfo(line);
|
||||
let lower = s.to_ascii_lowercase();
|
||||
// Walk every occurrence of every secret name; redact the value after the
|
||||
// next `=` or `:` (quotes and spaces skipped) up to whitespace, a quote, a
|
||||
// comma, `&` or `;`.
|
||||
let mut cuts: Vec<(usize, usize)> = Vec::new();
|
||||
for name in SECRET_NAMES {
|
||||
let mut from = 0;
|
||||
while let Some(pos) = lower[from..].find(name) {
|
||||
let start = from + pos;
|
||||
from = start + name.len();
|
||||
let bytes = s.as_bytes();
|
||||
let mut i = start + name.len();
|
||||
// allow a closing quote and spaces between the name and the separator
|
||||
while i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'' || bytes[i] == b' ') {
|
||||
i += 1;
|
||||
}
|
||||
if i >= bytes.len() || (bytes[i] != b'=' && bytes[i] != b':') {
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'"' || bytes[i] == b'\'') {
|
||||
i += 1;
|
||||
}
|
||||
let vstart = i;
|
||||
if name == "authorization" || name == "cookie" {
|
||||
// "Authorization: Bearer <token>", "Cookie: a=b; c=d": the whole
|
||||
// rest of the line is the secret.
|
||||
i = bytes.len();
|
||||
}
|
||||
while i < bytes.len()
|
||||
&& !matches!(bytes[i], b' ' | b'"' | b'\'' | b',' | b'&' | b';' | b'\t')
|
||||
{
|
||||
i += 1;
|
||||
}
|
||||
if i > vstart {
|
||||
cuts.push((vstart, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
if cuts.is_empty() {
|
||||
return s;
|
||||
}
|
||||
cuts.sort();
|
||||
let mut merged: Vec<(usize, usize)> = Vec::new();
|
||||
for (a, b) in cuts {
|
||||
match merged.last_mut() {
|
||||
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
||||
_ => merged.push((a, b)),
|
||||
}
|
||||
}
|
||||
for (a, b) in merged.into_iter().rev() {
|
||||
if s.is_char_boundary(a) && s.is_char_boundary(b) {
|
||||
s.replace_range(a..b, "[redacted]");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `scheme://user:password@host` -> `scheme://user:[redacted]@host`.
|
||||
fn scrub_url_userinfo(line: &str) -> String {
|
||||
let mut s = line.to_string();
|
||||
let mut from = 0;
|
||||
while let Some(p) = s[from..].find("://") {
|
||||
let auth_start = from + p + 3;
|
||||
let rest = &s[auth_start..];
|
||||
let end = rest
|
||||
.find(|c: char| c == '/' || c.is_whitespace())
|
||||
.unwrap_or(rest.len());
|
||||
let authority = &rest[..end];
|
||||
if let Some(at) = authority.rfind('@') {
|
||||
if let Some(colon) = authority[..at].find(':') {
|
||||
let a = auth_start + colon + 1;
|
||||
let b = auth_start + at;
|
||||
s.replace_range(a..b, "[redacted]");
|
||||
}
|
||||
}
|
||||
from = auth_start;
|
||||
if from >= s.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The newest activity-log lines, scrubbed and cut to the size limits.
|
||||
pub fn recent_log(full_log: &str) -> String {
|
||||
let lines: Vec<&str> = full_log.lines().collect();
|
||||
let tail = &lines[lines.len().saturating_sub(LOG_LINES)..];
|
||||
let mut text = scrub(&tail.join("\n"));
|
||||
if text.len() > LOG_BYTES {
|
||||
let mut cut = text.len() - LOG_BYTES;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut += 1;
|
||||
}
|
||||
text = text[cut..].to_string();
|
||||
if let Some(nl) = text.find('\n') {
|
||||
text = text[nl + 1..].to_string();
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The JSON body the relay takes.
|
||||
pub fn payload(kind: Kind, text: &str, ctx: &Context, log: Option<&str>) -> String {
|
||||
serde_json::json!({
|
||||
"kind": kind.as_str(),
|
||||
"text": text,
|
||||
"app_version": ctx.app_version,
|
||||
"platform": ctx.platform,
|
||||
"os": ctx.os,
|
||||
"appearance": ctx.appearance,
|
||||
"language": ctx.language,
|
||||
"window": ctx.window,
|
||||
"log": log.unwrap_or(""),
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// A filed issue: its number and web link.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Filed {
|
||||
pub number: u64,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Read the relay's answer: curl's body, then the HTTP status on the last line.
|
||||
pub fn parse_response(curl_stdout: &str) -> Result<Filed, String> {
|
||||
let trimmed = curl_stdout.trim_end();
|
||||
let (body, code) = match trimmed.rfind('\n') {
|
||||
Some(i) => (&trimmed[..i], trimmed[i + 1..].trim()),
|
||||
None => ("", trimmed),
|
||||
};
|
||||
let json: Option<serde_json::Value> = serde_json::from_str(body).ok();
|
||||
if code == "201" || code == "200" {
|
||||
let number = json.as_ref().and_then(|j| j["number"].as_u64());
|
||||
let url = json.as_ref().and_then(|j| j["url"].as_str()).unwrap_or("");
|
||||
return match number {
|
||||
Some(number) => Ok(Filed {
|
||||
number,
|
||||
url: url.to_string(),
|
||||
}),
|
||||
None => Err("the report service answered without an issue number; \
|
||||
check the issue list before sending again"
|
||||
.into()),
|
||||
};
|
||||
}
|
||||
let reason = json
|
||||
.as_ref()
|
||||
.and_then(|j| j["error"].as_str())
|
||||
.map(str::to_string);
|
||||
Err(match (code, reason) {
|
||||
(_, Some(r)) => r,
|
||||
("000", None) | ("", None) => "could not reach the report service".into(),
|
||||
(c, None) => format!("the report service answered HTTP {c}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Send a report on a worker thread; the receiver gets one result.
|
||||
pub fn send(body: String) -> Receiver<Result<Filed, String>> {
|
||||
let url = std::env::var("ALKANE_REPORT_URL").unwrap_or_else(|_| DEFAULT_URL.to_string());
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
let result = (|| {
|
||||
let mut child = alkane_core::platform::quiet_command("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"--max-time",
|
||||
"40",
|
||||
"-X",
|
||||
"POST",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"--data-binary",
|
||||
"@-",
|
||||
"-w",
|
||||
"\n%{http_code}",
|
||||
&url,
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("could not run curl: {e}"))?;
|
||||
if let Some(mut si) = child.stdin.take() {
|
||||
let _ = si.write_all(body.as_bytes());
|
||||
}
|
||||
let out = child
|
||||
.wait_with_output()
|
||||
.map_err(|e| format!("curl failed: {e}"))?;
|
||||
parse_response(&String::from_utf8_lossy(&out.stdout))
|
||||
})();
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scrub_removes_credentials_and_keeps_the_rest() {
|
||||
let log = "12:00:01 set pools on 192.168.1.20: url=stratum+tcp://u:hunter2@pool:3333 password=hunter2\n\
|
||||
12:00:02 login {\"user\": \"root\", \"pass\": \"s3cret\"}\n\
|
||||
12:00:03 Authorization: Bearer abc.def\n\
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----\n\
|
||||
12:00:04 scan finished: 9 miners";
|
||||
let s = scrub(log);
|
||||
assert!(!s.contains("hunter2"), "{s}");
|
||||
assert!(!s.contains("s3cret"), "{s}");
|
||||
assert!(!s.contains("abc.def"), "{s}");
|
||||
assert!(!s.contains("AAAA"), "{s}");
|
||||
assert!(s.contains("192.168.1.20"));
|
||||
assert!(s.contains("\"user\": \"root\""));
|
||||
assert!(s.contains("scan finished: 9 miners"));
|
||||
assert_eq!(s.matches("[redacted]").count(), 5, "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_log_keeps_the_newest_lines_within_limits() {
|
||||
let log: Vec<String> = (0..500)
|
||||
.map(|i| format!("line {i} {}", "x".repeat(300)))
|
||||
.collect();
|
||||
let tail = recent_log(&log.join("\n"));
|
||||
assert!(tail.len() <= LOG_BYTES);
|
||||
assert!(tail.ends_with(&log[499]));
|
||||
assert!(tail.starts_with("line "), "cut on a line boundary");
|
||||
assert!(!tail.contains("line 400 "), "only the newest lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_carries_kind_text_and_context() {
|
||||
let ctx = Context {
|
||||
app_version: "1.2.3".into(),
|
||||
platform: "macos-aarch64".into(),
|
||||
os: "macOS 15.1".into(),
|
||||
appearance: "dark".into(),
|
||||
language: "en".into(),
|
||||
window: "1280x800".into(),
|
||||
};
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(&payload(Kind::Ui, "Text \"quoted\"", &ctx, None)).unwrap();
|
||||
assert_eq!(v["kind"], "ui");
|
||||
assert_eq!(v["text"], "Text \"quoted\"");
|
||||
assert_eq!(v["app_version"], "1.2.3");
|
||||
assert_eq!(v["log"], "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_parsing() {
|
||||
assert_eq!(
|
||||
parse_response("{\"number\":42,\"url\":\"https://x/42\"}\n201"),
|
||||
Ok(Filed {
|
||||
number: 42,
|
||||
url: "https://x/42".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("{\"error\":\"Too many reports; try again later\"}\n429"),
|
||||
Err("Too many reports; try again later".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("\n000"),
|
||||
Err("could not reach the report service".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("<html>\n502"),
|
||||
Err("the report service answered HTTP 502".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -69,13 +69,26 @@ pub fn load_ssh_credentials() -> Option<(String, String)> {
|
||||
load_creds_file(SSH_CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
/// Save the SSH username/password (0600). Retained for a future SSH-login dialog
|
||||
/// now that the SSH PIC probe that used to save it has been removed (round 14 #5).
|
||||
#[allow(dead_code)]
|
||||
/// Save the SSH username/password (0600), from the Credentials dialog.
|
||||
pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
||||
save_creds_file(SSH_CREDENTIALS_FILE, user, pass)
|
||||
}
|
||||
|
||||
/// Remove the saved SSH login, if any. Not an error if none was saved.
|
||||
pub fn clear_ssh_credentials() -> std::io::Result<()> {
|
||||
clear_creds_file(SSH_CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
/// The SSH username to use: the saved one, or `root` (the control-board login
|
||||
/// on every firmware the restore flow drives over SSH) when none was entered.
|
||||
pub fn ssh_user_or_default(user: &str) -> String {
|
||||
if user.trim().is_empty() {
|
||||
"root".to_string()
|
||||
} else {
|
||||
user.trim().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the saved web/API credentials, if any. Not an error if none were saved.
|
||||
pub fn clear_credentials() -> std::io::Result<()> {
|
||||
match clear_creds_file(CREDENTIALS_FILE) {
|
||||
@@ -272,6 +285,28 @@ mod tests {
|
||||
assert_eq!(load_credentials(), None, "cleared -> None");
|
||||
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
|
||||
|
||||
// SSH login: separate file, same 0600 rule, clear is idempotent.
|
||||
assert_eq!(load_ssh_credentials(), None, "no SSH file -> None");
|
||||
save_ssh_credentials("root", "ssh-pass").unwrap();
|
||||
assert_owner_only(
|
||||
&config_path(SSH_CREDENTIALS_FILE),
|
||||
"SSH creds file must be 0600",
|
||||
);
|
||||
assert_eq!(
|
||||
load_ssh_credentials(),
|
||||
Some(("root".to_string(), "ssh-pass".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
load_credentials(),
|
||||
None,
|
||||
"SSH save leaves the web login alone"
|
||||
);
|
||||
clear_ssh_credentials().unwrap();
|
||||
assert_eq!(load_ssh_credentials(), None, "cleared -> None");
|
||||
clear_ssh_credentials().unwrap();
|
||||
assert_eq!(ssh_user_or_default(""), "root");
|
||||
assert_eq!(ssh_user_or_default(" admin "), "admin");
|
||||
|
||||
// Per-firmware overrides (round 12 #13). Kept in this same test because
|
||||
// HOME is process-global: a second #[test] mutating it would race under
|
||||
// cargo's default parallel runner.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Bench-fleet fixtures: the expected hardware output of the 9 boards on
|
||||
//! 10.255.1.0/24 (see ../../../HANDOFF.md section 7 and the parent project's
|
||||
//! [removed]). These are the reference values the workflow tests compare
|
||||
//! Fixture fleet: the expected hardware output of nine representative miners
|
||||
//! (one per control-board family / firmware). These are the reference values
|
||||
//! the workflow tests compare
|
||||
//! the application's actual output against, and the rows the offline
|
||||
//! `ALKANE_FAKE_SCAN` demo mode renders. Only miners that respond become rows,
|
||||
//! so there is no synthetic "offline" fixture.
|
||||
|
||||
@@ -34,7 +34,7 @@ impl Lang {
|
||||
Lang::Pt => "Portugu\u{ea}s",
|
||||
}
|
||||
}
|
||||
fn code(self) -> &'static str {
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Lang::En => "en",
|
||||
Lang::Zh => "zh",
|
||||
@@ -137,6 +137,13 @@ const TABLE: &[(&str, [&str; 6])] = &[
|
||||
("Credentials", ["Credentials", "\u{51ed}\u{636e}", "\u{0423}\u{0447}\u{0451}\u{0442}\u{043d}\u{044b}\u{0435} \u{0434}\u{0430}\u{043d}\u{043d}\u{044b}\u{0435}", "Identifiants", "Credenciales", "Credenciais"]),
|
||||
("Language", ["Language", "\u{8bed}\u{8a00}", "\u{042f}\u{0437}\u{044b}\u{043a}", "Langue", "Idioma", "Idioma"]),
|
||||
("Logs", ["Logs", "\u{65e5}\u{5fd7}", "\u{0416}\u{0443}\u{0440}\u{043d}\u{0430}\u{043b}", "Journaux", "Registros", "Registos"]),
|
||||
("Bug report", ["Bug report", "\u{95ee}\u{9898}\u{53cd}\u{9988}", "\u{421}\u{43e}\u{43e}\u{431}\u{449}\u{438}\u{442}\u{44c} \u{43e}\u{431} \u{43e}\u{448}\u{438}\u{431}\u{43a}\u{435}", "Signaler un bug", "Informar de un error", "Relatar um erro"]),
|
||||
("Type", ["Type", "\u{7c7b}\u{578b}", "\u{422}\u{438}\u{43f}", "Type", "Tipo", "Tipo"]),
|
||||
("Bug", ["Bug", "\u{7f3a}\u{9677}", "\u{41e}\u{448}\u{438}\u{431}\u{43a}\u{430}", "Bug", "Error", "Erro"]),
|
||||
("UI change", ["UI change", "\u{754c}\u{9762}\u{4fee}\u{6539}", "\u{418}\u{437}\u{43c}\u{435}\u{43d}\u{435}\u{43d}\u{438}\u{435} \u{438}\u{43d}\u{442}\u{435}\u{440}\u{444}\u{435}\u{439}\u{441}\u{430}", "Modification de l'interface", "Cambio de interfaz", "Altera\u{e7}\u{e3}o da interface"]),
|
||||
("Feature request", ["Feature request", "\u{529f}\u{80fd}\u{5efa}\u{8bae}", "\u{41f}\u{440}\u{435}\u{434}\u{43b}\u{43e}\u{436}\u{435}\u{43d}\u{438}\u{435} \u{444}\u{443}\u{43d}\u{43a}\u{446}\u{438}\u{438}", "Demande de fonctionnalit\u{e9}", "Solicitud de funci\u{f3}n", "Pedido de recurso"]),
|
||||
("Send", ["Send", "\u{53d1}\u{9001}", "\u{41e}\u{442}\u{43f}\u{440}\u{430}\u{432}\u{438}\u{442}\u{44c}", "Envoyer", "Enviar", "Enviar"]),
|
||||
("Open issue", ["Open issue", "\u{6253}\u{5f00}\u{95ee}\u{9898}", "\u{41e}\u{442}\u{43a}\u{440}\u{44b}\u{442}\u{44c} \u{437}\u{430}\u{434}\u{430}\u{447}\u{443}", "Ouvrir le ticket", "Abrir incidencia", "Abrir issue"]),
|
||||
// KPI captions
|
||||
("Total", ["Total", "\u{603b}\u{6570}", "\u{0412}\u{0441}\u{0435}\u{0433}\u{043e}", "Total", "Total", "Total"]),
|
||||
("Hashing", ["Hashing", "\u{6b63}\u{5728}\u{6316}\u{77ff}", "\u{0425}\u{0435}\u{0448}\u{0438}\u{0440}\u{043e}\u{0432}\u{0430}\u{043d}\u{0438}\u{0435}", "Minage", "Minando", "Minerando"]),
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
mod access_probe;
|
||||
mod askpass;
|
||||
mod bug_report;
|
||||
mod credentials;
|
||||
mod export;
|
||||
mod fixtures;
|
||||
@@ -99,6 +100,17 @@ fn run_selftest() -> i32 {
|
||||
let frame = wx_rs::Widget::main_frame();
|
||||
let mut app = ui::build(frame);
|
||||
let ok = app.run_fixture_selftest();
|
||||
// ALKANE_SNAPSHOT=path (macOS): also write a PNG of the window as the app
|
||||
// draws it, to check rendering without screen-recording permission.
|
||||
if let Some(path) = std::env::var_os("ALKANE_SNAPSHOT") {
|
||||
let path = path.to_string_lossy();
|
||||
let wrote = wx_rs::snapshot_png(&frame, &path);
|
||||
println!(
|
||||
"SNAPSHOT {} {}",
|
||||
if wrote { "wrote" } else { "unavailable" },
|
||||
path
|
||||
);
|
||||
}
|
||||
println!("SELFTEST {}", if ok { "PASS" } else { "FAIL" });
|
||||
if ok {
|
||||
0
|
||||
|
||||
@@ -245,7 +245,7 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) {
|
||||
if pass.is_empty() {
|
||||
return (
|
||||
false,
|
||||
"Braiins restore needs an SSH password (set the SSH login)".into(),
|
||||
"Braiins restore needs an SSH password (Credentials > SSH)".into(),
|
||||
);
|
||||
}
|
||||
let target = format!("{user}@{ip}");
|
||||
|
||||
@@ -86,7 +86,9 @@ pub fn save_scan_concurrency(n: usize) -> std::io::Result<()> {
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
pub const DEFAULT_RANGE: &str = "10.255.1.0/24";
|
||||
/// The usual home/site router subnet. Host bits are masked off, so this scans
|
||||
/// 192.168.1.0/24.
|
||||
pub const DEFAULT_RANGE: &str = "192.168.1.1/24";
|
||||
/// Default seconds between automatic rescans.
|
||||
pub const DEFAULT_AUTO_SECS: u64 = 300;
|
||||
|
||||
@@ -2267,6 +2269,13 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_range_covers_the_whole_192_168_1_subnet() {
|
||||
let ips = parse_line(DEFAULT_RANGE).unwrap();
|
||||
let cidrs = targets_to_cidrs(&ips);
|
||||
assert_eq!(cidrs, vec![(Ipv4Addr::new(192, 168, 1, 0), 24)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cidr_aggregation_round_trips() {
|
||||
// a /24 must aggregate back to exactly one /24 block
|
||||
|
||||
+388
-12
@@ -22,6 +22,12 @@ pub const ID_PRESETS: i32 = 108;
|
||||
pub const ID_EXPORT: i32 = 109;
|
||||
// Settings menu (round 15 #13): the toolbar button + its menu items.
|
||||
pub const ID_SETTINGS: i32 = 110;
|
||||
// Bug report / feature request dialog (toolbar, between Export and Settings).
|
||||
pub const ID_BUG_REPORT: i32 = 111;
|
||||
const ID_REPORT_SEND: i32 = 240;
|
||||
const ID_REPORT_CLOSE: i32 = 241;
|
||||
const ID_REPORT_OPEN: i32 = 242;
|
||||
const ID_REPORT_KIND: i32 = 243;
|
||||
const ID_LANG_BASE: i32 = 790; // one id per language (790 + Lang index); reserves 790..790+Lang::all().len()
|
||||
const ID_LOGS_OPEN: i32 = 796; // open the Logs page
|
||||
const ID_LOGS_REFRESH: i32 = 797;
|
||||
@@ -170,6 +176,68 @@ struct Palette {
|
||||
accent: (u8, u8, u8),
|
||||
/// Odd-row (zebra) background: a subtle tint of the window colour.
|
||||
zebra: (u8, u8, u8),
|
||||
/// Backgrounds coloured text is drawn on (window, zebra row, KPI card).
|
||||
/// `text()` keeps every computed text colour readable on all of them.
|
||||
text_bgs: Vec<(u8, u8, u8)>,
|
||||
}
|
||||
|
||||
/// WCAG relative luminance of an sRGB colour.
|
||||
fn wcag_luminance(c: (u8, u8, u8)) -> f64 {
|
||||
let ch = |v: u8| {
|
||||
let v = v as f64 / 255.0;
|
||||
if v <= 0.03928 {
|
||||
v / 12.92
|
||||
} else {
|
||||
((v + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
};
|
||||
0.2126 * ch(c.0) + 0.7152 * ch(c.1) + 0.0722 * ch(c.2)
|
||||
}
|
||||
|
||||
/// WCAG contrast ratio of two colours (1.0 to 21.0).
|
||||
fn contrast_ratio(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 {
|
||||
let (la, lb) = (wcag_luminance(a), wcag_luminance(b));
|
||||
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
|
||||
}
|
||||
|
||||
/// Minimum contrast for text: WCAG AA for normal-size text.
|
||||
const MIN_TEXT_CONTRAST: f64 = 4.5;
|
||||
/// Minimum contrast for icons and other graphics (WCAG non-text contrast).
|
||||
const MIN_ICON_CONTRAST: f64 = 3.0;
|
||||
|
||||
/// `c`, darkened (on light backgrounds) or lightened (on dark ones) just
|
||||
/// enough to reach MIN_TEXT_CONTRAST against every background in `bgs`,
|
||||
/// keeping its hue. Colours that already pass are returned unchanged.
|
||||
fn readable(c: (u8, u8, u8), bgs: &[(u8, u8, u8)]) -> (u8, u8, u8) {
|
||||
readable_at(c, bgs, MIN_TEXT_CONTRAST)
|
||||
}
|
||||
|
||||
/// `readable` with an explicit minimum ratio (MIN_ICON_CONTRAST for icons).
|
||||
fn readable_at(c: (u8, u8, u8), bgs: &[(u8, u8, u8)], min: f64) -> (u8, u8, u8) {
|
||||
let passes = |c| bgs.iter().all(|&bg| contrast_ratio(c, bg) >= min);
|
||||
if bgs.is_empty() || passes(c) {
|
||||
return c;
|
||||
}
|
||||
let mean = bgs.iter().map(|&bg| wcag_luminance(bg)).sum::<f64>() / bgs.len() as f64;
|
||||
let target = if mean > 0.18 {
|
||||
(0, 0, 0)
|
||||
} else {
|
||||
(255, 255, 255)
|
||||
};
|
||||
for step in 1..=50 {
|
||||
let d = tint_toward(c, target, step as f64 / 50.0);
|
||||
if passes(d) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// A text colour adjusted to stay readable on this theme's backgrounds.
|
||||
fn text(&self, c: (u8, u8, u8)) -> (u8, u8, u8) {
|
||||
readable(c, &self.text_bgs)
|
||||
}
|
||||
}
|
||||
|
||||
fn luminance(c: (u8, u8, u8)) -> f32 {
|
||||
@@ -206,11 +274,11 @@ fn tint_toward(base: (u8, u8, u8), target: (u8, u8, u8), f: f64) -> (u8, u8, u8)
|
||||
/// output reads as clearly bad, and 100% reads green.
|
||||
fn ratio_color(pal: &Palette, ratio: f64) -> (u8, u8, u8) {
|
||||
let t = ((ratio - 0.5) / 0.5).clamp(0.0, 1.0);
|
||||
if t <= 0.5 {
|
||||
pal.text(if t <= 0.5 {
|
||||
tint_toward(pal.red, pal.amber, t / 0.5)
|
||||
} else {
|
||||
tint_toward(pal.amber, pal.green, (t - 0.5) / 0.5)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a firmware family has a supported restore-to-stock path (round 12
|
||||
@@ -246,11 +314,11 @@ fn firmware_color(family: &str) -> Option<(u8, u8, u8)> {
|
||||
/// Colour for a chip-temperature reading: cool blue at/below 40 C fading to hot
|
||||
/// red at/above 90 C, so a hot miner reads red at a glance.
|
||||
fn temp_color(pal: &Palette, temp_c: f64) -> (u8, u8, u8) {
|
||||
tint_toward(
|
||||
pal.text(tint_toward(
|
||||
pal.accent,
|
||||
pal.red,
|
||||
((temp_c - 40.0) / 50.0).clamp(0.0, 1.0),
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// Build the segment-encoded cell for a combined actual/expected column
|
||||
@@ -618,7 +686,7 @@ fn palette() -> Palette {
|
||||
let win = wx_rs::system_color(0); // window background
|
||||
let text = wx_rs::system_color(1); // window text
|
||||
let dark = luminance(win) < 128.0;
|
||||
Palette {
|
||||
let mut p = Palette {
|
||||
// Cards read as slightly elevated vs the window: lighter in dark mode,
|
||||
// pure white on a light-grey window.
|
||||
card_bg: if dark {
|
||||
@@ -647,7 +715,17 @@ fn palette() -> Palette {
|
||||
} else {
|
||||
nudge(win, -10)
|
||||
},
|
||||
}
|
||||
text_bgs: Vec::new(),
|
||||
};
|
||||
// Every coloured text must read on the window, the zebra rows and the
|
||||
// KPI cards in both themes; tune the fixed hues to those backgrounds.
|
||||
p.text_bgs = vec![win, p.zebra, p.card_bg];
|
||||
p.label = p.text(p.label);
|
||||
p.green = p.text(p.green);
|
||||
p.amber = p.text(p.amber);
|
||||
p.red = p.text(p.red);
|
||||
p.accent = p.text(p.accent);
|
||||
p
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
@@ -770,6 +848,8 @@ pub struct App {
|
||||
// Credentials dialog (round 13 #2). Empty when no global credential is set.
|
||||
creds_user_input: Widget,
|
||||
creds_pass_input: Widget,
|
||||
ssh_user_input: Widget,
|
||||
ssh_pass_input: Widget,
|
||||
// The Credentials dialog (round 13 #2): the global login above plus one
|
||||
// (firmware name, user field, pass field) row per registry firmware.
|
||||
fwcreds_dialog: Widget,
|
||||
@@ -789,6 +869,15 @@ pub struct App {
|
||||
// Settings > Logs page (round 15 #13).
|
||||
logs_dialog: Widget,
|
||||
logs_text: Widget,
|
||||
// Bug report dialog (bug_report.rs): its controls, the send in flight and
|
||||
// the last filed issue's link.
|
||||
report_dialog: Widget,
|
||||
report_kind: Widget,
|
||||
report_text: Widget,
|
||||
report_log: Widget,
|
||||
report_status: Widget,
|
||||
report_rx: Option<std::sync::mpsc::Receiver<Result<crate::bug_report::Filed, String>>>,
|
||||
report_url: Option<String>,
|
||||
// Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog.
|
||||
restore: Option<restore::RestoreHandle>,
|
||||
restore_dialog: Widget,
|
||||
@@ -1001,11 +1090,20 @@ pub fn build(frame: Widget) -> App {
|
||||
ctl.add_spacer(8);
|
||||
// Play / pause / stop as coloured media icons (green / amber / red). Vivid
|
||||
// fixed colours read well on both light and dark themes.
|
||||
let play_btn = Widget::media_button(panel, ID_PLAY, 0, (56, 190, 108));
|
||||
// The icon colours are kept to at least 3:1 against this theme's button
|
||||
// face (the fixed hues alone were about 2:1 on light buttons). Native
|
||||
// buttons do not all paint the system button-face colour (macOS draws
|
||||
// #ebebeb on a white window), so also check the window colour and a shade
|
||||
// 20 steps toward the opposite end.
|
||||
let win = wx_rs::system_color(0);
|
||||
let shade = if luminance(win) < 128.0 { 20 } else { -20 };
|
||||
let face = [wx_rs::system_color(3), win, nudge(win, shade)];
|
||||
let icon = |c| readable_at(c, &face, MIN_ICON_CONTRAST);
|
||||
let play_btn = Widget::media_button(panel, ID_PLAY, 0, icon((56, 190, 108)));
|
||||
ctl.add(play_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, (240, 172, 40));
|
||||
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, icon((240, 172, 40)));
|
||||
ctl.add(pause_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
|
||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, icon((226, 72, 60)));
|
||||
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
ctl.add_stretch(1);
|
||||
// Toolbar buttons; labels are localized and tracked for live re-labelling
|
||||
@@ -1022,6 +1120,7 @@ pub fn build(frame: Widget) -> App {
|
||||
let _filter_btn = tbtn("Filter", ID_FILTER);
|
||||
let _columns_btn = tbtn("Columns", ID_COLUMNS);
|
||||
let _export_btn = tbtn("Export", ID_EXPORT);
|
||||
let _report_btn = tbtn("Bug report", ID_BUG_REPORT);
|
||||
// The old Credentials button is now a Settings menu (round 15 #13).
|
||||
let _creds_btn = tbtn("Settings", ID_SETTINGS);
|
||||
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
|
||||
@@ -1138,6 +1237,8 @@ pub fn build(frame: Widget) -> App {
|
||||
header_menu_col: None,
|
||||
creds_user_input: frame,
|
||||
creds_pass_input: frame,
|
||||
ssh_user_input: frame,
|
||||
ssh_pass_input: frame,
|
||||
fwcreds_dialog: frame,
|
||||
fwcreds_rows: Vec::new(),
|
||||
access_probe: None,
|
||||
@@ -1145,6 +1246,13 @@ pub fn build(frame: Widget) -> App {
|
||||
logview_dialog: frame,
|
||||
logs_dialog: frame,
|
||||
logs_text: frame,
|
||||
report_dialog: frame,
|
||||
report_kind: frame,
|
||||
report_text: frame,
|
||||
report_log: frame,
|
||||
report_status: frame,
|
||||
report_rx: None,
|
||||
report_url: None,
|
||||
restore: None,
|
||||
restore_dialog: frame,
|
||||
pending_restore: Vec::new(),
|
||||
@@ -1413,7 +1521,10 @@ impl App {
|
||||
let color = (!r.errors.is_empty()).then_some(self.pal.red);
|
||||
encode_flag_cell(&c.cell(r), color)
|
||||
}
|
||||
Column::Firmware => encode_flag_cell(&c.cell(r), firmware_color(&r.firmware)),
|
||||
Column::Firmware => encode_flag_cell(
|
||||
&c.cell(r),
|
||||
firmware_color(&r.firmware).map(|fc| self.pal.text(fc)),
|
||||
),
|
||||
Column::Status => {
|
||||
// The status reads as its KPI icon (round 12 #11), drawn
|
||||
// in the status colour so it matches the dashboard card.
|
||||
@@ -2355,6 +2466,7 @@ impl App {
|
||||
vnish_pass
|
||||
};
|
||||
let (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default();
|
||||
let ssh_user = credentials::ssh_user_or_default(&ssh_user);
|
||||
let ips: Vec<String> = targets.iter().map(|t| t.ip.clone()).collect();
|
||||
self.restore_dialog.close(1);
|
||||
crate::logs::log(format!("restore {} miner(s) to stock", ips.len()));
|
||||
@@ -3112,6 +3224,52 @@ impl App {
|
||||
);
|
||||
self.creds_user_input = user_input;
|
||||
self.creds_pass_input = pass_input;
|
||||
// SSH login for the control board (Braiins restore-to-stock). Same rule
|
||||
// as the global login: the password is never shown, blank keeps it.
|
||||
let (ssh_user, ssh_pass) = credentials::load_ssh_credentials().unwrap_or_default();
|
||||
let s_hint = if ssh_pass.is_empty() {
|
||||
"SSH (restore)"
|
||||
} else {
|
||||
"SSH (password saved; blank keeps it)"
|
||||
};
|
||||
let srow = Widget::box_sizer(false);
|
||||
let slabel = Widget::static_text(dlg, s_hint);
|
||||
slabel.set_min_size(150, -1);
|
||||
srow.add(
|
||||
slabel,
|
||||
0,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
6,
|
||||
);
|
||||
let ssh_user_input = Widget::text_ctrl(dlg, false);
|
||||
ssh_user_input.set_min_size(150, -1);
|
||||
ssh_user_input.set_value(if ssh_user.is_empty() {
|
||||
"root"
|
||||
} else {
|
||||
&ssh_user
|
||||
});
|
||||
srow.add(
|
||||
ssh_user_input,
|
||||
0,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
6,
|
||||
);
|
||||
let ssh_pass_input = Widget::password_ctrl(dlg);
|
||||
ssh_pass_input.set_min_size(150, -1);
|
||||
srow.add(
|
||||
ssh_pass_input,
|
||||
1,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
6,
|
||||
);
|
||||
root.add_sizer(
|
||||
srow,
|
||||
0,
|
||||
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
6,
|
||||
);
|
||||
self.ssh_user_input = ssh_user_input;
|
||||
self.ssh_pass_input = ssh_pass_input;
|
||||
// Column headers.
|
||||
let head = Widget::box_sizer(false);
|
||||
let h_fw = Widget::static_text(dlg, "Firmware");
|
||||
@@ -3223,6 +3381,21 @@ impl App {
|
||||
wx_rs::set_status_text(&format!("failed to save global login: {e}"));
|
||||
return;
|
||||
}
|
||||
// SSH login: a blank password keeps the saved one; with nothing saved
|
||||
// and no password entered there is nothing to store.
|
||||
let s_user = credentials::ssh_user_or_default(&self.ssh_user_input.get_value());
|
||||
let s_pass = self.ssh_pass_input.get_value();
|
||||
let ssh_result = if !s_pass.is_empty() {
|
||||
credentials::save_ssh_credentials(&s_user, &s_pass)
|
||||
} else if let Some((_, saved)) = credentials::load_ssh_credentials() {
|
||||
credentials::save_ssh_credentials(&s_user, &saved)
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
if let Err(e) = ssh_result {
|
||||
wx_rs::set_status_text(&format!("failed to save SSH login: {e}"));
|
||||
return;
|
||||
}
|
||||
// Per-firmware overrides.
|
||||
let mut map: std::collections::HashMap<String, (String, String)> =
|
||||
std::collections::HashMap::new();
|
||||
@@ -3259,6 +3432,8 @@ impl App {
|
||||
fn apply_firmware_creds_reset(&mut self) {
|
||||
self.creds_user_input.set_value("");
|
||||
self.creds_pass_input.set_value("");
|
||||
self.ssh_user_input.set_value("root");
|
||||
self.ssh_pass_input.set_value("");
|
||||
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
|
||||
let (user, pass) = credentials::firmware_default_for(name);
|
||||
user_ctrl.set_value(&user);
|
||||
@@ -3266,7 +3441,8 @@ impl App {
|
||||
}
|
||||
let per_fw = credentials::clear_firmware_credentials();
|
||||
let global = credentials::clear_credentials();
|
||||
match per_fw.and(global) {
|
||||
let ssh = credentials::clear_ssh_credentials();
|
||||
match per_fw.and(global).and(ssh) {
|
||||
Ok(()) => wx_rs::set_status_text("credentials reset to defaults"),
|
||||
Err(e) => wx_rs::set_status_text(&format!("failed to reset credentials: {e}")),
|
||||
}
|
||||
@@ -3559,6 +3735,7 @@ impl App {
|
||||
self.drain_refresh();
|
||||
self.drain_access_probe();
|
||||
self.drain_restore();
|
||||
self.drain_report();
|
||||
// A completed background log fetch yields a viewer dialog to show; return
|
||||
// it so `dispatch` presents it modally after the App borrow is released
|
||||
// (round 18 #12).
|
||||
@@ -3878,7 +4055,7 @@ impl App {
|
||||
let edit = Widget::text_ctrl(dlg, true);
|
||||
edit.set_value(&scan::load_ranges().join("\n"));
|
||||
edit.set_tool_tip(
|
||||
"One range per line:\n CIDR 10.255.1.0/24\n range 10.253.1.3-10.253.1.234\n single 10.253.1.5",
|
||||
"One range per line:\n CIDR 192.168.1.0/24\n range 192.168.1.3-192.168.1.234\n single 192.168.1.5",
|
||||
);
|
||||
root.add(edit, 1, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
// Auto-rescan interval (seconds; 0 = off) and per-miner scan timeout.
|
||||
@@ -4279,6 +4456,168 @@ impl App {
|
||||
|
||||
/// Build (but do not show) the Logs page (round 15 #13): the in-app activity
|
||||
/// log with Refresh / Clear / Close.
|
||||
/// The Bug report dialog: a type (Bug, UI change, Feature request), one text
|
||||
/// box whose first line becomes the issue title, and whether to include the
|
||||
/// recent activity log (scrubbed). Send files it through the report relay
|
||||
/// (bug_report.rs) and shows the issue number, or the reason, in the dialog.
|
||||
fn build_report_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let t = crate::i18n::t;
|
||||
let dlg = Widget::dialog(frame, &t("Bug report"));
|
||||
let root = Widget::box_sizer(true);
|
||||
let kindrow = Widget::box_sizer(false);
|
||||
kindrow.add(
|
||||
Widget::static_text(dlg, &t("Type")),
|
||||
0,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let kind = Widget::choice(dlg, ID_REPORT_KIND);
|
||||
for k in crate::bug_report::Kind::ALL {
|
||||
kind.choice_append(&t(k.label()));
|
||||
}
|
||||
kind.choice_set_selection(0);
|
||||
kindrow.add(kind, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
|
||||
root.add_sizer(kindrow, 0, sf::BORDER_ALL, 8);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&t("Describe the problem or the idea. The first line becomes the title."),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let text = Widget::text_ctrl(dlg, true);
|
||||
text.set_min_size(560, 220);
|
||||
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
|
||||
let log = Widget::check_box(
|
||||
dlg,
|
||||
&t("Include the recent activity log (passwords removed)"),
|
||||
);
|
||||
log.set_checked(true);
|
||||
root.add(log, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&t("Reports are public issues on gitea.bluefla.re. The app version and OS are included."),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
8,
|
||||
);
|
||||
let status = Widget::static_text(dlg, "");
|
||||
root.add(
|
||||
status,
|
||||
0,
|
||||
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let btns = Widget::box_sizer(false);
|
||||
let open = Widget::button(dlg, &t("Open issue"), ID_REPORT_OPEN);
|
||||
btns.add(open, 0, sf::BORDER_ALL, 6);
|
||||
btns.add_stretch(1);
|
||||
btns.add(
|
||||
Widget::button(dlg, &t("Close"), ID_REPORT_CLOSE),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
btns.add(
|
||||
Widget::button(dlg, &t("Send"), ID_REPORT_SEND),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(600, 440);
|
||||
dlg.fit(dlg);
|
||||
self.report_dialog = dlg;
|
||||
self.report_kind = kind;
|
||||
self.report_text = text;
|
||||
self.report_log = log;
|
||||
self.report_status = status;
|
||||
self.report_url = None;
|
||||
dlg
|
||||
}
|
||||
|
||||
/// Validate the Bug report dialog and send it on a worker thread.
|
||||
fn send_report(&mut self) {
|
||||
let t = crate::i18n::t;
|
||||
if self.report_rx.is_some() {
|
||||
return; // one send at a time
|
||||
}
|
||||
let text = self.report_text.get_value();
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
self.report_status
|
||||
.set_label(&t("Write what happened or what you would like first."));
|
||||
return;
|
||||
}
|
||||
if text.chars().count() > crate::bug_report::MAX_TEXT_CHARS {
|
||||
self.report_status.set_label(&format!(
|
||||
"{} ({} / {})",
|
||||
t("The text is too long"),
|
||||
text.chars().count(),
|
||||
crate::bug_report::MAX_TEXT_CHARS
|
||||
));
|
||||
return;
|
||||
}
|
||||
let kinds = crate::bug_report::Kind::ALL;
|
||||
let kind = usize::try_from(self.report_kind.choice_get_selection())
|
||||
.ok()
|
||||
.and_then(|i| kinds.get(i).copied())
|
||||
.unwrap_or(crate::bug_report::Kind::Bug);
|
||||
let size = wx_rs::get_client_size();
|
||||
let ctx = crate::bug_report::Context::current(
|
||||
wx_rs::is_dark(),
|
||||
crate::i18n::current().code(),
|
||||
(size.width as i32, size.height as i32),
|
||||
);
|
||||
let log = self
|
||||
.report_log
|
||||
.is_checked()
|
||||
.then(|| crate::bug_report::recent_log(&crate::logs::dump()));
|
||||
let body = crate::bug_report::payload(kind, text, &ctx, log.as_deref());
|
||||
self.report_status.set_label(&t("Sending..."));
|
||||
self.report_rx = Some(crate::bug_report::send(body));
|
||||
}
|
||||
|
||||
/// Show the Bug report result in the dialog once the send finishes.
|
||||
fn drain_report(&mut self) {
|
||||
let Some(rx) = &self.report_rx else { return };
|
||||
let result = match rx.try_recv() {
|
||||
Ok(r) => r,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
Err("the report was not sent".to_string())
|
||||
}
|
||||
};
|
||||
self.report_rx = None;
|
||||
let t = crate::i18n::t;
|
||||
match result {
|
||||
Ok(filed) => {
|
||||
crate::logs::log(format!("bug report filed as issue #{}", filed.number));
|
||||
self.report_status.set_label(&format!(
|
||||
"{} #{}",
|
||||
t("Thank you. Filed as issue"),
|
||||
filed.number
|
||||
));
|
||||
self.report_text.set_value("");
|
||||
self.report_kind.choice_set_selection(0);
|
||||
if !filed.url.is_empty() {
|
||||
self.report_url = Some(filed.url);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
crate::logs::log(format!("bug report not sent: {e}"));
|
||||
self.report_status
|
||||
.set_label(&format!("{} {e}", t("Not sent:")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_logs_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, &crate::i18n::t("Logs"));
|
||||
@@ -4864,6 +5203,17 @@ impl App {
|
||||
ID_EXPORT_ALL => self.export_check_all(true),
|
||||
ID_EXPORT_NONE => self.export_check_all(false),
|
||||
ID_SETTINGS => self.open_settings_menu(),
|
||||
ID_BUG_REPORT => return Some(self.build_report_dialog()),
|
||||
ID_REPORT_SEND => self.send_report(),
|
||||
ID_REPORT_CLOSE => self.report_dialog.close(0),
|
||||
ID_REPORT_OPEN => match &self.report_url {
|
||||
Some(url) => {
|
||||
wx_rs::launch_browser(url);
|
||||
}
|
||||
None => self.report_status.set_label(&crate::i18n::t(
|
||||
"Send a report first; its issue opens here.",
|
||||
)),
|
||||
},
|
||||
ID_LOGS_REFRESH => self.logs_text.set_value(&crate::logs::dump()),
|
||||
ID_LOGS_CLEAR => {
|
||||
crate::logs::clear();
|
||||
@@ -5321,9 +5671,35 @@ mod tests {
|
||||
red: (255, 0, 0),
|
||||
accent: (0, 0, 255),
|
||||
zebra: (245, 245, 245),
|
||||
text_bgs: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readable_reaches_aa_contrast_on_every_background() {
|
||||
let light = [(255, 255, 255), (245, 245, 245)];
|
||||
let dark = [(30, 30, 30), (41, 41, 41), (44, 44, 44)];
|
||||
for fw in [
|
||||
"braiins", "luxos", "vnish", "bixbit", "epic", "hiveon", "alkane",
|
||||
] {
|
||||
let c = firmware_color(fw).unwrap();
|
||||
for bgs in [&light[..], &dark[..]] {
|
||||
let r = readable(c, bgs);
|
||||
for &bg in bgs {
|
||||
assert!(
|
||||
contrast_ratio(r, bg) >= MIN_TEXT_CONTRAST,
|
||||
"{fw} {r:?} on {bg:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Already-readable colours are left alone; hue survives the nudge.
|
||||
assert_eq!(readable((0, 0, 0), &light), (0, 0, 0));
|
||||
let gold = readable((185, 150, 20), &light);
|
||||
assert!(gold.0 > gold.1 && gold.1 > gold.2, "still gold: {gold:?}");
|
||||
assert!((contrast_ratio((255, 255, 255), (0, 0, 0)) - 21.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_toward_endpoints_and_midpoint() {
|
||||
let a = (10, 20, 30);
|
||||
|
||||
@@ -25,11 +25,11 @@ BEGIN
|
||||
BEGIN
|
||||
BLOCK "040904B0"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "Blueflare"
|
||||
VALUE "CompanyName", "BlueFlare Energy Solutions Inc."
|
||||
VALUE "FileDescription", "Alkane Toolkit"
|
||||
VALUE "FileVersion", ALKANE_VER_STR
|
||||
VALUE "InternalName", "alkane-toolkit"
|
||||
VALUE "LegalCopyright", "Copyright (c) 2026 Blueflare (MIT License)"
|
||||
VALUE "LegalCopyright", "Copyright (c) 2026 BlueFlare Energy Solutions Inc. (MIT License)"
|
||||
VALUE "OriginalFilename", "alkane-toolkit.exe"
|
||||
VALUE "ProductName", "Alkane Toolkit"
|
||||
VALUE "ProductVersion", ALKANE_VER_STR
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# macOS
|
||||
|
||||
The macOS build is one universal app, `Alkane Toolkit.app`, that runs natively
|
||||
on Apple Silicon and Intel Macs with macOS 11 (Big Sur) or later. It ships as
|
||||
`alkane-toolkit-vX.Y.Z-macos-universal.zip`, holding the app, `LICENSE` and a
|
||||
`README.txt`.
|
||||
|
||||
## Using it
|
||||
|
||||
- Settings live in `~/.config/alkane-toolkit`, the same files as on Linux.
|
||||
- SSH actions use the system `ssh`; HTTP actions use the system `curl`.
|
||||
- The app is ad-hoc signed but not notarized, so macOS blocks the first launch.
|
||||
On macOS 15 or later, try to open it, then choose **Open Anyway** in
|
||||
System Settings > Privacy & Security. On macOS 11 to 14, Control-click the
|
||||
app and choose **Open**. Or clear the quarantine flag once:
|
||||
`xattr -dr com.apple.quarantine "/Applications/Alkane Toolkit.app"`.
|
||||
- The first scan asks for permission to find devices on the local network
|
||||
(macOS 15 and later). Scanning needs it.
|
||||
- Offline demo: `ALKANE_FAKE_SCAN=1 "/Applications/Alkane Toolkit.app/Contents/MacOS/alkane-toolkit"`.
|
||||
|
||||
## Building
|
||||
|
||||
macOS builds only on a Mac. It needs the Xcode Command Line Tools
|
||||
(`xcode-select --install`) and rustup with both Apple targets:
|
||||
|
||||
```sh
|
||||
rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
scripts/build-wx-macos.sh # once: universal static wxOSX 3.3.3 in ~/.cache/wx-3.3.3-macos
|
||||
scripts/build-gui-macos.sh # both slices, merged with lipo
|
||||
python3 ci/package-macos.py X.Y.Z target/universal-apple-darwin/release/alkane-toolkit dist
|
||||
```
|
||||
|
||||
`build-wx-macos.sh` builds wxWidgets once for arm64 and x86_64 together, with
|
||||
wx's bundled image, zlib, regex and expat libraries, so the app links only
|
||||
against system frameworks. `build-gui-macos.sh` builds each Rust target
|
||||
against that prefix and merges them. `package-macos.py` writes the bundle
|
||||
(Info.plist, icon), ad-hoc signs it and zips it with `ditto`.
|
||||
|
||||
To test on the Mac:
|
||||
|
||||
```sh
|
||||
ALKANE_SELFTEST=1 target/universal-apple-darwin/release/alkane-toolkit # headless UI self-test
|
||||
cargo test --release --offline --target aarch64-apple-darwin --workspace --exclude wx-rs
|
||||
```
|
||||
|
||||
The self-test opens a window briefly, so it needs a logged-in desktop
|
||||
session. Running the x86_64 slice on Apple Silicon needs Rosetta 2.
|
||||
|
||||
## Why macOS 11
|
||||
|
||||
Current Xcode SDKs ship a libc++ that supports macOS 11 and later only;
|
||||
building for an older target compiles, but the app could fail at run time on
|
||||
the older system. macOS 11 is also the first release for Apple Silicon. Older
|
||||
Intel Macs would need a build with an older SDK.
|
||||
|
||||
## Notes for the bridge
|
||||
|
||||
wxOSX reports logical (point) sizes, like the GTK and MSW bridges; the
|
||||
bridge never scales to physical pixels. wxOSX's Objective-C uses
|
||||
`@available`, so `build.rs` links clang's compiler runtime
|
||||
(`libclang_rt.osx.a`), which rustc's link does not include by itself. Both
|
||||
are wx-rs patch `0009`.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Getting started
|
||||
|
||||
Alkane Toolkit finds the ASIC miners on your network and shows them in one
|
||||
table: model, firmware, hashrate, power, temperatures, fans and the health of
|
||||
every hashboard. From the same table you can run the controls each miner's
|
||||
firmware supports, such as pausing, restarting or changing pools.
|
||||
|
||||
## Download
|
||||
|
||||
Get the latest release from the
|
||||
[downloads page](https://gitea.bluefla.re/blueflare/alkane-toolkit/releases).
|
||||
|
||||
| Platform | File | Notes |
|
||||
|---|---|---|
|
||||
| Windows 10 and 11 (x86_64) | `alkane-toolkit-vX.Y.Z-windows-x86_64.zip` | One signed `alkane-toolkit.exe`; nothing to install |
|
||||
| Linux (x86_64) | `alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz` | One binary; needs GTK 3 (`sudo apt install libgtk-3-0`) |
|
||||
| macOS 11 or later (Apple Silicon and Intel) | `alkane-toolkit-vX.Y.Z-macos-universal.zip` | One app; not notarized, so confirm the first launch |
|
||||
|
||||
### Windows
|
||||
|
||||
1. Download the zip, right-click it, choose **Properties**, tick **Unblock** if
|
||||
it is shown, then extract it.
|
||||
2. Run `alkane-toolkit.exe`. Windows shows *BlueFlare Energy Solutions Inc.* as
|
||||
the verified publisher. To check the signature yourself, right-click the exe,
|
||||
choose **Properties** and open **Digital Signatures**.
|
||||
|
||||
### macOS
|
||||
|
||||
1. Download the zip and open it; drag **Alkane Toolkit** to Applications.
|
||||
2. Open it. The app is not notarized, so macOS blocks the first launch:
|
||||
- macOS 15 or later: open **System Settings > Privacy & Security** and
|
||||
choose **Open Anyway** for Alkane Toolkit.
|
||||
- macOS 11 to 14: Control-click the app, choose **Open**, then **Open**.
|
||||
3. When asked, allow it to find devices on your local network. Scanning
|
||||
needs this.
|
||||
|
||||
### Linux
|
||||
|
||||
```sh
|
||||
tar xzf alkane-toolkit-vX.Y.Z-linux-x86_64.tar.gz
|
||||
./alkane-toolkit-vX.Y.Z-linux-x86_64/alkane-toolkit
|
||||
```
|
||||
|
||||
## First run
|
||||
|
||||
The toolkit starts a scan as soon as it opens. Set your own ranges first with
|
||||
**Scan ranges** (see [Scanning](02-scanning.md)); until you do, it scans
|
||||
192.168.1.0/24, the usual router subnet.
|
||||
|
||||
To look around without touching any miner, start it in demo mode. It shows a
|
||||
built-in sample fleet and simulates every action:
|
||||
|
||||
| Platform | Command |
|
||||
|---|---|
|
||||
| Windows (Command Prompt) | `set ALKANE_FAKE_SCAN=1 && alkane-toolkit.exe` |
|
||||
| Linux | `ALKANE_FAKE_SCAN=1 ./alkane-toolkit` |
|
||||
|
||||
## Where settings are kept
|
||||
|
||||
| Platform | Folder |
|
||||
|---|---|
|
||||
| Windows | `%APPDATA%\alkane-toolkit` |
|
||||
| Linux | `~/.config/alkane-toolkit` |
|
||||
|
||||
See [Settings and credentials](06-settings.md) for the files in that folder.
|
||||
Deleting the folder resets the toolkit to its defaults.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Scanning
|
||||
|
||||
Discovery is read-only: a scan asks each address what it is and records what
|
||||
it reports. It never changes a miner.
|
||||
|
||||
## Scan ranges
|
||||
|
||||
Click **Scan ranges** to edit the addresses to scan. Put one entry per line;
|
||||
blank lines and lines starting with `#` are ignored.
|
||||
|
||||
| Form | Example | Scans |
|
||||
|---|---|---|
|
||||
| Single address | `192.168.1.50` | that address |
|
||||
| CIDR block | `192.168.1.0/24` | the whole block |
|
||||
| Full range | `192.168.1.10-192.168.2.40` | every address between the two, inclusive |
|
||||
| Short range | `192.168.1.10-90` | `.10` to `.90` within the same /24 |
|
||||
| Per-octet ranges | `10.1-4.0-1.1-255` | every combination (10.1.0.1 ... 10.4.1.255) |
|
||||
|
||||
Commas or spaces between several entries on one line are not accepted; use one
|
||||
line each. Duplicates are removed automatically. One line, and all lines
|
||||
together, may cover at most 1,000,000 addresses.
|
||||
|
||||
**Apply** saves the ranges and starts a scan. A mistake keeps the dialog open
|
||||
and the status bar explains it, for example `invalid range: bad octet range`.
|
||||
|
||||
The same dialog has three numbers:
|
||||
|
||||
| Field | Meaning | Default |
|
||||
|---|---|---|
|
||||
| Rescan (s) | seconds between automatic rescans; `0` turns auto-rescan off | 300 |
|
||||
| Timeout (s) | how long to wait for one miner (scans, refreshes, actions and log fetches) | 10 |
|
||||
| Concurrency | how many addresses are probed at once (8 to 256); higher is faster but slow miners may report fewer values | 128 |
|
||||
|
||||
When the ranges change, miners outside the new ranges leave the table at the
|
||||
next scan.
|
||||
|
||||
## Running, pausing and stopping
|
||||
|
||||
The three buttons next to **Scan ranges** control scanning:
|
||||
|
||||
- **Play** (green) turns auto-rescan on and starts a scan now if none is running.
|
||||
- **Pause** (amber) turns auto-rescan off and lets the current scan finish.
|
||||
- **Stop** (red) turns auto-rescan off and cancels the current scan.
|
||||
|
||||
While a scan runs, a progress bar spans the top of the table and the status bar
|
||||
shows progress such as `1935/4590 - scanning 192.168.1.86 (92 found)`. Afterwards
|
||||
it shows the count and the time to the next scan, for example
|
||||
`245 miners - next scan in 4m 12s`.
|
||||
|
||||
Actions that change miners wait for the scan to finish; see
|
||||
[Actions](05-actions.md).
|
||||
@@ -0,0 +1,80 @@
|
||||
# The table and header
|
||||
|
||||
## Summary cards
|
||||
|
||||
The cards at the top count the miners **currently shown** (after any filter).
|
||||
Each miner is in exactly one status: slow, paused, hashing or not hashing.
|
||||
|
||||
| Card | Counts | Click |
|
||||
|---|---|---|
|
||||
| Total | rows in the view | - |
|
||||
| Hashing (green rabbit) | mining at 80% of expected hashrate or more | show only these; click again to clear |
|
||||
| Slow (amber turtle) | mining below 80% of expected hashrate | show only these |
|
||||
| Not hashing (red glass) | answering but not mining | show only these |
|
||||
| Paused (blue otter) | stopped on purpose (paused, stopped, suspended) | show only these |
|
||||
| SHA-256 Hashrate | total hashrate, per algorithm | switch algorithm when the fleet runs more than one |
|
||||
| Est. power | total reported power draw | - |
|
||||
|
||||
On a narrow window the hashrate and power cards are hidden.
|
||||
|
||||
## Columns
|
||||
|
||||
IP is always the first column. The default view shows Model, Health,
|
||||
Hashrate, Power, Chip temp, Firmware, CPU, Access and Light. More than seventy
|
||||
other columns are available, grouped as Identity, Firmware and board, Health
|
||||
and status, Performance, Temperature, Cooling, Hardware and Pools.
|
||||
|
||||
- **Columns** opens a checklist: tick to show, drag to reorder, or sort the list
|
||||
alphabetically or by category. *Hide columns with no scanned values* hides
|
||||
columns that are empty for every miner (it resets when the app restarts).
|
||||
- Drag a column header to move it.
|
||||
- Right-click a header to sort by it, auto-size one or all columns, hide it, or
|
||||
open the column chooser.
|
||||
|
||||
Some values worth knowing:
|
||||
|
||||
| Column | Shows |
|
||||
|---|---|
|
||||
| Hashrate | actual/expected, for example `95.0T/96.0T`; the actual part is red at 50% of expected or less, amber around 75%, green at 100% |
|
||||
| Chip temp | hottest chip on each hashboard, for example `77 / 64 / 74`; blue when cool, red at 90 C and above |
|
||||
| Firmware | the firmware family, coloured (Braiins purple, LuxOS gold, VNish green, ePIC light blue, Hiveon orange, Bixbit pink); stock firmware uses the normal text colour |
|
||||
| Pool account / Worker | the pool user split at the first dot |
|
||||
| Board HR / V / freq | per-hashboard hashrate, voltage and frequency |
|
||||
|
||||
A blank cell means the miner did not report that value.
|
||||
|
||||
## Sorting
|
||||
|
||||
Click a header to sort ascending, again for descending, again to clear.
|
||||
|
||||
- **Hashrate** also sorts by *relative* hashrate (actual as a share of
|
||||
expected), shown as `%^` and `%v` in the header.
|
||||
- **Health** sorts by overall health, then by power (`Pwr`), fans (`Fan`) and
|
||||
hashboards (`Brd`). Ascending puts the most broken miners first.
|
||||
|
||||
## Selecting miners
|
||||
|
||||
Click a row to select it; Ctrl-click and Shift-click add to the selection, and
|
||||
you can drag across rows to select a block. The selection follows miners by IP,
|
||||
so it survives rescans. Double-click a row (or press Enter) to open the miner's
|
||||
web page in your browser. Right-click the selection for [actions](05-actions.md).
|
||||
|
||||
## Filters and presets
|
||||
|
||||
**Filter** keeps only the rows that match. Pick a column, then:
|
||||
|
||||
- for numbers: between, =, !=, >, >=, < or <= (blank cells never match);
|
||||
- for text: *is any of* (tick values; `(blank)` matches empty cells), contains,
|
||||
does not contain, begins with, ends with or equals (case does not matter).
|
||||
|
||||
Filters on different columns must all match. **Reset** clears them. Clicking a
|
||||
status card is a quick filter of its own.
|
||||
|
||||
**Presets** saves and loads whole views: column order and visibility, sort and
|
||||
filters. *Default* is built in and cannot be deleted; saving under an existing
|
||||
name replaces it.
|
||||
|
||||
## Zoom and theme
|
||||
|
||||
The slider in the bottom-right corner zooms the table: text, icons and column
|
||||
widths scale together. The window follows the system light or dark theme.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Health, access and light
|
||||
|
||||
## The Health column
|
||||
|
||||
Each miner gets a row of icons, always in the same order, so problems line up
|
||||
across the table:
|
||||
|
||||
1. **Bolt**: the power supply
|
||||
2. **Brain**: the control board
|
||||
3. **Fan**: one icon per fan
|
||||
4. **Chip**: one icon per hashboard
|
||||
|
||||
Hover over any icon to see its details: PSU voltage and current, the fan speed,
|
||||
or a hashboard's actual and expected hashrate, frequency and voltage, and any
|
||||
fault message with its code.
|
||||
|
||||
| Colour | Meaning |
|
||||
|---|---|
|
||||
| Green | healthy |
|
||||
| Amber | working but below par (a slow board, a fan well below the others, a PSU fault while still mining) |
|
||||
| Red | detected but down (a faulted board, a stopped fan, a PSU that is not delivering) |
|
||||
| Grey | expected but not detected or not reachable |
|
||||
| Blue | the miner is paused, so its boards and stopped fans are idle on purpose |
|
||||
|
||||
How each part is judged:
|
||||
|
||||
- **Power** is green when the miner draws power, its PSU fan turns or it is
|
||||
mining; a reported PSU fault makes it amber (still mining) or red.
|
||||
- **Control board** is red for a control-board fault and amber for a
|
||||
miner-wide warning such as a high ambient temperature.
|
||||
- **Fans** are red at 0 rpm and amber below half the speed of the fastest fan.
|
||||
- **Hashboards** follow the status the miner reports for each board. When the
|
||||
firmware names the failing boards, only those turn red. A board the miner
|
||||
cannot see is grey.
|
||||
|
||||
While an action runs on a miner, its Health cell shows progress such as
|
||||
`restarting...` or `refreshing...`.
|
||||
|
||||
## Access
|
||||
|
||||
The padlock shows whether the toolkit can change the miner:
|
||||
|
||||
- **green, open**: changes are possible with the saved credentials;
|
||||
- **red, closed**: view only;
|
||||
- **blank**: not known yet.
|
||||
|
||||
After a scan the padlock is an estimate from what the firmware offers. Use
|
||||
**Check access (auth)** in the right-click menu for a real, read-only login
|
||||
test.
|
||||
|
||||
## Light
|
||||
|
||||
A flashing green-over-red dot means the miner's locate light is on. Turn it on
|
||||
or off with **Flash lights** / **Stop flashing lights**.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Actions
|
||||
|
||||
Right-click one or more selected miners for the actions menu. With several
|
||||
miners selected, labels show the count, for example *Restart (12)*. An action
|
||||
appears only when **every** selected miner's firmware supports it, so the menu
|
||||
changes with the selection.
|
||||
|
||||
| Action | What it does | Changes the miner |
|
||||
|---|---|---|
|
||||
| Open in browser | opens each miner's web page | no |
|
||||
| Refresh | re-reads just these miners | no |
|
||||
| Check access (auth) | tests whether the saved login is accepted | no |
|
||||
| View log (API)... | shows the first selected miner's log (WhatsMiner: its active fault codes) | no |
|
||||
| Restore to stock firmware... | removes aftermarket firmware; see [Restore to stock](07-restore.md) | yes, reboots |
|
||||
| Flash lights / Stop flashing lights | locate light on or off | yes, harmless |
|
||||
| Pause mining / Resume mining | stop or start hashing | yes |
|
||||
| Set tuning %... | tuning level, 0 to 100 | yes |
|
||||
| Set power target... | power target in watts; the prompt shows the current value and the allowed range | yes |
|
||||
| Set hashrate target... | hashrate target in TH/s, for firmware that tunes by hashrate | yes |
|
||||
| Set profile... | pick a firmware profile or preset (only profiles every selected miner has are listed) | yes |
|
||||
| Restart | reboot | yes |
|
||||
| Configure pools... | set up to three pools | yes |
|
||||
| Set timezone... | IANA time zone, for example `America/Edmonton` | yes |
|
||||
| Change password... | new web/API password | yes |
|
||||
| Factory reset... | wipes pools, tuning and network settings and reboots; the miner may come back on a new DHCP address | yes, destructive |
|
||||
|
||||
## Safety
|
||||
|
||||
- Pause, Resume, Restart and Factory reset ask for confirmation. Value prompts
|
||||
(tuning, targets, timezone, password) apply when you confirm the value.
|
||||
- Actions that change miners do not start while a scan is running, including an
|
||||
automatic rescan. Wait for it to finish or press **Pause**. Scans in turn wait
|
||||
for running actions.
|
||||
- Each changed miner is re-read automatically when the action finishes. Results
|
||||
and failures appear in the bottom-right corner of the status bar and in
|
||||
**Settings > Logs**.
|
||||
- If **Change password** succeeds on every selected miner, the saved global
|
||||
login is updated to the new password. If only some succeed, the saved login
|
||||
is left alone and the log says so.
|
||||
|
||||
## Configuring pools
|
||||
|
||||
The pool dialog has three rows: Address, Account, Worker and Password. A row is
|
||||
used only when it has an address and an account. A blank password becomes `x`.
|
||||
The miner's username becomes `account.worker`.
|
||||
|
||||
Each field has a **+** menu with common pool addresses and the values you saved
|
||||
before (**Add new...** edits that list). Worker names can use placeholders that
|
||||
are filled in per miner:
|
||||
|
||||
| Placeholder | Becomes |
|
||||
|---|---|
|
||||
| `{ip1}` to `{ip4}` | one octet of the miner's IP |
|
||||
| `{serial}`, `{mac}` | serial number; MAC without colons |
|
||||
| `{hostname}` | the miner's hostname |
|
||||
| `{brand}`, `{model}`, `{submodel}` | make and model |
|
||||
| `{firmware}`, `{cpu}`, `{cb}` | firmware family, control-board CPU and board |
|
||||
| `{nameplate-hr}` | the model's rated hashrate |
|
||||
|
||||
For example, `rack3-{ip3}-{ip4}` gives `rack3-1-50` for `10.0.1.50`.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Settings and credentials
|
||||
|
||||
**Settings** opens a menu with Credentials, Language and Logs.
|
||||
|
||||
## Credentials
|
||||
|
||||
Miners need a login for anything beyond basic discovery: for some details, and
|
||||
for every action. The Credentials dialog has three parts:
|
||||
|
||||
- **All firmwares** at the top: one username and password tried on every miner.
|
||||
The saved password is never shown; leave the field blank to keep it. Blank
|
||||
username and password clear it.
|
||||
- **SSH (restore)**: the control-board SSH login used to restore Braiins OS to
|
||||
stock (see [SSH login](#ssh-login)).
|
||||
- **One row per firmware**, pre-filled with that firmware's factory default.
|
||||
Change a row to override the login for that firmware only.
|
||||
|
||||
The toolkit tries, in order, the firmware's own row, then the global login,
|
||||
then the firmware's built-in default.
|
||||
|
||||
| Firmware | Factory default (user / password) |
|
||||
|---|---|
|
||||
| AntMiner Stock | root / root |
|
||||
| WhatsMiner Stock | admin / admin |
|
||||
| Braiins | root / root |
|
||||
| VNish | (none) / admin |
|
||||
| LuxOS | root / root |
|
||||
| UMC OS | (none) / letmein |
|
||||
| Marathon | root / root |
|
||||
| VolcMiner Stock | root / ltc@dog |
|
||||
| Elphapex Stock | root / root |
|
||||
| FutureBit Stock | futurebit / futurebit123 |
|
||||
| SealMiner Stock | seal / seal |
|
||||
| Auradine Stock | admin / admin |
|
||||
|
||||
**Reset to defaults** clears every override, the global login and the SSH
|
||||
login at once.
|
||||
|
||||
Logins are stored as plain text in the settings folder, readable only by your
|
||||
user account (Linux file mode 0600; on Windows, your profile folder's
|
||||
permissions).
|
||||
|
||||
### SSH login
|
||||
|
||||
Restoring Braiins to stock runs a command over SSH, using the system `ssh`
|
||||
client (built into Windows 10/11). Set its login in the **SSH (restore)** row
|
||||
of the Credentials dialog. The username defaults to `root`. As with the global
|
||||
login, the saved password is never shown and a blank password keeps it.
|
||||
|
||||
## Language
|
||||
|
||||
English, Chinese, Russian, French, Spanish and Portuguese. The toolbar, cards
|
||||
and column headers switch immediately; menus and dialogs not yet translated
|
||||
stay in English.
|
||||
|
||||
## Logs
|
||||
|
||||
An activity log of scans, actions, errors and exports, newest last, kept for
|
||||
the current session (the last 2000 lines). Times are shown in UTC.
|
||||
|
||||
## Files in the settings folder
|
||||
|
||||
| File | Holds |
|
||||
|---|---|
|
||||
| `scan-ranges.txt` | scan ranges, one per line |
|
||||
| `auto-rescan-secs.txt`, `scan-timeout-secs.txt`, `scan-concurrency.txt` | the three scan numbers |
|
||||
| `scan-credentials.txt` | global login |
|
||||
| `firmware-credentials.txt` | per-firmware logins |
|
||||
| `ssh-credentials.txt` | SSH login |
|
||||
| `presets.json` | saved views |
|
||||
| `language.txt` | UI language |
|
||||
| `pool-addresses.txt`, `pool-accounts.txt`, `pool-workers.txt`, `pool-passwords.txt` | saved pool values |
|
||||
@@ -0,0 +1,18 @@
|
||||
# Restore to stock firmware
|
||||
|
||||
**Restore to stock firmware...** removes aftermarket firmware and returns the
|
||||
miner to the manufacturer's firmware it keeps on board. Nothing is uploaded.
|
||||
The miner reboots, and some firmwares come back on a new address.
|
||||
|
||||
It is offered when the selection includes a supported firmware, and asks for
|
||||
confirmation with the list of miners first.
|
||||
|
||||
| Firmware | How it is removed | Login used |
|
||||
|---|---|---|
|
||||
| VNish (and builds based on it) | web API: unlock, then remove firmware; reboots in seconds | the VNish row in Credentials, else `admin` |
|
||||
| LuxOS | miner API: log on, then uninstall | none |
|
||||
| Braiins OS | SSH: runs the firmware's own `uninstall.sh` | the SSH row in Credentials (see [Settings](06-settings.md#ssh-login)) |
|
||||
|
||||
Miners are restored one at a time. A dropped connection after the command is
|
||||
sent counts as success, because that is the reboot. A refused login counts as
|
||||
a failure and leaves the miner unchanged.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Export
|
||||
|
||||
**Export** saves the scan as a CSV file for spreadsheets or other tools.
|
||||
|
||||
1. Choose the fields to include (all are ticked by default; **All** and
|
||||
**None** help).
|
||||
2. Pick where to save. The suggested name is `alkane-export-YYYYMMDD-HHMMSS.csv`.
|
||||
|
||||
The export contains **every scanned miner**, not just the rows the current
|
||||
filter shows. Per-board temperatures, fan speeds, board status and pools
|
||||
become numbered columns (`board_temp_1_c`, `fan_2_rpm`, `pool_1_url`, ...).
|
||||
|
||||
Values that start with `=`, `+`, `-` or `@` are prefixed with `'` so a
|
||||
spreadsheet treats them as text, not formulas.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Command line and environment
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Effect |
|
||||
|---|---|
|
||||
| `ALKANE_FAKE_SCAN=1` | demo mode: a built-in sample fleet, no network traffic, simulated actions |
|
||||
| `ALKANE_APPEARANCE=light` or `dark` | force the light or dark theme |
|
||||
| `ALKANE_SELFTEST=1` | run the built-in UI self-test on the sample fleet and exit (prints `SELFTEST PASS` or `FAIL`) |
|
||||
| `ALKANE_ACCESS_PROBE="<ip> <make>"` | print whether the saved login can change that miner, then exit |
|
||||
| `ALKANE_LOG_SCAN="<ip> <brand>"` | fetch that miner's log through its API, print the size, then exit |
|
||||
|
||||
On Windows these one-shot modes print to the Command Prompt they are started
|
||||
from.
|
||||
|
||||
## miner_probe
|
||||
|
||||
`miner_probe` is a command-line companion for scripting and diagnosis. These
|
||||
commands only read:
|
||||
|
||||
| Command | Prints |
|
||||
|---|---|
|
||||
| `miner_probe scan <cidr> [<cidr>...]` | discovered miners and their telemetry, as tab-separated values |
|
||||
| `miner_probe hashrate <cidr>...` | raw hashrate and algorithm |
|
||||
| `miner_probe msgs <ip>` | fault messages and per-board data |
|
||||
| `miner_probe tune <ip>` | tuning support and limits |
|
||||
| `miner_probe presets <ip>` | available firmware profiles |
|
||||
| `miner_probe timezone <ip>` | the current time zone |
|
||||
|
||||
Its other commands change miners. It uses the global login from the settings
|
||||
folder, or `ALKANE_PROBE_USER` and `ALKANE_PROBE_PASS`, and
|
||||
`ALKANE_PROBE_CONCURRENCY` (default 128).
|
||||
@@ -0,0 +1,46 @@
|
||||
# Troubleshooting
|
||||
|
||||
**Windows says "Windows protected your PC".** SmartScreen warns about new
|
||||
downloads until a certificate has built up reputation. The publisher shown
|
||||
should be *BlueFlare Energy Solutions Inc.*; click **More info**, then **Run
|
||||
anyway**. If no publisher is shown, do not run the file and download it again
|
||||
from the releases page.
|
||||
|
||||
**A miner is missing.** Check that its address is inside the scan ranges and
|
||||
that it answers on its web page from this computer. On busy or slow networks,
|
||||
raise **Timeout** or lower **Concurrency** in the Scan ranges dialog.
|
||||
|
||||
**An action is missing from the right-click menu.** Actions appear only when
|
||||
every selected miner supports them. Select fewer miners, or only miners with
|
||||
the same firmware.
|
||||
|
||||
**An action does nothing and the status says a scan is in progress.** Changes
|
||||
wait for scans. Press **Pause**, let the scan finish, then try again.
|
||||
|
||||
**Check access says locked.** The saved login is not accepted. Set the right
|
||||
password in **Settings > Credentials**, either for all firmwares or for that
|
||||
firmware's row.
|
||||
|
||||
**Values are blank.** The firmware did not report them, or it needs a login to
|
||||
report them. Try **Check access** and the Credentials dialog.
|
||||
|
||||
**The window is too small or too large.** It opens at most as large as your
|
||||
screen's work area. Use the zoom slider in the status bar to scale the table.
|
||||
|
||||
## Reporting a problem
|
||||
|
||||
**Bug report** in the toolbar, between Export and Settings, files a bug or a
|
||||
feature request with the developers. Choose the type (Bug, UI change or
|
||||
Feature request) and describe it; the first line becomes the title. **Send**
|
||||
shows the issue number when it is filed, and **Open issue** opens it in the
|
||||
browser. If it was not sent, the reason is shown and the text stays in the
|
||||
box.
|
||||
|
||||
A report includes the app version, the operating system, the light or dark
|
||||
appearance, the language and the window size. **Include the recent activity
|
||||
log** adds the newest lines of the Settings > Logs page, with passwords,
|
||||
tokens and similar values removed first; untick it to leave the log out.
|
||||
Reports become public issues on
|
||||
[gitea.bluefla.re](https://gitea.bluefla.re/blueflare/alkane-toolkit/issues),
|
||||
so do not put passwords or customer details in the text. A computer can send
|
||||
five reports an hour.
|
||||
+2
-3
@@ -63,7 +63,7 @@ credential; the script pins the new digest everywhere.
|
||||
|
||||
Release and `-rc` executables are Authenticode-signed with Azure Artifact
|
||||
Signing (formerly Trusted Signing), so Windows and SmartScreen show
|
||||
"Blueflare" as the verified publisher instead of "Unknown publisher".
|
||||
"BlueFlare Energy Solutions Inc." as the verified publisher instead of "Unknown publisher".
|
||||
|
||||
| Piece | Where |
|
||||
|-------|-------|
|
||||
@@ -99,8 +99,7 @@ AZURE_SIGNING_TOKEN=$(az account get-access-token --resource https://codesigning
|
||||
## Native Windows runner
|
||||
|
||||
`windows-native.yml` runs on the self-hosted runner `win11-test-vm`
|
||||
(label `alkane-windows`, host mode) inside the Windows 11 test VM
|
||||
(a local test VM). It downloads the
|
||||
(label `alkane-windows`, host mode) inside a Windows 11 test VM. It downloads the
|
||||
`alkane-toolkit-windows-tests` artifact of the triggering main run, runs every
|
||||
test executable and the UI self-test natively, and never blocks a release:
|
||||
while the VM is off, the job waits for the runner.
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
#!/bin/sh
|
||||
# Build the alkane-toolkit GUI on macOS.
|
||||
# wx-rs upstream supports macOS: its build.rs clones/builds wx 3.2.2.1 into
|
||||
# ./dist (osx-release-build) on first build. Requires Xcode Command Line
|
||||
# Tools. Run this ON a Mac - macOS cannot be linked from Linux.
|
||||
# Build the alkane-toolkit GUI on macOS as one universal binary.
|
||||
#
|
||||
# scripts/build-gui-macos.sh [extra cargo build args]
|
||||
# -> target/universal-apple-darwin/release/alkane-toolkit (arm64 + x86_64)
|
||||
#
|
||||
# Needs the Xcode Command Line Tools, rustup with the aarch64-apple-darwin and
|
||||
# x86_64-apple-darwin targets, and the universal static wx prefix from
|
||||
# scripts/build-wx-macos.sh (WX_MACOS_PREFIX, default ~/.cache/wx-3.3.3-macos).
|
||||
# Each target is built separately against that prefix, then the two slices
|
||||
# are merged with lipo. MACOSX_DEPLOYMENT_TARGET matches the wx build.
|
||||
set -e
|
||||
cd "$(dirname -- "$0")/.."
|
||||
cargo build --release -p alkane-gui
|
||||
echo "binary: target/release/alkane-toolkit (app bundle packaging is follow-up)"
|
||||
PREFIX="${WX_MACOS_PREFIX:-$HOME/.cache/wx-3.3.3-macos}"
|
||||
[ -x "$PREFIX/bin/wx-config" ] || {
|
||||
echo "no wx prefix at $PREFIX; run scripts/build-wx-macos.sh first" >&2; exit 1; }
|
||||
export WX_RS_WXCONFIG="$PREFIX/bin/wx-config"
|
||||
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_MIN:-11.0}"
|
||||
for target in aarch64-apple-darwin x86_64-apple-darwin; do
|
||||
cargo build --release --offline -p alkane-gui --target "$target" "$@"
|
||||
done
|
||||
out=target/universal-apple-darwin/release
|
||||
mkdir -p "$out"
|
||||
lipo -create -output "$out/alkane-toolkit" \
|
||||
target/aarch64-apple-darwin/release/alkane-toolkit \
|
||||
target/x86_64-apple-darwin/release/alkane-toolkit
|
||||
lipo -info "$out/alkane-toolkit"
|
||||
echo "binary: $out/alkane-toolkit"
|
||||
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/sh
|
||||
# Build the vendored wxWidgets 3.3.3 for macOS: wxOSX/Cocoa, static,
|
||||
# monolithic, and universal (arm64 + x86_64) so one prefix serves both Rust
|
||||
# targets. Run on a Mac with the Xcode Command Line Tools.
|
||||
#
|
||||
# scripts/build-wx-macos.sh -> ~/.cache/wx-3.3.3-macos
|
||||
#
|
||||
# Dependency tracking is off: its bootstrap fails with several -arch flags.
|
||||
# MACOSX_MIN (default 11.0) is the oldest macOS the app runs on, for both
|
||||
# slices: the libc++ in current SDKs supports nothing older, and macOS 11 is
|
||||
# also where Apple Silicon starts. Image/zlib/regex/expat libraries are
|
||||
# wx's bundled copies, so the app links only against system frameworks.
|
||||
# The repo's vendor tree stays pristine; the build lives in ~/.cache/wxbuild.
|
||||
set -e
|
||||
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
|
||||
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3-macos"
|
||||
PREFIX="${WX_MACOS_PREFIX:-$HOME/.cache/wx-3.3.3-macos}"
|
||||
MACOSX_MIN="${MACOSX_MIN:-11.0}"
|
||||
JOBS="${JOBS:-$(sysctl -n hw.ncpu)}"
|
||||
[ -d "$SRC" ] || { echo "thirdparty wxWidgets tree missing: $SRC" >&2; exit 1; }
|
||||
rm -rf "$BUILD"
|
||||
mkdir -p "$HOME/.cache/wxbuild"
|
||||
cp -R "$SRC" "$BUILD"
|
||||
trap 'rm -rf "$BUILD"' 0
|
||||
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
|
||||
mkdir -p "$BUILD/build-macos"
|
||||
cd "$BUILD/build-macos"
|
||||
sh ../configure --prefix="$PREFIX" --with-osx_cocoa \
|
||||
--disable-shared --enable-monolithic \
|
||||
--enable-universal_binary=arm64,x86_64 \
|
||||
--with-macosx-version-min="$MACOSX_MIN" \
|
||||
--disable-dependency-tracking \
|
||||
--with-libpng=builtin --with-libjpeg=builtin --without-libtiff \
|
||||
--with-zlib=builtin --with-expat=builtin --with-regex=builtin \
|
||||
--without-liblzma --without-libcurl \
|
||||
--with-opengl=no --disable-stc --disable-webview --disable-mediactrl \
|
||||
--disable-tests
|
||||
make -j"$JOBS"
|
||||
make install
|
||||
lib=$(ls "$PREFIX"/lib/libwx_osx_cocoau-3.3*.a | head -1)
|
||||
lipo -info "$lib"
|
||||
echo "installed: $PREFIX ($lib)"
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
Subject: [PATCH 0034] vnish: keep the reported boards and infer the algorithm for unknown models
|
||||
|
||||
Field report 2026-11-03: VNish Antminer S19 (88) units showed no hashboard
|
||||
icons while hashing. VNish reports the model as "Antminer S19 (88)", which is
|
||||
not in asic-rs' alias table, so it parses to AntMinerModel::Unknown with no
|
||||
hardware table. parse_hashboards sized the board list from that table
|
||||
(board_count() = None -> 0 boards) and dropped all three live chains the
|
||||
miner reports in /summary. The same Unknown model also got
|
||||
HashAlgorithm::Unknown, so its hashrate was bucketed as "Unknown Hashrate".
|
||||
|
||||
- VNish v1.2.x and v1.3.x parse_hashboards: when the model has no hardware
|
||||
table, size the boards from the highest 1-based chain id the miner reports
|
||||
(a dead middle board keeps its slot). Known models are unchanged.
|
||||
- infer_antminer_algo (family letter: S/T -> SHA-256, L -> Scrypt,
|
||||
Z -> Equihash, ambiguous -> Unknown) moves from the stock v2020 backend
|
||||
into asic-rs-makes-antminer as a public function; the stock backend and
|
||||
both VNish backends now use it for models the table cannot place.
|
||||
|
||||
Tests: unknown_model_keeps_the_reported_chains (both VNish backends, chain
|
||||
data from the live 10.4.0.179 unit); the existing
|
||||
unknown_models_infer_algo_from_family_letter still passes against the moved
|
||||
helper. Live-verified read-only on all 13 fleet S19 (88) units (10.4.x,
|
||||
10.7.1.190): three hashboard icons each, per-board state intact (e.g. one red
|
||||
board on 10.4.1.111), and the KPI reads "SHA-256 Hashrate".
|
||||
|
||||
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
index 71195737..872bd1de 100644
|
||||
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
|
||||
@@ -202,27 +202,7 @@ fn miner_conf_with_fan_config(miner_conf: &Value, config: FanConfig) -> Value {
|
||||
Value::Object(payload)
|
||||
}
|
||||
|
||||
-/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
-/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
-/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
-/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
-/// X11) is left Unknown rather than guessed wrong.
|
||||
-fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
- let upper = model.to_ascii_uppercase();
|
||||
- let name = upper
|
||||
- .strip_prefix("ANTMINER ")
|
||||
- .unwrap_or(&upper)
|
||||
- .trim_start();
|
||||
- match name.chars().next() {
|
||||
- // Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
- Some('Z') => HashAlgorithm::Equihash,
|
||||
- // L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
- Some('L') => HashAlgorithm::Scrypt,
|
||||
- // S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
- Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
- _ => HashAlgorithm::Unknown,
|
||||
- }
|
||||
-}
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
|
||||
impl AntMinerV2020 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
diff --git a/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs b/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
index 2c14f217..3c8e1bee 100644
|
||||
--- a/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-vnish/src/backends/v1_2_0/mod.rs
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
- device::DeviceInfo,
|
||||
+ device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV120 {
|
||||
impl VnishV120 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
- let algo = model.hash_algorithm();
|
||||
+ // A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
+ // resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
+ // as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
+ // the stock backend does.
|
||||
+ let algo = match model.hash_algorithm() {
|
||||
+ HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
+ known => known,
|
||||
+ };
|
||||
VnishV120 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -509,8 +517,24 @@ impl GetHashboards for VnishV120 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
- let mut hashboards: Vec<BoardData> =
|
||||
- (0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
+ // The model's hardware table gives the board count. For a model asic-rs
|
||||
+ // does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
+ // sizing from it dropped every live chain -- the boards then vanished
|
||||
+ // from the data although the miner reports them. Fall back to what the
|
||||
+ // miner reports: the highest 1-based chain id, so a dead middle board
|
||||
+ // still keeps its slot.
|
||||
+ let reported_boards = all_chains
|
||||
+ .iter()
|
||||
+ .filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
+ .max()
|
||||
+ .unwrap_or(0) as usize;
|
||||
+ let board_count = self
|
||||
+ .device_info
|
||||
+ .hardware
|
||||
+ .board_count()
|
||||
+ .map(|n| n as usize)
|
||||
+ .unwrap_or(reported_boards);
|
||||
+ let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1524,4 +1548,42 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
+
|
||||
+ /// Same as the 1.3.x backend: a model with no hardware table (VNish's
|
||||
+ /// "Antminer S19 (88)") must keep the chains the miner reports instead of
|
||||
+ /// sizing the board list to zero. Live 1.2.7 units (e.g. 10.4.1.111) run it.
|
||||
+ #[tokio::test]
|
||||
+ async fn unknown_model_keeps_the_reported_chains() {
|
||||
+ let miner = VnishV120::new(
|
||||
+ IpAddr::from([127, 0, 0, 1]),
|
||||
+ AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
+ );
|
||||
+ let mut results = HashMap::new();
|
||||
+ results.insert(
|
||||
+ MinerCommand::WebAPI {
|
||||
+ command: "info",
|
||||
+ parameters: None,
|
||||
+ },
|
||||
+ json!({ "miner": "Antminer S19 (88)", "hr_measure": "GH/s", "fw_version": "1.2.7" }),
|
||||
+ );
|
||||
+ results.insert(
|
||||
+ MinerCommand::WebAPI {
|
||||
+ command: "summary",
|
||||
+ parameters: None,
|
||||
+ },
|
||||
+ json!({ "miner": { "hr_realtime": 82600.0, "chains": [
|
||||
+ { "id": 1, "hashrate_rt": 27537.83 },
|
||||
+ { "id": 2, "hashrate_rt": 27511.20 },
|
||||
+ { "id": 3, "hashrate_rt": 27601.04 }
|
||||
+ ] } }),
|
||||
+ );
|
||||
+ let mock_api = MockAPIClient::new(results);
|
||||
+ let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
+ let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
+
|
||||
+ assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
+ // ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
+ assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
+ assert!(miner_data.hashboards.iter().all(|b| b.hashrate.is_some()));
|
||||
+ }
|
||||
}
|
||||
diff --git a/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs b/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
index e6247923..0e009f1c 100644
|
||||
--- a/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
+++ b/vendor/asic-rs-firmwares-vnish/src/backends/v1_3_0/mod.rs
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
+use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
- device::DeviceInfo,
|
||||
+ device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV130 {
|
||||
impl VnishV130 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
- let algo = model.hash_algorithm();
|
||||
+ // A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
+ // resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
+ // as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
+ // the stock backend does.
|
||||
+ let algo = match model.hash_algorithm() {
|
||||
+ HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
+ known => known,
|
||||
+ };
|
||||
VnishV130 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -516,8 +524,24 @@ impl GetHashboards for VnishV130 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
- let mut hashboards: Vec<BoardData> =
|
||||
- (0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
+ // The model's hardware table gives the board count. For a model asic-rs
|
||||
+ // does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
+ // sizing from it dropped every live chain -- the boards then vanished
|
||||
+ // from the data although the miner reports them. Fall back to what the
|
||||
+ // miner reports: the highest 1-based chain id, so a dead middle board
|
||||
+ // still keeps its slot.
|
||||
+ let reported_boards = all_chains
|
||||
+ .iter()
|
||||
+ .filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
+ .max()
|
||||
+ .unwrap_or(0) as usize;
|
||||
+ let board_count = self
|
||||
+ .device_info
|
||||
+ .hardware
|
||||
+ .board_count()
|
||||
+ .map(|n| n as usize)
|
||||
+ .unwrap_or(reported_boards);
|
||||
+ let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1661,4 +1685,46 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
+
|
||||
+ /// A model asic-rs has no hardware table for -- VNish reports the 88-chip
|
||||
+ /// S19 as "Antminer S19 (88)" -- must still surface the boards the miner
|
||||
+ /// reports. Sizing the board list from the (absent) table dropped all
|
||||
+ /// three live chains, so the GUI drew no hashboard icons for a hashing
|
||||
+ /// miner. Chain values match the live 10.4.0.179 unit.
|
||||
+ #[tokio::test]
|
||||
+ async fn unknown_model_keeps_the_reported_chains() {
|
||||
+ let miner = VnishV130::new(
|
||||
+ IpAddr::from([127, 0, 0, 1]),
|
||||
+ AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
+ );
|
||||
+ let mut results = HashMap::new();
|
||||
+ results.insert(
|
||||
+ web("info"),
|
||||
+ json!({ "miner": "Antminer S19 (88)", "model": "s19-88", "hr_measure": "GH/s" }),
|
||||
+ );
|
||||
+ results.insert(
|
||||
+ web("summary"),
|
||||
+ json!({
|
||||
+ "miner": {
|
||||
+ "hr_realtime": 82600.0,
|
||||
+ "chains": [
|
||||
+ { "id": 1, "hashrate_rt": 27537.83, "chip_statuses": { "grey": 88 } },
|
||||
+ { "id": 2, "hashrate_rt": 27511.20, "chip_statuses": { "grey": 88 } },
|
||||
+ { "id": 3, "hashrate_rt": 27601.04, "chip_statuses": { "grey": 88 } }
|
||||
+ ]
|
||||
+ }
|
||||
+ }),
|
||||
+ );
|
||||
+ let mock_api = MockAPIClient::new(results);
|
||||
+ let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
+ let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
+
|
||||
+ assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
+ // ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
+ assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
+ for (i, board) in miner_data.hashboards.iter().enumerate() {
|
||||
+ assert_eq!(board.position as usize, i);
|
||||
+ assert!(board.hashrate.is_some(), "board {i} keeps its live hashrate");
|
||||
+ }
|
||||
+ }
|
||||
}
|
||||
diff --git a/vendor/asic-rs-makes-antminer/src/models.rs b/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
index f52639fe..e3185089 100644
|
||||
--- a/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
+++ b/vendor/asic-rs-makes-antminer/src/models.rs
|
||||
@@ -201,6 +201,29 @@ pub enum AntMinerModel {
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
+/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
+/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
+/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
+/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
+/// X11) is left Unknown rather than guessed wrong. Shared by every firmware
|
||||
+/// backend that runs on Antminer hardware (stock, VNish).
|
||||
+pub fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
+ let upper = model.to_ascii_uppercase();
|
||||
+ let name = upper
|
||||
+ .strip_prefix("ANTMINER ")
|
||||
+ .unwrap_or(&upper)
|
||||
+ .trim_start();
|
||||
+ match name.chars().next() {
|
||||
+ // Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
+ Some('Z') => HashAlgorithm::Equihash,
|
||||
+ // L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
+ Some('L') => HashAlgorithm::Scrypt,
|
||||
+ // S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
+ Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
+ _ => HashAlgorithm::Unknown,
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
impl FromStr for AntMinerModel {
|
||||
type Err = ModelSelectionError;
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
Subject: [PATCH 0009] macOS: wxOSX through wx-config, logical sizes, clang runtime
|
||||
|
||||
--- a/build.rs
|
||||
+++ b/build.rs
|
||||
@@ -42,12 +42,12 @@
|
||||
target_os() == "linux"
|
||||
}
|
||||
|
||||
-// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
|
||||
-// mingw-w64, natively or cross from Linux) both build against a wx prefix
|
||||
-// described by its wx-config script, so they share one code path. Upstream's
|
||||
-// MSVC/nmake and macOS download-and-build paths are left as they were.
|
||||
+// alkane-toolkit patch: Linux (wxGTK), macOS (wxOSX/Cocoa, universal static
|
||||
+// build) and Windows/GNU (wxMSW built with mingw-w64, natively or cross from
|
||||
+// Linux) all build against a wx prefix described by its wx-config script, so
|
||||
+// they share one code path. Upstream's MSVC/nmake path is left as it was.
|
||||
fn uses_wx_config() -> bool {
|
||||
- is_linux() || (is_windows() && !is_msvc())
|
||||
+ is_linux() || is_osx() || (is_windows() && !is_msvc())
|
||||
}
|
||||
|
||||
fn is_stub() -> bool {
|
||||
@@ -278,7 +278,14 @@
|
||||
build.cpp(true)
|
||||
.file("cpp_src/wxbridge.cpp")
|
||||
.file("cpp_src/widgets_bridge.cpp");
|
||||
- for f in cxxflags.split_whitespace() {
|
||||
+ let mut flags = cxxflags.split_whitespace();
|
||||
+ while let Some(f) = flags.next() {
|
||||
+ // A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
|
||||
+ // one target at a time and cc adds that target's own -arch.
|
||||
+ if is_osx() && f == "-arch" {
|
||||
+ flags.next();
|
||||
+ continue;
|
||||
+ }
|
||||
build.flag(f);
|
||||
}
|
||||
if is_linux() {
|
||||
@@ -308,7 +315,53 @@
|
||||
}
|
||||
build.compile("wxbridge");
|
||||
|
||||
- for flag in libs.split_whitespace() {
|
||||
+ if is_osx() {
|
||||
+ // wxOSX's Objective-C uses @available, which calls
|
||||
+ // ___isPlatformVersionAtLeast from clang's compiler runtime. clang
|
||||
+ // links that runtime itself, but rustc drives the link without it.
|
||||
+ let resource_dir = Command::new("clang")
|
||||
+ .arg("-print-resource-dir")
|
||||
+ .output()
|
||||
+ .ok()
|
||||
+ .filter(|o| o.status.success())
|
||||
+ .and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
+ .map(|s| s.trim().to_string())
|
||||
+ .ok_or("wx-rs: cannot ask clang for its resource directory")?;
|
||||
+ let rt = Path::new(&resource_dir).join("lib").join("darwin");
|
||||
+ if !rt.join("libclang_rt.osx.a").exists() {
|
||||
+ return Err(format!("wx-rs: no libclang_rt.osx.a in {}", rt.display()).into());
|
||||
+ }
|
||||
+ println!("cargo:rustc-link-search=native={}", rt.display());
|
||||
+ println!("cargo:rustc-link-lib=static=clang_rt.osx");
|
||||
+ }
|
||||
+
|
||||
+ let mut lib_flags = libs.split_whitespace();
|
||||
+ while let Some(flag) = lib_flags.next() {
|
||||
+ if is_osx() {
|
||||
+ match flag {
|
||||
+ "-arch" => {
|
||||
+ lib_flags.next();
|
||||
+ continue;
|
||||
+ }
|
||||
+ "-framework" => {
|
||||
+ if let Some(name) = lib_flags.next() {
|
||||
+ println!("cargo:rustc-link-lib=framework={}", name);
|
||||
+ }
|
||||
+ continue;
|
||||
+ }
|
||||
+ "-weak_framework" => {
|
||||
+ if let Some(name) = lib_flags.next() {
|
||||
+ println!("cargo:rustc-link-arg=-Wl,-weak_framework,{}", name);
|
||||
+ }
|
||||
+ continue;
|
||||
+ }
|
||||
+ _ if flag.starts_with("-Wl,") => {
|
||||
+ println!("cargo:rustc-link-arg={}", flag);
|
||||
+ continue;
|
||||
+ }
|
||||
+ _ => {}
|
||||
+ }
|
||||
+ }
|
||||
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
|
||||
// static wx builds: wx-config emits the archive as a full path
|
||||
let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
|
||||
--- a/cpp_src/wxbridge.cpp
|
||||
+++ b/cpp_src/wxbridge.cpp
|
||||
@@ -492,21 +492,12 @@
|
||||
|
||||
// The logical window size
|
||||
Size get_client_size() {
|
||||
-#ifdef __APPLE__
|
||||
- int status_bar_height;
|
||||
- if (wxGetApp().frame->GetStatusBar()) {
|
||||
- status_bar_height = wxGetApp().frame->GetStatusBar()->GetRect().height;
|
||||
- } else {
|
||||
- status_bar_height = 0;
|
||||
- }
|
||||
- float scale_factor = wxGetApp().frame->GetDPIScaleFactor();
|
||||
- wxSize s = wxGetApp().frame->GetClientSize();
|
||||
- struct Size sz = {s.x * scale_factor, (s.y + status_bar_height) * scale_factor};
|
||||
- return sz;
|
||||
-#elif defined(__linux__)
|
||||
- // alkane-toolkit patch: wxGTK3 path (upstream only knew Apple vs Windows)
|
||||
+#if defined(__linux__) || defined(__APPLE__)
|
||||
+ // alkane-toolkit patch: wxGTK3 and wxOSX both report logical (DIP) sizes,
|
||||
+ // like every other bridge size. Upstream's Apple branch scaled to physical
|
||||
+ // pixels through a float -> int narrowing current clang rejects.
|
||||
wxSize s = wxGetApp().frame->GetClientSize();
|
||||
- return Size {(unsigned int)s.x, (unsigned int)s.y};
|
||||
+ return Size {s.x, s.y};
|
||||
#else
|
||||
HWND hwnd = (HWND) wxGetApp().frame->GetHandle();
|
||||
RECT rect;
|
||||
@@ -559,15 +550,10 @@
|
||||
}
|
||||
|
||||
Size get_mouse_position(wxMouseEvent &event) {
|
||||
-#ifdef __APPLE__
|
||||
- wxPoint p = event.GetPosition();
|
||||
- float scale_factor = wxGetApp().frame->GetDPIScaleFactor();
|
||||
- struct Size s = {p.x * scale_factor, p.y * scale_factor};
|
||||
- return s;
|
||||
-#else
|
||||
+ // alkane-toolkit patch: logical (DIP) coordinates on every platform,
|
||||
+ // matching get_client_size (upstream scaled them on Apple).
|
||||
wxPoint p = event.GetPosition();
|
||||
return Size {p.x, p.y};
|
||||
-#endif
|
||||
}
|
||||
|
||||
int get_mouse_wheel_rotation(wxMouseEvent &event) {
|
||||
@@ -0,0 +1,162 @@
|
||||
Subject: [PATCH 0010] macOS: native alternating rows, theme text colour, self-test snapshot
|
||||
|
||||
--- a/build.rs
|
||||
+++ b/build.rs
|
||||
@@ -278,6 +278,12 @@
|
||||
build.cpp(true)
|
||||
.file("cpp_src/wxbridge.cpp")
|
||||
.file("cpp_src/widgets_bridge.cpp");
|
||||
+ if is_osx() {
|
||||
+ // Cocoa calls wx does not wrap (native alternating rows, self-test
|
||||
+ // snapshot); clang compiles .mm as Objective-C++.
|
||||
+ println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
|
||||
+ build.file("cpp_src/osx_native.mm");
|
||||
+ }
|
||||
let mut flags = cxxflags.split_whitespace();
|
||||
while let Some(f) = flags.next() {
|
||||
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -597,7 +597,11 @@
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
} else {
|
||||
+#ifdef __WXOSX__
|
||||
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
|
||||
+#else
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
+#endif
|
||||
}
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
continue;
|
||||
@@ -688,6 +692,11 @@
|
||||
(unsigned char)(c.blue * 255.0 + 0.5));
|
||||
}
|
||||
}
|
||||
+#elif defined(__WXOSX__)
|
||||
+ // The DC arrives with the control's foreground colour, which is not the
|
||||
+ // theme-aware label colour native cells use; take the list text colour so
|
||||
+ // uncoloured segments follow light/dark like the native columns.
|
||||
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
|
||||
#endif
|
||||
return wxColour();
|
||||
}
|
||||
@@ -1463,8 +1472,21 @@
|
||||
|
||||
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
|
||||
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
|
||||
+#ifdef __WXOSX__
|
||||
+extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
|
||||
+#endif
|
||||
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
|
||||
+#ifdef __WXOSX__
|
||||
+ // wxOSX draws custom cells without clipping them to the cell, so the
|
||||
+ // renderer's over-sized background fill (which GTK/MSW clip) painted over
|
||||
+ // neighbouring cells and hid their text until a row was selected. Use the
|
||||
+ // table's native alternating rows instead: AppKit paints them under every
|
||||
+ // cell, in the theme's colours, and no row carries a background attribute.
|
||||
+ dvlc_store(win)->zebra = wxColour();
|
||||
+ wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
|
||||
+#else
|
||||
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
|
||||
+#endif
|
||||
}
|
||||
|
||||
// The model-row index of the first (top) visible row, or -1 if none. Used to
|
||||
--- a/cpp_src/osx_native.mm
|
||||
+++ b/cpp_src/osx_native.mm
|
||||
@@ -0,0 +1,60 @@
|
||||
+// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
|
||||
+// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
|
||||
+
|
||||
+#include <wx/wx.h>
|
||||
+#include <wx/dataview.h>
|
||||
+
|
||||
+#import <Cocoa/Cocoa.h>
|
||||
+
|
||||
+// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
|
||||
+// enclosing NSScrollView.
|
||||
+static NSTableView* TableOf(wxWindow* win) {
|
||||
+ if (!win) return nil;
|
||||
+ id h = (id)win->GetHandle();
|
||||
+ if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
|
||||
+ if ([h isKindOfClass:[NSScrollView class]]) {
|
||||
+ id doc = [(NSScrollView*)h documentView];
|
||||
+ if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
|
||||
+ }
|
||||
+ return nil;
|
||||
+}
|
||||
+
|
||||
+extern "C" {
|
||||
+
|
||||
+// Native alternating-row backgrounds. AppKit paints them under every cell,
|
||||
+// custom-drawn ones included, in the theme's own colours (light and dark), so
|
||||
+// custom renderers never paint row backgrounds on macOS.
|
||||
+void wxbr_osx_set_alternating_rows(void* win, int on) {
|
||||
+ NSTableView* tv = TableOf((wxWindow*)win);
|
||||
+ if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
|
||||
+}
|
||||
+
|
||||
+// Write a PNG of a top-level window's content, rendered by the app itself
|
||||
+// (no screen-recording permission needed). Used by the self-test with
|
||||
+// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
|
||||
+// success.
|
||||
+int wxbr_osx_snapshot(void* win, const char* path) {
|
||||
+ wxWindow* w = (wxWindow*)win;
|
||||
+ if (!w || !path) return 0;
|
||||
+ wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
|
||||
+ if (!tlw) return 0;
|
||||
+ tlw->Show();
|
||||
+ tlw->Raise();
|
||||
+ // Let the window lay out and paint before capturing it.
|
||||
+ for (int i = 0; i < 30; ++i) {
|
||||
+ wxYield();
|
||||
+ wxMilliSleep(30);
|
||||
+ }
|
||||
+ NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
+ NSView* view = [nsw contentView];
|
||||
+ if (!view) return 0;
|
||||
+ NSRect rect = [view bounds];
|
||||
+ NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
+ if (!rep) return 0;
|
||||
+ [view cacheDisplayInRect:rect toBitmapImageRep:rep];
|
||||
+ NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
+ if (!png) return 0;
|
||||
+ return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
|
||||
+}
|
||||
+
|
||||
+}
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -107,6 +107,8 @@
|
||||
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
|
||||
pub fn wxbr_set_appearance_system();
|
||||
pub fn wxbr_is_dark() -> c_int;
|
||||
+ #[cfg(target_os = "macos")]
|
||||
+ pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
|
||||
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
|
||||
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
@@ -271,6 +273,22 @@
|
||||
unsafe { notsafe::wxbr_is_dark() != 0 }
|
||||
}
|
||||
|
||||
+/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
|
||||
+/// the window and lets it paint first). macOS only, for the self-test's
|
||||
+/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
|
||||
+pub fn snapshot_png(win: &Widget, path: &str) -> bool {
|
||||
+ #[cfg(target_os = "macos")]
|
||||
+ {
|
||||
+ let Ok(p) = CString::new(path) else { return false };
|
||||
+ unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
|
||||
+ }
|
||||
+ #[cfg(not(target_os = "macos"))]
|
||||
+ {
|
||||
+ let _ = (win, path);
|
||||
+ false
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
|
||||
/// 3=button face, 4=grey text. Returns (r, g, b).
|
||||
pub fn system_color(which: i32) -> (u8, u8, u8) {
|
||||
@@ -0,0 +1,17 @@
|
||||
Subject: [PATCH 0011] macOS self-test snapshot includes the window background
|
||||
|
||||
--- a/cpp_src/osx_native.mm
|
||||
+++ b/cpp_src/osx_native.mm
|
||||
@@ -46,7 +46,11 @@
|
||||
wxMilliSleep(30);
|
||||
}
|
||||
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
- NSView* view = [nsw contentView];
|
||||
+ // The content view's superview (the window's frame view) also draws the
|
||||
+ // window background and title bar. The content view alone leaves every
|
||||
+ // area the app's panels do not paint transparent, which read as white.
|
||||
+ NSView* view = [[nsw contentView] superview];
|
||||
+ if (!view) view = [nsw contentView];
|
||||
if (!view) return 0;
|
||||
NSRect rect = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
Vendored
+3
@@ -27,6 +27,9 @@ later changes go in new patches.
|
||||
| 0006 | Build: platform from the target, not the host; Windows/GNU via `wx-config` |
|
||||
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
|
||||
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
|
||||
| 0009 | macOS: wxOSX (universal static) through `wx-config`, logical sizes on Apple, clang compiler runtime for `@available` |
|
||||
| 0010 | macOS table: native alternating rows instead of the unclipped custom-cell background fill (it hid neighbouring cells' text), theme-aware text colour, `osx_native.mm`, self-test window snapshot |
|
||||
| 0011 | macOS self-test snapshot captures the window's frame view, so areas the app does not paint show the real window background instead of transparency |
|
||||
|
||||
History: the round 19 health-tooltip fix (GTK tip area converted from
|
||||
bin-window to widget coordinates) used to be a separate patch on top of an
|
||||
|
||||
+66
-7
@@ -42,12 +42,12 @@ fn is_linux() -> bool {
|
||||
target_os() == "linux"
|
||||
}
|
||||
|
||||
// alkane-toolkit patch: Linux (wxGTK) and Windows/GNU (wxMSW built with
|
||||
// mingw-w64, natively or cross from Linux) both build against a wx prefix
|
||||
// described by its wx-config script, so they share one code path. Upstream's
|
||||
// MSVC/nmake and macOS download-and-build paths are left as they were.
|
||||
// alkane-toolkit patch: Linux (wxGTK), macOS (wxOSX/Cocoa, universal static
|
||||
// build) and Windows/GNU (wxMSW built with mingw-w64, natively or cross from
|
||||
// Linux) all build against a wx prefix described by its wx-config script, so
|
||||
// they share one code path. Upstream's MSVC/nmake path is left as it was.
|
||||
fn uses_wx_config() -> bool {
|
||||
is_linux() || (is_windows() && !is_msvc())
|
||||
is_linux() || is_osx() || (is_windows() && !is_msvc())
|
||||
}
|
||||
|
||||
fn is_stub() -> bool {
|
||||
@@ -278,7 +278,20 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
build.cpp(true)
|
||||
.file("cpp_src/wxbridge.cpp")
|
||||
.file("cpp_src/widgets_bridge.cpp");
|
||||
for f in cxxflags.split_whitespace() {
|
||||
if is_osx() {
|
||||
// Cocoa calls wx does not wrap (native alternating rows, self-test
|
||||
// snapshot); clang compiles .mm as Objective-C++.
|
||||
println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
|
||||
build.file("cpp_src/osx_native.mm");
|
||||
}
|
||||
let mut flags = cxxflags.split_whitespace();
|
||||
while let Some(f) = flags.next() {
|
||||
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
|
||||
// one target at a time and cc adds that target's own -arch.
|
||||
if is_osx() && f == "-arch" {
|
||||
flags.next();
|
||||
continue;
|
||||
}
|
||||
build.flag(f);
|
||||
}
|
||||
if is_linux() {
|
||||
@@ -308,7 +321,53 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
build.compile("wxbridge");
|
||||
|
||||
for flag in libs.split_whitespace() {
|
||||
if is_osx() {
|
||||
// wxOSX's Objective-C uses @available, which calls
|
||||
// ___isPlatformVersionAtLeast from clang's compiler runtime. clang
|
||||
// links that runtime itself, but rustc drives the link without it.
|
||||
let resource_dir = Command::new("clang")
|
||||
.arg("-print-resource-dir")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.map(|s| s.trim().to_string())
|
||||
.ok_or("wx-rs: cannot ask clang for its resource directory")?;
|
||||
let rt = Path::new(&resource_dir).join("lib").join("darwin");
|
||||
if !rt.join("libclang_rt.osx.a").exists() {
|
||||
return Err(format!("wx-rs: no libclang_rt.osx.a in {}", rt.display()).into());
|
||||
}
|
||||
println!("cargo:rustc-link-search=native={}", rt.display());
|
||||
println!("cargo:rustc-link-lib=static=clang_rt.osx");
|
||||
}
|
||||
|
||||
let mut lib_flags = libs.split_whitespace();
|
||||
while let Some(flag) = lib_flags.next() {
|
||||
if is_osx() {
|
||||
match flag {
|
||||
"-arch" => {
|
||||
lib_flags.next();
|
||||
continue;
|
||||
}
|
||||
"-framework" => {
|
||||
if let Some(name) = lib_flags.next() {
|
||||
println!("cargo:rustc-link-lib=framework={}", name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
"-weak_framework" => {
|
||||
if let Some(name) = lib_flags.next() {
|
||||
println!("cargo:rustc-link-arg=-Wl,-weak_framework,{}", name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ if flag.starts_with("-Wl,") => {
|
||||
println!("cargo:rustc-link-arg={}", flag);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if flag.ends_with(".a") && Path::new(flag).is_absolute() {
|
||||
// static wx builds: wx-config emits the archive as a full path
|
||||
let file = Path::new(flag).file_name().and_then(|f| f.to_str()).unwrap_or(flag);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
|
||||
// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
|
||||
|
||||
#include <wx/wx.h>
|
||||
#include <wx/dataview.h>
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
|
||||
// enclosing NSScrollView.
|
||||
static NSTableView* TableOf(wxWindow* win) {
|
||||
if (!win) return nil;
|
||||
id h = (id)win->GetHandle();
|
||||
if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
|
||||
if ([h isKindOfClass:[NSScrollView class]]) {
|
||||
id doc = [(NSScrollView*)h documentView];
|
||||
if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
// Native alternating-row backgrounds. AppKit paints them under every cell,
|
||||
// custom-drawn ones included, in the theme's own colours (light and dark), so
|
||||
// custom renderers never paint row backgrounds on macOS.
|
||||
void wxbr_osx_set_alternating_rows(void* win, int on) {
|
||||
NSTableView* tv = TableOf((wxWindow*)win);
|
||||
if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
|
||||
}
|
||||
|
||||
// Write a PNG of a top-level window's content, rendered by the app itself
|
||||
// (no screen-recording permission needed). Used by the self-test with
|
||||
// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
|
||||
// success.
|
||||
int wxbr_osx_snapshot(void* win, const char* path) {
|
||||
wxWindow* w = (wxWindow*)win;
|
||||
if (!w || !path) return 0;
|
||||
wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
|
||||
if (!tlw) return 0;
|
||||
tlw->Show();
|
||||
tlw->Raise();
|
||||
// Let the window lay out and paint before capturing it.
|
||||
for (int i = 0; i < 30; ++i) {
|
||||
wxYield();
|
||||
wxMilliSleep(30);
|
||||
}
|
||||
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
// The content view's superview (the window's frame view) also draws the
|
||||
// window background and title bar. The content view alone leaves every
|
||||
// area the app's panels do not paint transparent, which read as white.
|
||||
NSView* view = [[nsw contentView] superview];
|
||||
if (!view) view = [nsw contentView];
|
||||
if (!view) return 0;
|
||||
NSRect rect = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
if (!rep) return 0;
|
||||
[view cacheDisplayInRect:rect toBitmapImageRep:rep];
|
||||
NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
if (!png) return 0;
|
||||
return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -597,7 +597,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
} else {
|
||||
#ifdef __WXOSX__
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
|
||||
#else
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
#endif
|
||||
}
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
continue;
|
||||
@@ -688,6 +692,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
(unsigned char)(c.blue * 255.0 + 0.5));
|
||||
}
|
||||
}
|
||||
#elif defined(__WXOSX__)
|
||||
// The DC arrives with the control's foreground colour, which is not the
|
||||
// theme-aware label colour native cells use; take the list text colour so
|
||||
// uncoloured segments follow light/dark like the native columns.
|
||||
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
|
||||
#endif
|
||||
return wxColour();
|
||||
}
|
||||
@@ -1463,8 +1472,21 @@ void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
|
||||
|
||||
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
|
||||
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
|
||||
#ifdef __WXOSX__
|
||||
extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
|
||||
#endif
|
||||
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
|
||||
#ifdef __WXOSX__
|
||||
// wxOSX draws custom cells without clipping them to the cell, so the
|
||||
// renderer's over-sized background fill (which GTK/MSW clip) painted over
|
||||
// neighbouring cells and hid their text until a row was selected. Use the
|
||||
// table's native alternating rows instead: AppKit paints them under every
|
||||
// cell, in the theme's colours, and no row carries a background attribute.
|
||||
dvlc_store(win)->zebra = wxColour();
|
||||
wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
|
||||
#else
|
||||
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
|
||||
#endif
|
||||
}
|
||||
|
||||
// The model-row index of the first (top) visible row, or -1 if none. Used to
|
||||
|
||||
+7
-21
@@ -492,21 +492,12 @@ extern "C" {
|
||||
|
||||
// The logical window size
|
||||
Size get_client_size() {
|
||||
#ifdef __APPLE__
|
||||
int status_bar_height;
|
||||
if (wxGetApp().frame->GetStatusBar()) {
|
||||
status_bar_height = wxGetApp().frame->GetStatusBar()->GetRect().height;
|
||||
} else {
|
||||
status_bar_height = 0;
|
||||
}
|
||||
float scale_factor = wxGetApp().frame->GetDPIScaleFactor();
|
||||
wxSize s = wxGetApp().frame->GetClientSize();
|
||||
struct Size sz = {s.x * scale_factor, (s.y + status_bar_height) * scale_factor};
|
||||
return sz;
|
||||
#elif defined(__linux__)
|
||||
// alkane-toolkit patch: wxGTK3 path (upstream only knew Apple vs Windows)
|
||||
#if defined(__linux__) || defined(__APPLE__)
|
||||
// alkane-toolkit patch: wxGTK3 and wxOSX both report logical (DIP) sizes,
|
||||
// like every other bridge size. Upstream's Apple branch scaled to physical
|
||||
// pixels through a float -> int narrowing current clang rejects.
|
||||
wxSize s = wxGetApp().frame->GetClientSize();
|
||||
return Size {(unsigned int)s.x, (unsigned int)s.y};
|
||||
return Size {s.x, s.y};
|
||||
#else
|
||||
HWND hwnd = (HWND) wxGetApp().frame->GetHandle();
|
||||
RECT rect;
|
||||
@@ -559,15 +550,10 @@ extern "C" {
|
||||
}
|
||||
|
||||
Size get_mouse_position(wxMouseEvent &event) {
|
||||
#ifdef __APPLE__
|
||||
wxPoint p = event.GetPosition();
|
||||
float scale_factor = wxGetApp().frame->GetDPIScaleFactor();
|
||||
struct Size s = {p.x * scale_factor, p.y * scale_factor};
|
||||
return s;
|
||||
#else
|
||||
// alkane-toolkit patch: logical (DIP) coordinates on every platform,
|
||||
// matching get_client_size (upstream scaled them on Apple).
|
||||
wxPoint p = event.GetPosition();
|
||||
return Size {p.x, p.y};
|
||||
#endif
|
||||
}
|
||||
|
||||
int get_mouse_wheel_rotation(wxMouseEvent &event) {
|
||||
|
||||
@@ -107,6 +107,8 @@ mod notsafe {
|
||||
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
|
||||
pub fn wxbr_set_appearance_system();
|
||||
pub fn wxbr_is_dark() -> c_int;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
|
||||
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
|
||||
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
@@ -271,6 +273,22 @@ pub fn is_dark() -> bool {
|
||||
unsafe { notsafe::wxbr_is_dark() != 0 }
|
||||
}
|
||||
|
||||
/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
|
||||
/// the window and lets it paint first). macOS only, for the self-test's
|
||||
/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
|
||||
pub fn snapshot_png(win: &Widget, path: &str) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let Ok(p) = CString::new(path) else { return false };
|
||||
unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = (win, path);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
|
||||
/// 3=button face, 4=grey text. Returns (r, g, b).
|
||||
pub fn system_color(which: i32) -> (u8, u8, u8) {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Report relay for the Alkane Toolkit's Bug report button (see README.md).
|
||||
FROM python:3.13-alpine
|
||||
RUN adduser -D -H -u 10001 relay
|
||||
COPY relay.py /app/relay.py
|
||||
USER relay
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["python3", "-u", "/app/relay.py"]
|
||||
@@ -0,0 +1,65 @@
|
||||
# Report relay
|
||||
|
||||
Files the app's bug reports and feature requests as issues in
|
||||
`blueflare/alkane-toolkit`. The app's **Bug report** button posts the report
|
||||
here; the relay holds the only token, so the public app download carries no
|
||||
secret.
|
||||
|
||||
```
|
||||
app --HTTPS--> gitea.bluefla.re/alkane-report/ (nginx) --> relay --> Gitea API
|
||||
```
|
||||
|
||||
## What it does
|
||||
|
||||
- `POST /v1/report` takes the JSON the app sends (`kind`, `text`, version and
|
||||
OS context, optional `log`) and answers `201 {"number", "url"}` or an error
|
||||
`{"error": "..."}` the app shows as is. `GET /healthz` answers `200`.
|
||||
- Checks: type is `bug`, `ui` or `feature`; text 1 to 8,000 characters;
|
||||
each context value at most 120 printable characters; log at most 16 KiB;
|
||||
body at most 64 KiB (nginx enforces the same).
|
||||
- Rate limits, in memory: 5 reports per client IP per hour and 60 in all.
|
||||
Over the limit: `429` with `Retry-After`. At most 4 reports in flight.
|
||||
The client IP is `X-Real-IP` from nginx. Office LAN clients reach nginx
|
||||
through the router's hairpin NAT, so they share one IP and one limit.
|
||||
- Scrubs the log a second time (the app scrubs first): password, token,
|
||||
secret and similar values, `Authorization`/`Cookie` values, URL passwords
|
||||
and PEM private keys become `[redacted]`.
|
||||
- `@name` in a report cannot notify anyone (a zero-width space follows `@`).
|
||||
- The issue title is the text's first line (up to 100 characters). The body
|
||||
has the type, a context table, the text, and the log in a collapsed block.
|
||||
Labels: the type (`bug`, `ui`, `feature`) and `from-app`.
|
||||
- Nothing is stored. Each report leaves one log line: the client IP and the
|
||||
outcome (`filed #N`, `refused <status>`, `rate limited`, `tracker error`),
|
||||
never the report's text.
|
||||
|
||||
## Gitea account
|
||||
|
||||
Issues are filed as `alkane-reporter`, a local non-admin user with a random
|
||||
password that is never used. Its only access is the org team
|
||||
`alkane-reporters` (units `repo.code: read`, `repo.issues: write`) on
|
||||
`alkane-toolkit`. Its token `alkane-toolkit-bug-reports` has the scopes
|
||||
`write:issue` and `read:repository`. This mirrors FLARE's `flare-reporter`.
|
||||
|
||||
## Deployment
|
||||
|
||||
On the Gitea host, recorded in the `flare-deployment` repository
|
||||
(`runbooks/alkane-report-relay.md`):
|
||||
|
||||
```sh
|
||||
# in /opt/flare/deploy/alkane-report-relay, holding relay.py, Dockerfile, compose.yml
|
||||
PROXY_NETWORK=flare_default docker compose -p alkane-report-relay up -d --build
|
||||
```
|
||||
|
||||
The token file is `secrets/gitea_token` next to the compose file (directory
|
||||
`0700`, never committed). nginx routes `location /alkane-report/` in the
|
||||
`gitea.bluefla.re` server block to `alkane-report-relay:8080`.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
python3 tools/report-relay/test_relay.py
|
||||
```
|
||||
|
||||
They run the real HTTP handler against a fake Gitea: filing, scrubbing,
|
||||
mention handling, validation, size and rate limits, and tracker errors. CI
|
||||
runs them in the `verify` workflow's unit tests.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Deployed on the Gitea host next to the shared nginx (see README.md).
|
||||
# The token file is created on the host and never committed.
|
||||
services:
|
||||
report-relay:
|
||||
build: .
|
||||
image: alkane-report-relay:local
|
||||
container_name: alkane-report-relay
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
environment:
|
||||
GITEA_URL: http://gitea:3000
|
||||
GITEA_REPO: blueflare/alkane-toolkit
|
||||
GITEA_TOKEN_FILE: /run/secrets/gitea_token
|
||||
RATE_PER_IP: "5"
|
||||
RATE_GLOBAL: "60"
|
||||
volumes:
|
||||
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
|
||||
networks: [proxy]
|
||||
networks:
|
||||
proxy:
|
||||
external: true
|
||||
name: ${PROXY_NETWORK:?set PROXY_NETWORK to the shared nginx network}
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Report relay: files Alkane Toolkit bug reports as Gitea issues.
|
||||
|
||||
The app's Bug report button posts JSON here; the relay checks it, scrubs the
|
||||
log again, rate-limits, and files one issue in one repository with its own
|
||||
token. The app holds no secret. Nothing about a report is stored.
|
||||
|
||||
POST /v1/report {"kind": "bug"|"ui"|"feature", "text": "...",
|
||||
"app_version", "platform", "os", "appearance",
|
||||
"language", "window": "...", "log": "..."}
|
||||
-> 201 {"number": N, "url": "..."}
|
||||
-> 4xx/5xx {"error": "reason the app shows"}
|
||||
GET /healthz -> 200 ok
|
||||
|
||||
Configuration (environment):
|
||||
GITEA_URL API base, e.g. http://gitea:3000 (default https://gitea.bluefla.re)
|
||||
GITEA_REPO owner/name the issues go to (default blueflare/alkane-toolkit)
|
||||
GITEA_TOKEN_FILE file holding the token (scopes write:issue, read:repository)
|
||||
LISTEN host:port (default 0.0.0.0:8080)
|
||||
RATE_PER_IP reports per client IP per hour (default 5)
|
||||
RATE_GLOBAL reports per hour in all (default 60)
|
||||
|
||||
The client IP is the X-Real-IP header the reverse proxy sets; the relay must
|
||||
only be reachable through that proxy.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KINDS = {"bug": "Bug", "ui": "UI change", "feature": "Feature request"}
|
||||
CONTEXT_FIELDS = (
|
||||
("app_version", "App version"),
|
||||
("platform", "Platform"),
|
||||
("os", "OS"),
|
||||
("appearance", "Appearance"),
|
||||
("language", "Language"),
|
||||
("window", "Window"),
|
||||
)
|
||||
FROM_APP_LABEL = "from-app"
|
||||
MAX_BODY = 64 * 1024
|
||||
MAX_TEXT_CHARS = 8000
|
||||
MAX_CONTEXT_CHARS = 120
|
||||
MAX_LOG_BYTES = 16 * 1024
|
||||
MAX_TITLE_CHARS = 100
|
||||
MAX_IN_FLIGHT = 4
|
||||
HOUR = 3600.0
|
||||
|
||||
SECRET_NAME = re.compile(
|
||||
r"(password|passwd|pass|pwd|secret|token|apikey|api_key|psk|credential)"
|
||||
r"(['\"]?\s*[:=]\s*['\"]?)([^\s'\",&;]+)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
HEADER_SECRET = re.compile(r"((?:authorization|cookie)\s*:\s*).+", re.IGNORECASE)
|
||||
URL_USERINFO = re.compile(r"(://[^/\s:@]+:)[^/\s@]+(@)")
|
||||
PEM_BLOCK = re.compile(
|
||||
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(-----END [A-Z ]*PRIVATE KEY-----|\Z)",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def scrub(text: str) -> str:
|
||||
"""Remove credentials (the app scrubs too; this is the second pass)."""
|
||||
text = PEM_BLOCK.sub("[redacted]", text)
|
||||
text = HEADER_SECRET.sub(r"\1[redacted]", text)
|
||||
text = URL_USERINFO.sub(r"\1[redacted]\2", text)
|
||||
return SECRET_NAME.sub(r"\1\2[redacted]", text)
|
||||
|
||||
|
||||
def no_mentions(text: str) -> str:
|
||||
"""Stop @name in a report from notifying Gitea users."""
|
||||
return re.sub(r"@(?=[A-Za-z0-9_])", "@\u200b", text)
|
||||
|
||||
|
||||
def fence_for(text: str) -> str:
|
||||
"""A backtick fence longer than any backtick run in `text`."""
|
||||
longest = max((len(m) for m in re.findall(r"`+", text)), default=0)
|
||||
return "`" * max(3, longest + 1)
|
||||
|
||||
|
||||
def cell(value: str) -> str:
|
||||
return value.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
class BadReport(Exception):
|
||||
def __init__(self, status: int, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
def validate(raw: bytes) -> dict:
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise BadReport(400, "The report was not valid JSON")
|
||||
if not isinstance(data, dict):
|
||||
raise BadReport(400, "The report was not a JSON object")
|
||||
kind = data.get("kind", "bug")
|
||||
if kind not in KINDS:
|
||||
raise BadReport(422, "Unknown report type")
|
||||
text = data.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise BadReport(422, "The report is empty")
|
||||
text = text.strip()
|
||||
if len(text) > MAX_TEXT_CHARS:
|
||||
raise BadReport(413, f"The text is longer than {MAX_TEXT_CHARS} characters")
|
||||
context = {}
|
||||
for key, _ in CONTEXT_FIELDS:
|
||||
value = data.get(key, "")
|
||||
if not isinstance(value, str) or len(value) > MAX_CONTEXT_CHARS:
|
||||
raise BadReport(422, f"Bad value for {key}")
|
||||
context[key] = "".join(c for c in value if c.isprintable())
|
||||
log = data.get("log", "")
|
||||
if not isinstance(log, str) or len(log.encode()) > MAX_LOG_BYTES:
|
||||
raise BadReport(413, "The log is too large")
|
||||
return {"kind": kind, "text": text, "context": context, "log": log}
|
||||
|
||||
|
||||
def issue_title(report: dict) -> str:
|
||||
first = next(line.strip() for line in report["text"].splitlines() if line.strip())
|
||||
if len(first) > MAX_TITLE_CHARS:
|
||||
first = first[: MAX_TITLE_CHARS - 3].rstrip() + "..."
|
||||
return no_mentions(first)
|
||||
|
||||
|
||||
def issue_body(report: dict) -> str:
|
||||
ctx = report["context"]
|
||||
lines = [
|
||||
f"**Type:** {KINDS[report['kind']]}",
|
||||
"",
|
||||
"Sent from the Alkane Toolkit app's Bug report button.",
|
||||
"",
|
||||
"| | |",
|
||||
"|---|---|",
|
||||
]
|
||||
for key, label in CONTEXT_FIELDS:
|
||||
if ctx.get(key):
|
||||
lines.append(f"| {label} | {cell(ctx[key])} |")
|
||||
lines += ["", "---", "", no_mentions(report["text"])]
|
||||
log = scrub(report["log"]).strip()
|
||||
if log:
|
||||
fence = fence_for(log)
|
||||
lines += [
|
||||
"",
|
||||
"<details><summary>Recent activity log</summary>",
|
||||
"",
|
||||
fence,
|
||||
no_mentions(log),
|
||||
fence,
|
||||
"",
|
||||
"</details>",
|
||||
]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""Sliding one-hour windows, per client IP and in all."""
|
||||
|
||||
def __init__(self, per_ip: int, total: int, clock=time.monotonic):
|
||||
self.per_ip, self.total, self.clock = per_ip, total, clock
|
||||
self.by_ip: dict[str, deque] = {}
|
||||
self.all: deque = deque()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def take(self, ip: str) -> float:
|
||||
"""0 if the report may go now, else seconds until it may."""
|
||||
now = self.clock()
|
||||
with self.lock:
|
||||
for q in [self.all, *self.by_ip.values()]:
|
||||
while q and now - q[0] >= HOUR:
|
||||
q.popleft()
|
||||
self.by_ip = {k: q for k, q in self.by_ip.items() if q}
|
||||
mine = self.by_ip.setdefault(ip, deque())
|
||||
if len(mine) >= self.per_ip:
|
||||
return HOUR - (now - mine[0])
|
||||
if len(self.all) >= self.total:
|
||||
return HOUR - (now - self.all[0])
|
||||
mine.append(now)
|
||||
self.all.append(now)
|
||||
return 0.0
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, url: str, repo: str, token: str, timeout: float = 20):
|
||||
self.api = url.rstrip("/") + "/api/v1/repos/" + repo
|
||||
self.token, self.timeout = token, timeout
|
||||
self.labels: dict[str, int] = {}
|
||||
self.labels_at = 0.0
|
||||
|
||||
def _call(self, method: str, path: str, body: dict | None = None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(self.api + path, data=data, method=method)
|
||||
req.add_header("Authorization", f"token {self.token}")
|
||||
req.add_header("Accept", "application/json")
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
return json.load(resp)
|
||||
|
||||
def label_ids(self, names: list[str]) -> list[int]:
|
||||
"""IDs of the repository's labels by name (cached 10 minutes);
|
||||
unknown names are skipped."""
|
||||
if time.monotonic() - self.labels_at > 600:
|
||||
try:
|
||||
found = self._call("GET", "/labels?limit=50")
|
||||
self.labels = {l["name"]: l["id"] for l in found}
|
||||
self.labels_at = time.monotonic()
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError):
|
||||
pass
|
||||
return [self.labels[n] for n in names if n in self.labels]
|
||||
|
||||
def file(self, title: str, body: str, labels: list[str]) -> tuple[int, str]:
|
||||
issue = self._call("POST", "/issues", {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"labels": self.label_ids(labels),
|
||||
})
|
||||
return int(issue["number"]), str(issue["html_url"])
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, gitea: Gitea, limiter: RateLimiter, log=print):
|
||||
self.gitea, self.limiter, self.log = gitea, limiter, log
|
||||
self.slots = threading.BoundedSemaphore(MAX_IN_FLIGHT)
|
||||
|
||||
def handle(self, ip: str, raw: bytes) -> tuple[int, dict, dict]:
|
||||
"""Return (status, json body, extra headers)."""
|
||||
try:
|
||||
report = validate(raw)
|
||||
except BadReport as bad:
|
||||
self.log(f"report from {ip}: refused {bad.status} ({bad.message})")
|
||||
return bad.status, {"error": bad.message}, {}
|
||||
wait = self.limiter.take(ip)
|
||||
if wait > 0:
|
||||
self.log(f"report from {ip}: rate limited")
|
||||
return 429, {"error": "Too many reports; try again later"}, {
|
||||
"Retry-After": str(int(wait) + 1)}
|
||||
if not self.slots.acquire(blocking=False):
|
||||
return 503, {"error": "The report service is busy; try again shortly"}, {}
|
||||
try:
|
||||
number, url = self.gitea.file(
|
||||
issue_title(report), issue_body(report), [report["kind"], FROM_APP_LABEL])
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
|
||||
self.log(f"report from {ip}: tracker error ({type(e).__name__})")
|
||||
return 502, {"error": "The issue tracker did not answer; check the issue "
|
||||
"list before sending again"}, {}
|
||||
finally:
|
||||
self.slots.release()
|
||||
self.log(f"report from {ip}: filed #{number}")
|
||||
return 201, {"number": number, "url": url}, {}
|
||||
|
||||
|
||||
def make_handler(relay: Relay):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "alkane-report-relay"
|
||||
sys_version = ""
|
||||
|
||||
def _send(self, status: int, body: dict, headers: dict | None = None):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/healthz":
|
||||
self._send(200, {"status": "ok"})
|
||||
else:
|
||||
self._send(404, {"error": "Not found"})
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/v1/report":
|
||||
return self._send(404, {"error": "Not found"})
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", ""))
|
||||
except ValueError:
|
||||
return self._send(411, {"error": "Length required"})
|
||||
if length < 0 or length > MAX_BODY:
|
||||
return self._send(413, {"error": "The report is too large"})
|
||||
raw = self.rfile.read(length)
|
||||
ip = self.headers.get("X-Real-IP") or self.client_address[0]
|
||||
status, body, headers = relay.handle(ip, raw)
|
||||
self._send(status, body, headers)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass # one line per report comes from Relay.handle instead
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main() -> None:
|
||||
token_file = os.environ.get("GITEA_TOKEN_FILE", "/run/secrets/gitea_token")
|
||||
with open(token_file) as fh:
|
||||
token = fh.read().strip()
|
||||
if not token:
|
||||
sys.exit(f"empty token in {token_file}")
|
||||
gitea = Gitea(os.environ.get("GITEA_URL", "https://gitea.bluefla.re"),
|
||||
os.environ.get("GITEA_REPO", "blueflare/alkane-toolkit"), token)
|
||||
limiter = RateLimiter(int(os.environ.get("RATE_PER_IP", "5")),
|
||||
int(os.environ.get("RATE_GLOBAL", "60")))
|
||||
relay = Relay(gitea, limiter, log=lambda m: print(m, flush=True))
|
||||
host, _, port = os.environ.get("LISTEN", "0.0.0.0:8080").rpartition(":")
|
||||
server = ThreadingHTTPServer((host or "0.0.0.0", int(port)), make_handler(relay))
|
||||
print(f"report relay on {host}:{port} -> {gitea.api}", flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Tests for the report relay: python3 tools/report-relay/test_relay.py"""
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
import relay # noqa: E402
|
||||
|
||||
TOKEN = "test-token-123"
|
||||
|
||||
|
||||
class FakeGitea:
|
||||
"""Records issue creations; serves the repository's labels."""
|
||||
|
||||
def __init__(self, fail=False):
|
||||
self.created = []
|
||||
self.fail = fail
|
||||
outer = self
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _json(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
||||
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||
{"name": "feature", "id": 3},
|
||||
{"name": "from-app", "id": 9}])
|
||||
self._json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if outer.fail:
|
||||
return self._json(500, {"message": "boom"})
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
outer.created.append((self.path, body))
|
||||
n = len(outer.created)
|
||||
self._json(201, {"number": n,
|
||||
"html_url": f"https://gitea.example/blueflare/alkane-toolkit/issues/{n}"})
|
||||
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
class RelayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.gitea = FakeGitea()
|
||||
self.now = [1000.0]
|
||||
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
||||
self.logs = []
|
||||
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
|
||||
self.limiter, log=self.logs.append)
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.gitea.close()
|
||||
|
||||
def post(self, body, ip="198.51.100.7", path="/v1/report", raw=None):
|
||||
data = raw if raw is not None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(self.url + path, data=data, method="POST",
|
||||
headers={"Content-Type": "application/json",
|
||||
"X-Real-IP": ip})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, json.load(resp), resp.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.load(e), e.headers
|
||||
|
||||
def report(self, **over):
|
||||
body = {"kind": "bug", "text": "Table is blank on macOS\nSteps: open the app.",
|
||||
"app_version": "0.110.0", "platform": "macos-aarch64", "os": "macOS 15.1",
|
||||
"appearance": "dark", "language": "en", "window": "1280x800", "log": ""}
|
||||
body.update(over)
|
||||
return body
|
||||
|
||||
def test_files_an_issue_with_title_body_and_labels(self):
|
||||
status, body, _ = self.post(self.report(kind="feature", log="12:00 scan done"))
|
||||
self.assertEqual(status, 201)
|
||||
self.assertEqual(body["number"], 1)
|
||||
self.assertTrue(body["url"].endswith("/issues/1"))
|
||||
path, issue = self.gitea.created[0]
|
||||
self.assertEqual(path, "/api/v1/repos/blueflare/alkane-toolkit/issues")
|
||||
self.assertEqual(issue["title"], "Table is blank on macOS")
|
||||
self.assertEqual(issue["labels"], [3, 9])
|
||||
self.assertIn("**Type:** Feature request", issue["body"])
|
||||
self.assertIn("| OS | macOS 15.1 |", issue["body"])
|
||||
self.assertIn("Steps: open the app.", issue["body"])
|
||||
self.assertIn("<details><summary>Recent activity log</summary>", issue["body"])
|
||||
self.assertIn("filed #1", self.logs[-1])
|
||||
self.assertNotIn("blank", " ".join(self.logs), "report text is never logged")
|
||||
|
||||
def test_scrubs_the_log_and_neutralises_mentions(self):
|
||||
log = ("set pool url=stratum+tcp://w:hunter2@pool:3333 password=hunter2\n"
|
||||
"Authorization: Bearer abc.def\n``` fence ```")
|
||||
status, _, _ = self.post(self.report(text="@admin please look", log=log))
|
||||
self.assertEqual(status, 201)
|
||||
_, issue = self.gitea.created[0]
|
||||
self.assertNotIn("hunter2", issue["body"])
|
||||
self.assertNotIn("abc.def", issue["body"])
|
||||
self.assertNotIn("@admin", issue["body"])
|
||||
self.assertNotIn("@admin", issue["title"])
|
||||
self.assertIn("````\n", issue["body"], "fence longer than the log's own")
|
||||
|
||||
def test_rejects_bad_reports(self):
|
||||
cases = [
|
||||
(self.report(text=" "), 422),
|
||||
(self.report(kind="hack"), 422),
|
||||
(self.report(text="x" * 8001), 413),
|
||||
(self.report(log="y" * (16 * 1024 + 1)), 413),
|
||||
(self.report(os="z" * 121), 422),
|
||||
(self.report(os=5), 422),
|
||||
([1, 2], 400),
|
||||
]
|
||||
for body, want in cases:
|
||||
status, answer, _ = self.post(body)
|
||||
self.assertEqual(status, want, body if not isinstance(body, dict) else answer)
|
||||
self.assertIn("error", answer)
|
||||
status, _, _ = self.post(None, raw=b"{not json")
|
||||
self.assertEqual(status, 400)
|
||||
status, _, _ = self.post(None, raw=b"x" * (relay.MAX_BODY + 1))
|
||||
self.assertEqual(status, 413)
|
||||
status, _, _ = self.post(self.report(), path="/v1/other")
|
||||
self.assertEqual(status, 404)
|
||||
self.assertEqual(self.gitea.created, [])
|
||||
|
||||
def test_rate_limits_per_ip_and_in_all(self):
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.post(self.report())[0], 201)
|
||||
status, body, headers = self.post(self.report())
|
||||
self.assertEqual(status, 429)
|
||||
self.assertGreater(int(headers["Retry-After"]), 0)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.9")[0], 201)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.10")[0], 429, "global cap of 3")
|
||||
self.now[0] += relay.HOUR
|
||||
self.assertEqual(self.post(self.report())[0], 201, "window slides")
|
||||
|
||||
def test_tracker_failure_is_reported(self):
|
||||
self.gitea.fail = True
|
||||
status, body, _ = self.post(self.report())
|
||||
self.assertEqual(status, 502)
|
||||
self.assertIn("check the issue list", body["error"])
|
||||
|
||||
def test_title_is_cut(self):
|
||||
title = relay.issue_title({"text": "\n\n" + "w" * 300})
|
||||
self.assertEqual(len(title), relay.MAX_TITLE_CHARS)
|
||||
self.assertTrue(title.endswith("..."))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"b2dbba5377a739bc8be3380cfbd09aa80893841c15c305bfd25f900ba7b6a0c9","src/backends/v2020/rpc.rs":"b517f88b9125fe1d8a20d5167f5d0d105b1339fce3d1a9fad5592e00470f46fb","src/backends/v2020/web.rs":"a6a3ad3eb77551b098b0092553b02cee43d165476d8c92164e12a1e765753b0d","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"0906bff13eb51bd47fb0e06cc2c1955fe459c601cb467efc917801ead825dd61","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"e75c21d63218204b61bfab067599402e5c0b20452beaf0b16bfa79bf8afb6b35","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"f709048edc8eddf71d848d0f3c55c3e2c748726072f9c838482062b66524d875","src/backends/v2020/rpc.rs":"b517f88b9125fe1d8a20d5167f5d0d105b1339fce3d1a9fad5592e00470f46fb","src/backends/v2020/web.rs":"a6a3ad3eb77551b098b0092553b02cee43d165476d8c92164e12a1e765753b0d","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"0906bff13eb51bd47fb0e06cc2c1955fe459c601cb467efc917801ead825dd61","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"e75c21d63218204b61bfab067599402e5c0b20452beaf0b16bfa79bf8afb6b35","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
|
||||
+1
-21
@@ -202,27 +202,7 @@ fn miner_conf_with_fan_config(miner_conf: &Value, config: FanConfig) -> Value {
|
||||
Value::Object(payload)
|
||||
}
|
||||
|
||||
/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
/// X11) is left Unknown rather than guessed wrong.
|
||||
fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
let upper = model.to_ascii_uppercase();
|
||||
let name = upper
|
||||
.strip_prefix("ANTMINER ")
|
||||
.unwrap_or(&upper)
|
||||
.trim_start();
|
||||
match name.chars().next() {
|
||||
// Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
Some('Z') => HashAlgorithm::Equihash,
|
||||
// L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
Some('L') => HashAlgorithm::Scrypt,
|
||||
// S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
_ => HashAlgorithm::Unknown,
|
||||
}
|
||||
}
|
||||
use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
|
||||
impl AntMinerV2020 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"de321c89f62a60690ba07d6bb145ac688c6141c458638e68b3ed36b50b8de1f1","Cargo.lock":"5942ec7c9cf5c201bd32442d65020dc3ae72e33cb5aaf374b2a26501571a1487","Cargo.toml":"cb9ee00cbb415fa66a71a7d4822839bb3552336ec9ab975ae7b1137c711449cb","Cargo.toml.orig":"08409c395e4d502015da62e97efdc9c5bc6e3076031144f3f5aa35c900c7c735","src/backends/mod.rs":"26591e67688f8d015242295dde5050c4b34986e9980018a855346291a0472206","src/backends/v1_2_0/mod.rs":"a1b0eb9e2e57cad0190eb8f31dafff0999e31c3602db2b8d84e9dd45c955b623","src/backends/v1_2_0/web.rs":"ac89f16bf623f7d85590d34b45c99b0e522d9d434b4c22af7fa8a8a653e09d2e","src/backends/v1_3_0/mod.rs":"9aa230fe942ca775f812300f0041f5565861ef32ad73207e48d02b41e423ee25","src/backends/v1_3_0/web.rs":"1ec4cbe6bdc26f165d9e54e9bf2aac4c3706357ce4677dc21113710d4a26c3c1","src/firmware.rs":"168eeffaef90cb1525bb2e126e73905b5205d49215437263813e30323f6b7a05","src/lib.rs":"16ea1c0007fa6d6c86c1f83d3ac9cdf065cd9936cd52f35ef89c227397bbc54a","src/timezone.rs":"309bf23de1bdc9126bde5db8dabff0d2c0fea797dbf2630a772a18539838a05e"},"package":"1cb662e56f104c0fe45c8ccdac13f60cbcaad45ac228f939c6ac46ff40335052"}
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"de321c89f62a60690ba07d6bb145ac688c6141c458638e68b3ed36b50b8de1f1","Cargo.lock":"5942ec7c9cf5c201bd32442d65020dc3ae72e33cb5aaf374b2a26501571a1487","Cargo.toml":"cb9ee00cbb415fa66a71a7d4822839bb3552336ec9ab975ae7b1137c711449cb","Cargo.toml.orig":"08409c395e4d502015da62e97efdc9c5bc6e3076031144f3f5aa35c900c7c735","src/backends/mod.rs":"26591e67688f8d015242295dde5050c4b34986e9980018a855346291a0472206","src/backends/v1_2_0/mod.rs":"f0818aae9410bcf4cf6f2efbb867ce9ea8a7542cc9cf9942be1b99570e2912c4","src/backends/v1_2_0/web.rs":"ac89f16bf623f7d85590d34b45c99b0e522d9d434b4c22af7fa8a8a653e09d2e","src/backends/v1_3_0/mod.rs":"3e1e10869930c72135ec98e69293c0aeb07d4c31c06e8f8301aa1dbfc87552bb","src/backends/v1_3_0/web.rs":"1ec4cbe6bdc26f165d9e54e9bf2aac4c3706357ce4677dc21113710d4a26c3c1","src/firmware.rs":"168eeffaef90cb1525bb2e126e73905b5205d49215437263813e30323f6b7a05","src/lib.rs":"16ea1c0007fa6d6c86c1f83d3ac9cdf065cd9936cd52f35ef89c227397bbc54a","src/timezone.rs":"309bf23de1bdc9126bde5db8dabff0d2c0fea797dbf2630a772a18539838a05e"},"package":"1cb662e56f104c0fe45c8ccdac13f60cbcaad45ac228f939c6ac46ff40335052"}
|
||||
+66
-4
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
device::DeviceInfo,
|
||||
device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV120 {
|
||||
impl VnishV120 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
let algo = model.hash_algorithm();
|
||||
// A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
// resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
// as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
// the stock backend does.
|
||||
let algo = match model.hash_algorithm() {
|
||||
HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
known => known,
|
||||
};
|
||||
VnishV120 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -509,8 +517,24 @@ impl GetHashboards for VnishV120 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
let mut hashboards: Vec<BoardData> =
|
||||
(0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
// The model's hardware table gives the board count. For a model asic-rs
|
||||
// does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
// sizing from it dropped every live chain -- the boards then vanished
|
||||
// from the data although the miner reports them. Fall back to what the
|
||||
// miner reports: the highest 1-based chain id, so a dead middle board
|
||||
// still keeps its slot.
|
||||
let reported_boards = all_chains
|
||||
.iter()
|
||||
.filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
.max()
|
||||
.unwrap_or(0) as usize;
|
||||
let board_count = self
|
||||
.device_info
|
||||
.hardware
|
||||
.board_count()
|
||||
.map(|n| n as usize)
|
||||
.unwrap_or(reported_boards);
|
||||
let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1524,4 +1548,42 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
|
||||
/// Same as the 1.3.x backend: a model with no hardware table (VNish's
|
||||
/// "Antminer S19 (88)") must keep the chains the miner reports instead of
|
||||
/// sizing the board list to zero. Live 1.2.7 units (e.g. 10.4.1.111) run it.
|
||||
#[tokio::test]
|
||||
async fn unknown_model_keeps_the_reported_chains() {
|
||||
let miner = VnishV120::new(
|
||||
IpAddr::from([127, 0, 0, 1]),
|
||||
AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
);
|
||||
let mut results = HashMap::new();
|
||||
results.insert(
|
||||
MinerCommand::WebAPI {
|
||||
command: "info",
|
||||
parameters: None,
|
||||
},
|
||||
json!({ "miner": "Antminer S19 (88)", "hr_measure": "GH/s", "fw_version": "1.2.7" }),
|
||||
);
|
||||
results.insert(
|
||||
MinerCommand::WebAPI {
|
||||
command: "summary",
|
||||
parameters: None,
|
||||
},
|
||||
json!({ "miner": { "hr_realtime": 82600.0, "chains": [
|
||||
{ "id": 1, "hashrate_rt": 27537.83 },
|
||||
{ "id": 2, "hashrate_rt": 27511.20 },
|
||||
{ "id": 3, "hashrate_rt": 27601.04 }
|
||||
] } }),
|
||||
);
|
||||
let mock_api = MockAPIClient::new(results);
|
||||
let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
|
||||
assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
// ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
assert!(miner_data.hashboards.iter().all(|b| b.hashrate.is_some()));
|
||||
}
|
||||
}
|
||||
|
||||
+70
-4
@@ -1,5 +1,6 @@
|
||||
use std::{collections::HashMap, net::IpAddr, str::FromStr, time::Duration};
|
||||
|
||||
use asic_rs_makes_antminer::models::infer_antminer_algo;
|
||||
use anyhow;
|
||||
use asic_rs_core::{
|
||||
config::{
|
||||
@@ -17,7 +18,7 @@ use asic_rs_core::{
|
||||
DataCollector, DataExtensions, DataExtractor, DataField, DataLocation, get_by_pointer,
|
||||
},
|
||||
command::MinerCommand,
|
||||
device::DeviceInfo,
|
||||
device::{DeviceInfo, HashAlgorithm},
|
||||
fan::FanData,
|
||||
hashrate::{HashRate, HashRateUnit},
|
||||
message::{MessageSeverity, MinerComponent, MinerMessage},
|
||||
@@ -52,7 +53,14 @@ pub struct VnishV130 {
|
||||
impl VnishV130 {
|
||||
pub fn new(ip: IpAddr, model: impl MinerModel) -> Self {
|
||||
let auth = Self::default_auth();
|
||||
let algo = model.hash_algorithm();
|
||||
// A model outside asic-rs' alias table (VNish's "Antminer S19 (88)")
|
||||
// resolves to HashAlgorithm::Unknown, which left its hashrate bucketed
|
||||
// as "Unknown Hashrate". Infer it from the Antminer family letter, as
|
||||
// the stock backend does.
|
||||
let algo = match model.hash_algorithm() {
|
||||
HashAlgorithm::Unknown => infer_antminer_algo(&model.to_string()),
|
||||
known => known,
|
||||
};
|
||||
VnishV130 {
|
||||
ip,
|
||||
web: VnishWebAPI::new(ip, 80, auth),
|
||||
@@ -516,8 +524,24 @@ impl GetHashboards for VnishV130 {
|
||||
.and_then(|v| v.pointer("/factory"))
|
||||
.and_then(|v| v.as_array());
|
||||
|
||||
let mut hashboards: Vec<BoardData> =
|
||||
(0..self.device_info.hardware.board_count().unwrap_or(0) as usize)
|
||||
// The model's hardware table gives the board count. For a model asic-rs
|
||||
// does not know (e.g. VNish "Antminer S19 (88)") there is no table, and
|
||||
// sizing from it dropped every live chain -- the boards then vanished
|
||||
// from the data although the miner reports them. Fall back to what the
|
||||
// miner reports: the highest 1-based chain id, so a dead middle board
|
||||
// still keeps its slot.
|
||||
let reported_boards = all_chains
|
||||
.iter()
|
||||
.filter_map(|c| c.pointer("/id").and_then(|v| v.as_u64()))
|
||||
.max()
|
||||
.unwrap_or(0) as usize;
|
||||
let board_count = self
|
||||
.device_info
|
||||
.hardware
|
||||
.board_count()
|
||||
.map(|n| n as usize)
|
||||
.unwrap_or(reported_boards);
|
||||
let mut hashboards: Vec<BoardData> = (0..board_count)
|
||||
.map(|idx| {
|
||||
BoardData::new(idx as u8, self.device_info.hardware.chips_for_board(idx))
|
||||
})
|
||||
@@ -1661,4 +1685,46 @@ mod tests {
|
||||
assert!(config.available.contains(&Tz::Etc__GMT));
|
||||
assert_eq!(config.available.last(), Some(&Tz::Etc__GMTMinus14));
|
||||
}
|
||||
|
||||
/// A model asic-rs has no hardware table for -- VNish reports the 88-chip
|
||||
/// S19 as "Antminer S19 (88)" -- must still surface the boards the miner
|
||||
/// reports. Sizing the board list from the (absent) table dropped all
|
||||
/// three live chains, so the GUI drew no hashboard icons for a hashing
|
||||
/// miner. Chain values match the live 10.4.0.179 unit.
|
||||
#[tokio::test]
|
||||
async fn unknown_model_keeps_the_reported_chains() {
|
||||
let miner = VnishV130::new(
|
||||
IpAddr::from([127, 0, 0, 1]),
|
||||
AntMinerModel::Unknown("ANTMINER S19 (88)".to_string()),
|
||||
);
|
||||
let mut results = HashMap::new();
|
||||
results.insert(
|
||||
web("info"),
|
||||
json!({ "miner": "Antminer S19 (88)", "model": "s19-88", "hr_measure": "GH/s" }),
|
||||
);
|
||||
results.insert(
|
||||
web("summary"),
|
||||
json!({
|
||||
"miner": {
|
||||
"hr_realtime": 82600.0,
|
||||
"chains": [
|
||||
{ "id": 1, "hashrate_rt": 27537.83, "chip_statuses": { "grey": 88 } },
|
||||
{ "id": 2, "hashrate_rt": 27511.20, "chip_statuses": { "grey": 88 } },
|
||||
{ "id": 3, "hashrate_rt": 27601.04, "chip_statuses": { "grey": 88 } }
|
||||
]
|
||||
}
|
||||
}),
|
||||
);
|
||||
let mock_api = MockAPIClient::new(results);
|
||||
let mut collector = DataCollector::new_with_client(&miner, &mock_api);
|
||||
let miner_data = miner.parse_data(collector.collect_all().await);
|
||||
|
||||
assert_eq!(miner_data.hashboards.len(), 3, "one board per reported chain");
|
||||
// ...and its hashrate is SHA-256 (family letter S), not "Unknown".
|
||||
assert_eq!(miner_data.hashrate.expect("hashrate").algo, HashAlgorithm::SHA256);
|
||||
for (i, board) in miner_data.hashboards.iter().enumerate() {
|
||||
assert_eq!(board.position as usize, i);
|
||||
assert!(board.hashrate.is_some(), "board {i} keeps its live hashrate");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"aaaa0f14e3aff2543d3d09a4515efa5ab439f0651a36b582e87b9843d0475752","Cargo.lock":"58da2f3399ff680bf7d619204897b4edf5c03d336a8c3cceb54c9aba280bfed1","Cargo.toml":"57f92bf3808fa6f468dbabf43763a808d9ead128eef83b748f940ef3b219a80e","Cargo.toml.orig":"cbfb99fc843dd61ad2025dcfc16bd435afd2b6d43c2c983867af08af415916f1","src/hardware.rs":"6a52c19b38be83fe47ccf8f6c6fe3b7d9597575b79366fbc678ea3586953dd52","src/lib.rs":"b2f55767a7f3fdacb1e898c5cb961c2dec8481823f94386ee67628960e91bf7d","src/make.rs":"e968e4dbd745d485fc9ad4c5a4c081d679eddce11f66e572f81f2dbe37ede3f0","src/models.rs":"b4ea44fc627ff6c8b41bf8758d6ce6074aa690fe9f6c95a9cb3d1cdbd00e51d6"},"package":"67cca6e6bf4ac14562084ce7534521ffa7cd313fa39e2392f98ff98a047a4353"}
|
||||
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"aaaa0f14e3aff2543d3d09a4515efa5ab439f0651a36b582e87b9843d0475752","Cargo.lock":"58da2f3399ff680bf7d619204897b4edf5c03d336a8c3cceb54c9aba280bfed1","Cargo.toml":"57f92bf3808fa6f468dbabf43763a808d9ead128eef83b748f940ef3b219a80e","Cargo.toml.orig":"cbfb99fc843dd61ad2025dcfc16bd435afd2b6d43c2c983867af08af415916f1","src/hardware.rs":"6a52c19b38be83fe47ccf8f6c6fe3b7d9597575b79366fbc678ea3586953dd52","src/lib.rs":"b2f55767a7f3fdacb1e898c5cb961c2dec8481823f94386ee67628960e91bf7d","src/make.rs":"e968e4dbd745d485fc9ad4c5a4c081d679eddce11f66e572f81f2dbe37ede3f0","src/models.rs":"11bb8edd2417dbbd8754b56d35488db5e3d4655e16e71eee85291fabea876e99"},"package":"67cca6e6bf4ac14562084ce7534521ffa7cd313fa39e2392f98ff98a047a4353"}
|
||||
+23
@@ -201,6 +201,29 @@ pub enum AntMinerModel {
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// Infer an Antminer's hash algorithm from its model-family letter, for models
|
||||
/// asic-rs' alias table doesn't recognise (round 13 #5). Only the families whose
|
||||
/// entire product line shares one algorithm are inferred; anything ambiguous
|
||||
/// (the K-series spans Kadena/KHeavyHash/Eaglesong, DR is Blake256 while D is
|
||||
/// X11) is left Unknown rather than guessed wrong. Shared by every firmware
|
||||
/// backend that runs on Antminer hardware (stock, VNish).
|
||||
pub fn infer_antminer_algo(model: &str) -> HashAlgorithm {
|
||||
let upper = model.to_ascii_uppercase();
|
||||
let name = upper
|
||||
.strip_prefix("ANTMINER ")
|
||||
.unwrap_or(&upper)
|
||||
.trim_start();
|
||||
match name.chars().next() {
|
||||
// Z9 / Z11 / Z15 / Z15 Pro / Z15J -- the whole Z line is Equihash.
|
||||
Some('Z') => HashAlgorithm::Equihash,
|
||||
// L3+ / L7 / L9 / L11 -- the whole L line is Scrypt.
|
||||
Some('L') => HashAlgorithm::Scrypt,
|
||||
// S9..S21 and T9..T21 (and future revisions) are all SHA-256.
|
||||
Some('S') | Some('T') => HashAlgorithm::SHA256,
|
||||
_ => HashAlgorithm::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for AntMinerModel {
|
||||
type Err = ModelSelectionError;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user