Compare commits

..
12 Commits
30 changed files with 277 additions and 1516 deletions
-34
View File
@@ -1,34 +0,0 @@
name: public-benchmark-pages
on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
group: alkane-toolkit-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-pages
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- 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
-8
View File
@@ -4,10 +4,6 @@ on:
push:
branches: [next]
concurrency:
group: alkane-toolkit-next
cancel-in-progress: false
permissions:
contents: write
@@ -15,7 +11,6 @@ jobs:
candidate:
runs-on: alkane-ci
env:
CARGO_TARGET_DIR: target
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
@@ -51,6 +46,3 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz"
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+5 -11
View File
@@ -6,10 +6,6 @@ on:
push:
branches: [main]
concurrency:
group: alkane-toolkit-main
cancel-in-progress: false
permissions:
contents: write
actions: write
@@ -42,9 +38,6 @@ jobs:
- name: Benchmark history checks
run: python3 ci/test-bench-history.py
- name: Benchmark suite checks
run: python3 ci/test-bench-badge.py
- name: Install build dependencies
run: |
apt-get update -qq
@@ -96,12 +89,12 @@ jobs:
- name: Microbenchmarks
run: |
# Require every declared benchmark before publishing history or a release.
# Capture the bench stdout for the weighted-average delta badge (round 19
# #1) while keeping the step a hard gate: pipefail preserves cargo's exit
# code (each bench asserts its own absolute ceiling) even through tee.
set -o pipefail
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
| tee bench-current.txt
python3 ci/bench-badge.py --current bench-current.txt \
--baseline badges/bench-baseline.json --no-write
- name: Record private benchmark history
env:
@@ -112,6 +105,7 @@ jobs:
with:
name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html
- name: Headless UI self-test
run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
@@ -173,7 +167,7 @@ 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"
- name: Publish measured badges
env:
Generated
-4
View File
@@ -40,9 +40,7 @@ name = "alkane-artifacts"
version = "0.1.0"
dependencies = [
"alkane-core",
"flate2",
"sha2",
"tar",
"thiserror",
]
@@ -50,7 +48,6 @@ dependencies = [
name = "alkane-cli"
version = "0.1.0"
dependencies = [
"alkane-access",
"alkane-artifacts",
"alkane-core",
]
@@ -78,7 +75,6 @@ dependencies = [
"alkane-artifacts",
"alkane-core",
"sha2",
"tempfile",
"thiserror",
]
+95 -43
View File
@@ -1,6 +1,6 @@
# Alkane Toolkit
# alkane-toolkit
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/next.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
![tests](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/tests.svg)
![coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/coverage.svg)
![bench](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench.svg)
@@ -10,66 +10,118 @@
![dependencies](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/dependencies.svg)
![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg)
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
a patched [wx-rs bridge](thirdparty/wx-rs). Firmware installation is under
development.
The CI badge shows the last completed attempt for this branch while newer
runs are queued. Badge SVGs are stored in a private, machine-maintained branch.
The code-quality letter requires warnings-denied Clippy and measured test plus
UI self-test line coverage: A at 90%, B at 80%, C at 70%, D at 60%, and F
below 60%. A missing coverage measurement displays pending.
The benchmark delta compares an earlier commit only when its CPU class
matches the current dedicated runner; otherwise it establishes a new
baseline. Main CI runs microbenchmarks serially to avoid test contention.
## Run locally
A cross-platform desktop toolkit for discovering, monitoring, and re-flashing
ASIC miners. It scans a fleet over the network, shows live health and hashrate
in a sortable table. The install path is under development for **stock** and
**alkaneOS** firmware on boards running stock, VNish/AnthillOS, Braiins OS+,
LuxOS, ePIC, HiveOn, BixBit, WardenOS).
The core and UI are pure Rust; the native window is wxWidgets driven through a
vendored, patched [wx-rs](thirdparty/wx-rs) bridge, so there is no Electron,
no web view, and a single self-contained binary per platform.
## What it does
- **Discover** a fleet by CIDR or IP range and identify each miner's make,
model, control board, and firmware (via a vendored [asic-rs](vendor/asic-rs)).
- **Monitor** hashrate vs. expected, per-board health, chip temperatures, fans,
PSU state, and pool workers, with an Excel-style filter and drag-reorderable
columns.
- **Operate** miners from a right-click menu: flash the locate light, pause /
resume, restart, set a power or hashrate target, select a firmware profile
(LuxOS/VNish presets), configure pools, set the timezone, and change the
password -- each action offered only when every selected miner supports it.
- **Install firmware**: push stock or aftermarket images, or revert an
aftermarket miner to stock, behind a typed confirmation.
Discovery and telemetry are read-only and safe to run against any fleet; every
mutating action is capability-gated and, where destructive, confirmed.
## Build and run (Debian/Ubuntu)
```sh
scripts/build-wx-linux.sh
scripts/build-gui-linux.sh
ALKANE_FAKE_SCAN=1 ~/.cache/alkane-tk-target/release/alkane-toolkit
scripts/build-wx-linux.sh # once: builds the vendored wxWidgets 3.3.3 into ~/.cache
scripts/build-gui-linux.sh # cargo build --release -p alkane-gui
~/.cache/alkane-tk-target/release/alkane-toolkit
```
The first command builds wxWidgets 3.3.3 once. Linux needs GTK 3. Fake scan
uses offline fixtures and does not contact hardware. For Windows and macOS,
use the matching `scripts/build-gui-*.sh` script.
Runtime needs GTK 3: `sudo apt install libgtk-3-0`. To explore the UI with no
hardware, run the offline demo fleet:
## Current scope
```sh
ALKANE_FAKE_SCAN=1 alkane-toolkit
```
- Discover miners by CIDR or IP range with vendored [asic-rs](vendor/asic-rs).
- Show model, firmware, health, hashrate, temperatures, fans, PSU, and workers.
- Filter and sort the desktop table; inspect probes with `miner_probe`.
Windows and macOS share all GUI code; only the C++ bridge and wx build differ
(`scripts/build-gui-windows.sh` needs an msys2 toolchain, `-macos.sh` needs a
Mac).
Discovery is read-only. The installer and operator actions remain in the
[implementation plan](docs/IMPLEMENTATION-PLAN.md) and
[firmware matrix](docs/aftermarket-parity-roadmap.md).
## Command-line probe
`miner_probe` is a headless companion for hardware checks that should not go
through the window event loop -- discovery, telemetry, and each write action:
```sh
miner_probe scan 10.0.0.0/24 # discover + telemetry (TSV)
miner_probe presets 10.0.0.5 # list a firmware's selectable profiles
miner_probe setpreset 10.0.0.5 540MHz
```
Run `miner_probe` with no arguments for the full verb list.
## Development
```sh
WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \
CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" \
cargo test -p alkane-gui --offline
export WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config"
export CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" # keep the target tree off the source share
cargo test -p alkane-gui # unit tests
cargo test -p alkane-gui --release -- --ignored bench_ # microbenchmarks
cargo clippy -p alkane-gui --no-deps --bins -- -D warnings # lint gate
xvfb-run -a env ALKANE_SELFTEST=1 \
"$CARGO_TARGET_DIR/release/alkane-toolkit" # headless UI self-test
ci/coverage.sh --summary-only # coverage (tests + self-test)
```
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/).
CI mirrors these: `verify.yml` runs lint, tests, benchmarks, the self-test, and
a dependency audit on development branches. `release.yml` runs the full gate
on every `main` push and cuts an `X.Y.Z` release when the change warrants it.
`next.yml` builds release candidates with little testing and publishes `-rc`
releases. Dependencies are vendored under `vendor/`, so builds never touch the
network.
## Firmware safety
## Architecture
Installation must follow the [SDK install rules](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md):
use the exact board's packer and boot-switch procedure, verify through an
independent channel, and never write bootloader or secure regions.
- `crates/alkane-gui` -- the application: scan engine, data model, wxWidgets UI,
and the `miner_probe` CLI (the other `crates/alkane-*` are early scaffolding).
- `vendor/asic-rs` -- the miner-discovery and control library, vendored and
extended through numbered patches under `thirdparty/asic-rs/patches`.
- `thirdparty/wx-rs` -- the patched wxWidgets bridge (see `docs/adr/0002`,
`0003`).
After an Alkane image boots, compare its build marker with the verified
archive from a separate host:
See [`docs/IMPLEMENTATION-PLAN.md`](docs/IMPLEMENTATION-PLAN.md) for the roadmap
and [`docs/aftermarket-parity-roadmap.md`](docs/aftermarket-parity-roadmap.md)
for the firmware config/scan parity work.
```sh
alkane-cli verify-sdk-release <SHA256SUMS> <downloaded-board-archive>
alkane-cli verify-running-build <ip> <ssh-user> <absolute-known-hosts-file> <board> <sdk-commit> <os-commit>
```
## Firmware safety rules
The first command checks the release checksum, inner file list, checksums,
and SDK and OS revisions for a board archive. It prints the revisions to use
in the second command. The QEMU research archive has no board revision
metadata, so only its release checksum is checked. The second command reads
`/etc/alkane-build` over SSH and fails on a mismatch. Neither command installs
firmware or establishes the recovery path.
Encoded in code, from alkane-sdk `docs/install-methods.md`:
1. Never write the bootloader or secure region.
2. Verify on a channel the installer does not control.
3. Reboot is root-only; a dropped SSH connection can still be success.
4. A packer is per board; never reuse one across boards.
5. Boot-switch handling is an explicit, verified step.
## License
[MIT](LICENSE). Vendored dependencies keep their own terms.
Licensed under the [MIT license](LICENSE).
+9 -9
View File
@@ -1,11 +1,11 @@
{
"bench_parse_line_near_max_addrs": 644187.0,
"bench_parse_targets_many_ranges_near_cap": 49565223.0,
"bench_render_cells": 3037944.0,
"bench_sort_by_each_column": 816884.0,
"bench_targets_to_cidrs_large_range": 443875.0,
"bench_upsert_cold_start_population": 8871040.0,
"bench_view_pipeline": 177652.0,
"bench_view_pipeline_default_sort": 203830.0,
"bench_view_pipeline_with_filter": 187371.0
"bench_parse_line_near_max_addrs": 807160.0,
"bench_parse_targets_many_ranges_near_cap": 54465485.0,
"bench_render_cells": 3503112.0,
"bench_sort_by_each_column": 486975.0,
"bench_targets_to_cidrs_large_range": 482167.0,
"bench_upsert_cold_start_population": 8315814.0,
"bench_view_pipeline": 191794.0,
"bench_view_pipeline_default_sort": 193214.0,
"bench_view_pipeline_with_filter": 253085.0
}
+7 -7
View File
@@ -1,19 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="160.5" height="20" role="img" aria-label="bench coverage: pending">
<title>bench coverage: pending</title>
<svg xmlns="http://www.w3.org/2000/svg" width="128.0" height="20" role="img" aria-label="bench coverage: 7%">
<title>bench coverage: 7%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="160.5" height="20" rx="3" fill="#fff"/></clipPath>
<clipPath id="r"><rect width="128.0" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="103.0" height="20" fill="#555"/>
<rect x="103.0" width="57.5" height="20" fill="#9f9f9f"/>
<rect width="160.5" height="20" fill="url(#s)"/>
<rect x="103.0" width="25.0" height="20" fill="#e05d44"/>
<rect width="128.0" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="51.5" y="15" fill="#010101" fill-opacity=".3">bench coverage</text>
<text x="51.5" y="14">bench coverage</text>
<text x="131.8" y="15" fill="#010101" fill-opacity=".3">pending</text>
<text x="131.8" y="14">pending</text>
<text x="115.5" y="15" fill="#010101" fill-opacity=".3">7%</text>
<text x="115.5" y="14">7%</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 966 B

After

Width:  |  Height:  |  Size: 946 B

+7 -7
View File
@@ -1,19 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="147.5" height="20" role="img" aria-label="bench: -79.9% vs prev">
<title>bench: -79.9% vs prev</title>
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="bench: +7.4% vs prev">
<title>bench: +7.4% vs prev</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="147.5" height="20" rx="3" fill="#fff"/></clipPath>
<clipPath id="r"><rect width="141.0" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="44.5" height="20" fill="#555"/>
<rect x="44.5" width="103.0" height="20" fill="#4c1"/>
<rect width="147.5" height="20" fill="url(#s)"/>
<rect x="44.5" width="96.5" height="20" fill="#dfb317"/>
<rect width="141.0" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="22.2" y="15" fill="#010101" fill-opacity=".3">bench</text>
<text x="22.2" y="14">bench</text>
<text x="96.0" y="15" fill="#010101" fill-opacity=".3">-79.9% vs prev</text>
<text x="96.0" y="14">-79.9% vs prev</text>
<text x="92.8" y="15" fill="#010101" fill-opacity=".3">+7.4% vs prev</text>
<text x="92.8" y="14">+7.4% vs prev</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 952 B

After

Width:  |  Height:  |  Size: 950 B

+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="lines of code: 13.7k">
<title>lines of code: 13.7k</title>
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="lines of code: 13.7K">
<title>lines of code: 13.7K</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -13,7 +13,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="48.2" y="15" fill="#010101" fill-opacity=".3">lines of code</text>
<text x="48.2" y="14">lines of code</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">13.7k</text>
<text x="118.8" y="14">13.7k</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">13.7K</text>
<text x="118.8" y="14">13.7K</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 952 B

After

Width:  |  Height:  |  Size: 952 B

+45 -57
View File
@@ -1,8 +1,27 @@
#!/usr/bin/env python3
"""Check the Toolkit benchmark suite and compare it with the prior release."""
"""Compute the weighted-average microbenchmark delta versus the previous release.
Reads the captured stdout of `cargo test ... --ignored --nocapture bench_` (whose
timings are Rust `Duration` Debug strings: "12.3ms", "512us"/"512µs", "840ns",
"1.2s"), compares each bench to a committed baseline of the previous release's
numbers, and prints the time-weighted average change as a signed percentage:
(sum(current) / sum(baseline) - 1) * 100 over benches present in both
Weighting by duration means the slow benches dominate, so the number tracks
overall wall-time change rather than giving a tiny bench equal say. Then the
baseline is rewritten with the current numbers, so the next release compares
against this one ("the previous commit").
Usage:
bench-badge.py --current bench-current.txt --baseline badges/bench-baseline.json
Prints the delta as a plain number (e.g. "-3.2", or "NEW" when there is no
usable baseline) to stdout. The baseline JSON lives under badges/ so committing
it back does not trip compute-version.sh's path-based release bump.
"""
import argparse
import json
import math
import os
import re
import sys
@@ -10,17 +29,9 @@ import sys
# A Duration Debug token: a number immediately followed by a time unit, with the
# multi-char units listed before the bare "s" so alternation prefers them. The
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|\u00b5s|us|ms|s)(?![a-zA-Z])")
_UNIT_NS = {"ns": 1.0, "us": 1e3, "\u00b5s": 1e3, "ms": 1e6, "s": 1e9}
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|µs|us|ms|s)(?![a-zA-Z])")
_UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9}
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
EXPECTED_BENCHES = {
"bench_naming_transforms",
"bench_parse_line_near_max_addrs", "bench_parse_targets_many_ranges_near_cap",
"bench_targets_to_cidrs_large_range", "bench_view_pipeline",
"bench_render_cells", "bench_health_diagnostics",
"bench_view_pipeline_default_sort", "bench_sort_by_each_column",
"bench_view_pipeline_with_filter", "bench_upsert_cold_start_population",
}
def parse_bench(text: str) -> dict:
@@ -33,33 +44,12 @@ def parse_bench(text: str) -> dict:
continue
durs = _DUR.findall(line)
if not durs:
raise ValueError(f"missing timing for {m.group(1)}")
continue
val, unit = durs[-1]
elapsed = float(val) * _UNIT_NS[unit]
if m.group(1) in out or not math.isfinite(elapsed) or elapsed <= 0:
raise ValueError(f"duplicate or invalid timing for {m.group(1)}")
out[m.group(1)] = elapsed
out[m.group(1)] = float(val) * _UNIT_NS[unit]
return out
def require_suite(results: dict) -> dict:
if results.keys() != EXPECTED_BENCHES:
raise ValueError("microbenchmark results differ from the declared suite")
return results
def benchmark_delta(current: dict, baseline: dict) -> float | None:
"""Average each comparable benchmark's percentage improvement."""
if not baseline:
return None
changes = [(baseline[name] - current[name]) / baseline[name]
for name in baseline]
delta = math.fsum(changes) / len(changes) * 100
if not math.isfinite(delta):
raise ValueError("benchmark comparison is not finite")
return delta
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--current", required=True, help="captured bench stdout")
@@ -69,34 +59,32 @@ def main() -> int:
try:
with open(args.current, encoding="utf-8") as fh:
current = require_suite(parse_bench(fh.read()))
except (OSError, ValueError) as e:
current = parse_bench(fh.read())
except OSError as e:
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
return 1
print("NEW")
return 0
if not current:
print("bench-badge: no bench lines parsed from current results", file=sys.stderr)
print("NEW")
return 0
baseline = {}
try:
with open(args.baseline, encoding="utf-8") as fh:
baseline = json.load(fh)
except FileNotFoundError:
pass
except (OSError, ValueError) as e:
print(f"bench-badge: invalid baseline: {e}", file=sys.stderr)
return 1
if (not isinstance(baseline, dict)
or not set(baseline).issubset(current)
or any(not isinstance(value, (int, float)) or isinstance(value, bool)
or not math.isfinite(value) or value <= 0
for value in baseline.values())):
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
return 1
baseline = {k: float(v) for k, v in json.load(fh).items()}
except (OSError, ValueError):
baseline = {}
try:
delta = benchmark_delta(current, baseline)
except ValueError as error:
print(f"bench-badge: {error}", file=sys.stderr)
return 1
print("NEW" if delta is None else f"{delta:.1f}")
common = [k for k in current if k in baseline and baseline[k] > 0]
if common:
sum_new = sum(current[k] for k in common)
sum_old = sum(baseline[k] for k in common)
delta = (sum_new / sum_old - 1.0) * 100.0 if sum_old > 0 else 0.0
print(f"{delta:.1f}")
else:
print("NEW")
if not args.no_write:
os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True)
+3 -10
View File
@@ -126,7 +126,7 @@ def render_html(index: dict) -> str:
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("prepare", "publish", "render"))
parser.add_argument("action", choices=("prepare", "publish"))
args = parser.parse_args()
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
@@ -141,15 +141,8 @@ def main() -> None:
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements")
return
if args.action == "render":
if not index["entries"]:
raise ValueError("no measured benchmark history to publish")
Path("bench-site").mkdir(exist_ok=True)
Path("bench-site/index.html").write_text(render_html(index))
print(f"Rendered {len(index['entries'])} measured benchmark commits")
return
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
Path("bench-current.txt").read_text())), "bench_host": benchmark_host()}
metrics = {"bench_ns_per_op": bench_badge.parse_bench(
Path("bench-current.txt").read_text()), "bench_host": benchmark_host()}
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp)
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
+1 -1
View File
@@ -9,7 +9,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
DIRECTORIES = ("target", "dist", "coverage")
FILES = ("bench-current.txt",)
+12 -13
View File
@@ -2,11 +2,10 @@
# Measure line coverage from BOTH the unit tests AND the headless UI self-test.
#
# The self-test (ALKANE_SELFTEST=1) builds the real wxWidgets table, renders every
# fixture through the real widgets, and checks each cell against the model.
# It covers the fixture-rendering path, while interactive event handlers need
# separate tests. Because it runs as a separate binary invocation, a plain
# `cargo llvm-cov` (which only runs the #[test]s) never counts it. This
# combines both runs' coverage.
# fixture through the real widgets, and checks each cell against the model -- it
# exercises most of ui.rs. Because it runs as a separate binary invocation, a plain
# `cargo llvm-cov` (which only runs the #[test]s) never counts it, so ui.rs shows
# ~4% even though it is integration-tested. This combines both runs' coverage.
#
# Usage: ci/coverage.sh [extra `cargo llvm-cov report` args, e.g. --summary-only]
set -euo pipefail
@@ -17,12 +16,8 @@ export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$HOME/.cache/wx-3.3.3-linux/bin/wx-conf
# default; override with CARGO_LLVM_COV_FLAGS if you need something else.
read -ra CARGO_FLAGS <<<"${CARGO_LLVM_COV_FLAGS:---offline}"
# A display is required for the self-test; skipping it would publish an
# incomplete coverage number as if the measured test set had run.
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "coverage.sh: xvfb-run is required for the UI self-test" >&2
exit 1
fi
# A display for the self-test's real widgets.
need_xvfb() { command -v xvfb-run >/dev/null 2>&1; }
cargo llvm-cov clean --workspace
@@ -32,8 +27,12 @@ cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" \
-p alkane-artifacts -p alkane-flash -p alkane-cli
# 2. Headless UI self-test, under the same instrumentation, its coverage appended.
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
if need_xvfb; then
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
else
echo "coverage.sh: xvfb-run not found; skipping the self-test run (unit tests only)" >&2
fi
# 3. Merged report, our source only (vendored asic-rs + the patched wx-rs bridge
# are out of scope).
+21 -15
View File
@@ -108,13 +108,13 @@ def loc_color(n: int) -> str:
def bench_color(delta_pct: float) -> str:
# Positive delta means faster than the previous release. A +/-2% band
# absorbs run-to-run jitter on the dedicated CI runner.
if delta_pct >= 2.0:
# Negative delta = faster than the previous release. A +/-2% dead band absorbs
# the run-to-run jitter of microbenchmarks on a shared CI runner.
if delta_pct <= -2.0:
return "brightgreen"
if delta_pct > -2.0:
if delta_pct < 2.0:
return "blue"
if delta_pct > -10.0:
if delta_pct < 10.0:
return "yellow"
return "orange"
@@ -131,10 +131,15 @@ def cov_color(pct: float) -> str:
return "red"
def quality_grade(clippy: str | None) -> str:
if clippy is None:
def quality_grade(clippy: str, coverage: float | None) -> str:
if clippy != "clean":
return "F"
if coverage is None:
return "pending"
return "A" if clippy == "clean" else "F"
for minimum, grade in ((90, "A"), (80, "B"), (70, "C"), (60, "D")):
if coverage >= minimum:
return grade
return "F"
def human(n: int) -> str:
@@ -161,10 +166,11 @@ def main() -> int:
ap.add_argument("--coverage", type=float, default=None)
ap.add_argument("--bench-coverage", type=float, default=None)
ap.add_argument("--bench", default=None)
# Mean per-benchmark improvement vs the previous release, as a signed
# percentage string, or "NEW" when there is no baseline.
# Weighted-average microbench delta vs the previous release, as a signed
# percentage string (e.g. "-3.2"), or "NEW"/"" when there is no baseline yet
# (round 19 #1). Takes precedence over --bench for the bench badge.
ap.add_argument("--bench-delta", default=None)
ap.add_argument("--clippy", choices=("clean", "failed"))
ap.add_argument("--clippy", default="clean")
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):
@@ -185,7 +191,7 @@ 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)
grade = quality_grade(args.clippy, args.coverage)
write("quality", "code quality", grade,
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
@@ -196,8 +202,8 @@ def main() -> int:
write("bench-coverage", "bench coverage",
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
# Bench badge: prefer the mean per-benchmark improvement vs the previous
# release. Use the static label when no comparison is available.
# Bench badge: prefer the weighted-average delta vs the previous release; fall
# back to the static label (first run, or when the delta could not be computed).
delta = None
if args.bench_delta not in (None, "", "NEW"):
try:
@@ -205,7 +211,7 @@ def main() -> int:
except ValueError:
delta = None
if delta is not None:
# Positive = faster than the previous release.
# Negative = faster than the previous release (good).
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
write("bench", "bench", msg, bench_color(delta))
elif args.bench_delta == "NEW":
-121
View File
@@ -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()
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check that every Toolkit benchmark contributes to the release badge."""
import importlib.util
import re
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("bench_badge", ROOT / "ci/bench-badge.py")
assert spec is not None and spec.loader is not None
badge = importlib.util.module_from_spec(spec)
spec.loader.exec_module(badge)
badge_spec = importlib.util.spec_from_file_location("gen_badges", ROOT / "ci/gen-badges.py")
assert badge_spec is not None and badge_spec.loader is not None
gen_badges = importlib.util.module_from_spec(badge_spec)
badge_spec.loader.exec_module(gen_badges)
class BenchBadgeTests(unittest.TestCase):
def test_declared_suite_matches_rust_benchmarks(self):
names = set()
for directory in (ROOT / "crates/alkane-gui/src", ROOT / "crates/alkane-artifacts/src"):
for path in directory.rglob("*.rs"):
names.update(re.findall(
r'#\[test\]\s*#\[ignore(?:\s*=\s*"[^"]*")?\]\s*'
r'fn (bench_[A-Za-z0-9_]+)\s*\(', path.read_text()))
self.assertEqual(names, badge.EXPECTED_BENCHES)
def test_incomplete_duplicate_and_malformed_results_fail(self):
lines = [f"test tests::{name} ... {name}: 10ms/op"
for name in sorted(badge.EXPECTED_BENCHES)]
values = badge.require_suite(badge.parse_bench("\n".join(lines)))
self.assertEqual(len(values), len(badge.EXPECTED_BENCHES))
with self.assertRaisesRegex(ValueError, "declared suite"):
badge.require_suite(badge.parse_bench("\n".join(lines[:-1])))
with self.assertRaisesRegex(ValueError, "duplicate"):
badge.parse_bench("\n".join(lines + [lines[0]]))
with self.assertRaisesRegex(ValueError, "missing timing"):
badge.parse_bench(lines[0].replace("10ms/op", "missing"))
def test_badge_averages_each_benchmark_improvement(self):
current = {"short": 50.0, "long": 900.0}
baseline = {"short": 100.0, "long": 1000.0}
self.assertEqual(badge.benchmark_delta(current, baseline), 30.0)
self.assertAlmostEqual(badge.benchmark_delta(baseline, current), -55.5555556)
self.assertIsNone(badge.benchmark_delta(current, {}))
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
if __name__ == "__main__":
unittest.main()
+1 -537
View File
@@ -1,537 +1 @@
// SPDX-License-Identifier: MIT
//! Bounded, read-only SSH probes for board identification.
use std::collections::HashSet;
use std::fs;
use std::io::{self, Read};
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
const MAX_PROBE_BYTES: usize = 64 * 1024;
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Probe {
KernelRelease,
MtdTable,
DeviceTreeModel,
AlkaneBuildMarker,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AlkaneBuildMarker {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildMarkerError {
InvalidFormat,
InvalidBoard,
InvalidRevision,
UnexpectedBuild,
}
/// A running board must report the identity embedded in the CI artifact.
/// This parser accepts the exact three-line marker emitted by the SDK.
pub fn parse_build_marker(bytes: &[u8]) -> Result<AlkaneBuildMarker, BuildMarkerError> {
if bytes.len() > 256 {
return Err(BuildMarkerError::InvalidFormat);
}
let text = std::str::from_utf8(bytes).map_err(|_| BuildMarkerError::InvalidFormat)?;
let mut lines = text.lines();
let board = lines
.next()
.and_then(|line| line.strip_prefix("board="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let sdk_revision = lines
.next()
.and_then(|line| line.strip_prefix("sdk_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let os_revision = lines
.next()
.and_then(|line| line.strip_prefix("os_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
if lines.next().is_some() || !text.ends_with('\n') {
return Err(BuildMarkerError::InvalidFormat);
}
if !matches!(
board,
"am335x-bb"
| "zynq-7010"
| "cv1835"
| "a113d"
| "allwinner-h3"
| "allwinner-h6"
| "allwinner-h616"
) {
return Err(BuildMarkerError::InvalidBoard);
}
for revision in [sdk_revision, os_revision] {
if revision.len() != 40
|| !revision
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
{
return Err(BuildMarkerError::InvalidRevision);
}
}
Ok(AlkaneBuildMarker {
board: board.to_owned(),
sdk_revision: sdk_revision.to_owned(),
os_revision: os_revision.to_owned(),
})
}
pub fn verify_build_marker(
observed: &AlkaneBuildMarker,
expected: &AlkaneBuildMarker,
) -> Result<(), BuildMarkerError> {
if observed == expected {
Ok(())
} else {
Err(BuildMarkerError::UnexpectedBuild)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdPartition {
pub index: u32,
pub size_bytes: u64,
pub erase_bytes: u64,
pub name: String,
}
/// The partition identity and geometry required by an SDK flash plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdRequirement {
pub index: u32,
pub name: String,
pub size_bytes: u64,
pub erase_bytes: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdTarget {
pub device: PathBuf,
pub size_bytes: u64,
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdMatchError {
MissingIndex,
AmbiguousIndex,
NameMismatch,
SizeMismatch,
EraseMismatch,
}
/// Resolve a character device only after comparing the observed partition
/// with the expected identity and geometry. This does not authorize a write.
pub fn resolve_mtd_target(
observed: &[MtdPartition],
expected: &MtdRequirement,
) -> Result<MtdTarget, MtdMatchError> {
let mut matches = observed
.iter()
.filter(|entry| entry.index == expected.index);
let entry = matches.next().ok_or(MtdMatchError::MissingIndex)?;
if matches.next().is_some() {
return Err(MtdMatchError::AmbiguousIndex);
}
if entry.name != expected.name {
return Err(MtdMatchError::NameMismatch);
}
if entry.size_bytes != expected.size_bytes {
return Err(MtdMatchError::SizeMismatch);
}
if entry.erase_bytes != expected.erase_bytes {
return Err(MtdMatchError::EraseMismatch);
}
Ok(MtdTarget {
device: PathBuf::from(format!("/dev/mtd{}", entry.index)),
size_bytes: entry.size_bytes,
})
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdError {
InvalidHeader,
InvalidEntry(usize),
DuplicateIndex,
DuplicateName,
TooManyEntries,
}
/// Parse `/proc/mtd` as data. A flash plan must match both partition index
/// and name against its board-specific layout before using a device path.
pub fn parse_mtd_table(bytes: &[u8]) -> Result<Vec<MtdPartition>, MtdError> {
if bytes.len() > MAX_PROBE_BYTES {
return Err(MtdError::TooManyEntries);
}
let text = std::str::from_utf8(bytes).map_err(|_| MtdError::InvalidHeader)?;
let mut lines = text.lines();
if lines
.next()
.map(str::split_whitespace)
.map(Iterator::collect::<Vec<_>>)
!= Some(vec!["dev:", "size", "erasesize", "name"])
{
return Err(MtdError::InvalidHeader);
}
let mut entries = Vec::new();
let mut indices = HashSet::new();
let mut names = HashSet::new();
for (offset, line) in lines.enumerate() {
if line.trim().is_empty() {
continue;
}
let line_number = offset + 2;
if entries.len() >= 128 {
return Err(MtdError::TooManyEntries);
}
let invalid = || MtdError::InvalidEntry(line_number);
let start = line.find('"').ok_or_else(invalid)?;
let end = line.rfind('"').ok_or_else(invalid)?;
if start == end || !line[end + 1..].trim().is_empty() {
return Err(invalid());
}
let fields: Vec<_> = line[..start].split_whitespace().collect();
if fields.len() != 3 {
return Err(invalid());
}
let index = fields[0]
.strip_prefix("mtd")
.and_then(|value| value.strip_suffix(':'))
.and_then(|value| value.parse::<u32>().ok())
.ok_or_else(invalid)?;
let size_bytes = u64::from_str_radix(fields[1], 16).map_err(|_| invalid())?;
let erase_bytes = u64::from_str_radix(fields[2], 16).map_err(|_| invalid())?;
let name = &line[start + 1..end];
if size_bytes == 0
|| erase_bytes == 0
|| name.is_empty()
|| name.len() > 128
|| !name
.bytes()
.all(|byte| byte.is_ascii_graphic() || byte == b' ')
|| name.contains('"')
{
return Err(invalid());
}
if !indices.insert(index) {
return Err(MtdError::DuplicateIndex);
}
if !names.insert(name.to_owned()) {
return Err(MtdError::DuplicateName);
}
entries.push(MtdPartition {
index,
size_bytes,
erase_bytes,
name: name.to_owned(),
});
}
if entries.is_empty() {
return Err(MtdError::InvalidHeader);
}
Ok(entries)
}
impl Probe {
fn command(self) -> &'static str {
match self {
Self::KernelRelease => "uname -r",
Self::MtdTable => "cat /proc/mtd",
Self::DeviceTreeModel => "cat /proc/device-tree/model",
Self::AlkaneBuildMarker => "cat /etc/alkane-build",
}
}
}
#[derive(Debug)]
pub enum AccessError {
InvalidTarget,
InvalidKnownHosts,
Timeout,
OutputTooLarge,
RemoteFailure,
Io(io::Error),
}
impl From<io::Error> for AccessError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
pub struct SshTarget {
address: IpAddr,
port: u16,
user: String,
known_hosts: PathBuf,
}
impl SshTarget {
pub fn new(
address: IpAddr,
port: u16,
user: &str,
known_hosts: &Path,
) -> Result<Self, AccessError> {
if port == 0
|| user.is_empty()
|| !user
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
{
return Err(AccessError::InvalidTarget);
}
if !known_hosts.is_absolute()
|| !fs::metadata(known_hosts).is_ok_and(|metadata| metadata.is_file())
{
return Err(AccessError::InvalidKnownHosts);
}
Ok(Self {
address,
port,
user: user.to_owned(),
known_hosts: known_hosts.to_owned(),
})
}
fn command(&self, probe: Probe) -> Command {
let mut command = Command::new("ssh");
command
.arg("-F")
.arg("none")
.arg("-o")
.arg("BatchMode=yes")
.arg("-o")
.arg("StrictHostKeyChecking=yes")
.arg("-o")
.arg("GlobalKnownHostsFile=none")
.arg("-o")
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
.arg("-o")
.arg("ConnectTimeout=5")
.arg("-o")
.arg("ServerAliveInterval=5")
.arg("-o")
.arg("ServerAliveCountMax=1")
.arg("-o")
.arg("RequestTTY=no")
.arg("-p")
.arg(self.port.to_string())
.arg(format!("{}@{}", self.user, self.address))
.arg(probe.command());
command
}
pub fn probe(&self, probe: Probe) -> Result<Vec<u8>, AccessError> {
run_bounded(self.command(probe))
}
}
fn collect_bounded<R: Read + Send + 'static>(
mut reader: R,
) -> thread::JoinHandle<Result<Vec<u8>, AccessError>> {
thread::spawn(move || {
let mut data = Vec::new();
let mut chunk = [0_u8; 4096];
loop {
let count = reader.read(&mut chunk)?;
if count == 0 {
return Ok(data);
}
if data.len() + count > MAX_PROBE_BYTES {
return Err(AccessError::OutputTooLarge);
}
data.extend_from_slice(&chunk[..count]);
}
})
}
fn run_bounded(command: Command) -> Result<Vec<u8>, AccessError> {
run_bounded_with_timeout(command, PROBE_TIMEOUT)
}
fn run_bounded_with_timeout(
mut command: Command,
timeout: Duration,
) -> Result<Vec<u8>, AccessError> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let stdout = collect_bounded(child.stdout.take().expect("piped stdout"));
let stderr = collect_bounded(child.stderr.take().expect("piped stderr"));
let deadline = Instant::now() + timeout;
let result = loop {
if let Some(status) = child.try_wait()? {
break status.success();
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = stdout.join();
let _ = stderr.join();
return Err(AccessError::Timeout);
}
thread::sleep(Duration::from_millis(10));
};
let output = stdout.join().map_err(|_| AccessError::RemoteFailure)??;
let error_output = stderr.join().map_err(|_| AccessError::RemoteFailure)??;
if !result || !error_output.is_empty() {
return Err(AccessError::RemoteFailure);
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn target_rejects_injected_user_and_unknown_host_file() {
let address = "127.0.0.1".parse().unwrap();
assert!(matches!(
SshTarget::new(
address,
22,
"root;id",
Path::new("/etc/ssh/ssh_known_hosts")
),
Err(AccessError::InvalidTarget)
));
assert!(matches!(
SshTarget::new(address, 22, "root", Path::new("relative-known-hosts")),
Err(AccessError::InvalidKnownHosts)
));
}
#[cfg(unix)]
#[test]
fn bounded_runner_rejects_excess_output_and_failed_command() {
let mut success = Command::new("/bin/sh");
success.args(["-c", "printf board"]);
assert_eq!(run_bounded(success).unwrap(), b"board");
let mut overflow = Command::new("/bin/sh");
overflow.args(["-c", "head -c 70000 /dev/zero"]);
assert!(matches!(
run_bounded(overflow),
Err(AccessError::OutputTooLarge)
));
let mut failed = Command::new("/bin/sh");
failed.args(["-c", "exit 7"]);
assert!(matches!(
run_bounded(failed),
Err(AccessError::RemoteFailure)
));
let mut hanging = Command::new("/bin/sleep");
hanging.arg("1");
assert!(matches!(
run_bounded_with_timeout(hanging, Duration::from_millis(20)),
Err(AccessError::Timeout)
));
}
#[test]
fn parses_captured_mtd_layout_and_rejects_duplicate_targets() {
let captured = b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n";
let entries = parse_mtd_table(captured).unwrap();
assert_eq!(entries[0].index, 0);
assert_eq!(entries[0].size_bytes, 0x0280_0000);
assert_eq!(entries[0].erase_bytes, 0x0002_0000);
assert_eq!(entries[0].name, "BOOT.bin-dts-marker-kernel");
let duplicate = b"dev: size erasesize name\n\
mtd0: 00020000 00020000 \"boot\"\n\
mtd0: 00020000 00020000 \"root\"\n";
assert_eq!(parse_mtd_table(duplicate), Err(MtdError::DuplicateIndex));
assert_eq!(
parse_mtd_table(b"mtd0: 1 1 \"boot\"\n"),
Err(MtdError::InvalidHeader)
);
}
#[test]
fn flash_target_requires_captured_identity_and_geometry() {
let observed = parse_mtd_table(
b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n",
)
.unwrap();
let mut required = MtdRequirement {
index: 0,
name: "BOOT.bin-dts-marker-kernel".to_owned(),
size_bytes: 0x0280_0000,
erase_bytes: 0x0002_0000,
};
assert_eq!(
resolve_mtd_target(&observed, &required).unwrap().device,
Path::new("/dev/mtd0")
);
required.name = "ramfs".to_owned();
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::NameMismatch)
);
required.name = observed[0].name.clone();
required.size_bytes -= 1;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::SizeMismatch)
);
required.size_bytes = observed[0].size_bytes;
required.erase_bytes *= 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::EraseMismatch)
);
required.index = 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::MissingIndex)
);
}
#[test]
fn running_build_marker_must_match_the_artifact() {
let sha = "0123456789abcdef0123456789abcdef01234567";
let marker = format!("board=am335x-bb\nsdk_revision={sha}\nos_revision={sha}\n");
let expected = parse_build_marker(marker.as_bytes()).unwrap();
assert_eq!(verify_build_marker(&expected, &expected), Ok(()));
let other = AlkaneBuildMarker {
board: "zynq-7010".to_owned(),
..expected.clone()
};
assert_eq!(
verify_build_marker(&expected, &other),
Err(BuildMarkerError::UnexpectedBuild)
);
assert_eq!(
parse_build_marker(
marker
.replace("board=am335x-bb", "board=unknown")
.as_bytes()
),
Err(BuildMarkerError::InvalidBoard)
);
assert_eq!(
parse_build_marker(marker.replace(sha, "not-a-commit").as_bytes()),
Err(BuildMarkerError::InvalidRevision)
);
assert_eq!(
parse_build_marker(format!("{marker}extra=value\n").as_bytes()),
Err(BuildMarkerError::InvalidFormat)
);
}
}
// alkane-access
-2
View File
@@ -8,5 +8,3 @@ license.workspace = true
alkane-core = { path = "../alkane-core" }
sha2.workspace = true
thiserror.workspace = true
flate2 = "1"
tar = "0.4"
+1 -345
View File
@@ -1,9 +1,8 @@
// SPDX-License-Identifier: MIT
//! Verify local firmware artifacts before an install path consumes them.
use flate2::read::GzDecoder;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
@@ -11,26 +10,6 @@ use thiserror::Error;
const SEED: &str = include_str!("../data/manifest-seed.csv");
const HEADER: &str = "sha256,size_bytes,path,family,format,applicability";
const SDK_RELEASE_ASSETS: [&str; 8] = [
"alkane-sdk-a113d.tar.gz",
"alkane-sdk-allwinner-h3.tar.gz",
"alkane-sdk-allwinner-h6.tar.gz",
"alkane-sdk-allwinner-h616.tar.gz",
"alkane-sdk-am335x-bb.tar.gz",
"alkane-sdk-cv1835.tar.gz",
"alkane-sdk-qemu-zynq-research.tar.gz",
"alkane-sdk-zynq-7010.tar.gz",
];
const MAX_SDK_FILES: usize = 64;
const MAX_SDK_FILE_BYTES: u64 = 1024 * 1024 * 1024;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SdkArchiveInfo {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
pub artifact_count: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArtifactRecord {
@@ -56,10 +35,6 @@ pub enum VerifyError {
Digest,
#[error("artifact format is not recognized")]
UnsupportedFormat,
#[error("release asset name or path is invalid")]
ReleasePath,
#[error("SDK release archive contents are invalid")]
ReleaseContents,
}
/// A verified, rewound descriptor. Consumers should read this descriptor
@@ -133,205 +108,6 @@ pub fn parse_manifest(text: &str) -> Result<Vec<ArtifactRecord>, VerifyError> {
Ok(records)
}
/// Verify one archive against the complete checksum sidecar from its SDK
/// release. Keep the returned descriptor for any subsequent guarded use.
pub fn verify_sdk_release_archive(
checksums: &Path,
archive: &Path,
) -> Result<VerifiedArtifact, VerifyError> {
if std::fs::metadata(checksums)?.len() > 4096 {
return Err(VerifyError::Manifest(1));
}
let name = archive
.file_name()
.and_then(|value| value.to_str())
.ok_or(VerifyError::ReleasePath)?;
let listed = parse_sdk_release_checksums(&std::fs::read_to_string(checksums)?)?;
let sha256 = listed
.into_iter()
.find_map(|(entry, digest)| (entry == name).then_some(digest))
.ok_or(VerifyError::ReleasePath)?;
let record = ArtifactRecord {
sha256,
size_bytes: std::fs::metadata(archive)?.len(),
path: PathBuf::from(name),
family: name
.strip_prefix("alkane-sdk-")
.and_then(|value| value.strip_suffix(".tar.gz"))
.ok_or(VerifyError::ReleasePath)?
.to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
verify_file(archive, &record)
}
/// Check the inner file list and revisions of a previously verified SDK archive.
/// This reads the verified descriptor; it never extracts archive paths.
pub fn inspect_sdk_release_archive(
verified: &mut VerifiedArtifact,
) -> Result<SdkArchiveInfo, VerifyError> {
let board = verified
.record
.family
.strip_prefix("qemu-")
.unwrap_or(&verified.record.family)
.to_owned();
let prefix = format!("alkane-sdk-{board}/");
verified.file.seek(SeekFrom::Start(0))?;
let decoder = GzDecoder::new(&mut verified.file);
let mut archive = tar::Archive::new(decoder);
let mut digests = HashMap::new();
let mut metadata = HashMap::new();
let mut count = 0;
for entry in archive.entries()?.raw(true) {
let mut entry = entry?;
count += 1;
if count > MAX_SDK_FILES {
return Err(VerifyError::ReleaseContents);
}
let path = entry.path_bytes().into_owned();
if count == 1 {
if !entry.header().entry_type().is_dir()
|| path.as_slice() != prefix.trim_end_matches('/').as_bytes()
&& path.as_slice() != prefix.as_bytes()
{
return Err(VerifyError::ReleaseContents);
}
continue;
}
if !entry.header().entry_type().is_file()
|| entry.size() > MAX_SDK_FILE_BYTES
|| !path.starts_with(prefix.as_bytes())
{
return Err(VerifyError::ReleaseContents);
}
let name =
std::str::from_utf8(&path[prefix.len()..]).map_err(|_| VerifyError::ReleaseContents)?;
if name.is_empty()
|| name == "."
|| name == ".."
|| !name.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-')
})
|| digests.contains_key(name)
{
return Err(VerifyError::ReleaseContents);
}
let mut hasher = Sha256::new();
let mut contents = Vec::new();
let is_metadata = matches!(name, "SDK-REVISION" | "OS-REVISION" | "SHA256SUMS");
if is_metadata && entry.size() > 100_000 {
return Err(VerifyError::ReleaseContents);
}
let mut buffer = [0_u8; 64 * 1024];
let mut read_bytes = 0_u64;
loop {
let length = entry.read(&mut buffer)?;
if length == 0 {
break;
}
read_bytes += length as u64;
hasher.update(&buffer[..length]);
if is_metadata {
contents.extend_from_slice(&buffer[..length]);
}
}
if read_bytes != entry.size() {
return Err(VerifyError::ReleaseContents);
}
if is_metadata {
metadata.insert(name.to_owned(), contents);
}
digests.insert(name.to_owned(), format!("{:x}", hasher.finalize()));
}
let mut decoder = archive.into_inner();
// Drain the gzip trailer to check its CRC, with a bound on tar padding.
if std::io::copy(
&mut decoder.by_ref().take(1024 * 1024 + 1),
&mut std::io::sink(),
)? > 1024 * 1024
{
return Err(VerifyError::ReleaseContents);
}
drop(decoder);
verified.revalidate()?;
let revision = |key| -> Result<String, VerifyError> {
let bytes = metadata.get(key).ok_or(VerifyError::ReleaseContents)?;
if bytes.len() != 41 || bytes[40] != b'\n' || !bytes[..40].iter().all(u8::is_ascii_hexdigit)
{
return Err(VerifyError::ReleaseContents);
}
let text = std::str::from_utf8(&bytes[..40]).map_err(|_| VerifyError::ReleaseContents)?;
if !text
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
{
return Err(VerifyError::ReleaseContents);
}
Ok(text.to_owned())
};
let sdk_revision = revision("SDK-REVISION")?;
let os_revision = revision("OS-REVISION")?;
let checksums = metadata
.get("SHA256SUMS")
.ok_or(VerifyError::ReleaseContents)?;
let text = std::str::from_utf8(checksums).map_err(|_| VerifyError::ReleaseContents)?;
if !text.ends_with('\n') {
return Err(VerifyError::ReleaseContents);
}
let mut listed = HashMap::new();
for line in text.lines() {
let (digest, name) = line
.split_once(" ./")
.ok_or(VerifyError::ReleaseContents)?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !digests.contains_key(name)
|| listed.insert(name.to_owned(), digest.to_owned()).is_some()
{
return Err(VerifyError::ReleaseContents);
}
}
digests.remove("SHA256SUMS");
if listed != digests || digests.len() < 3 {
return Err(VerifyError::ReleaseContents);
}
Ok(SdkArchiveInfo {
board,
sdk_revision,
os_revision,
artifact_count: digests.len() - 2,
})
}
fn parse_sdk_release_checksums(text: &str) -> Result<Vec<(String, String)>, VerifyError> {
let mut entries = Vec::new();
let mut names = HashSet::new();
for (index, line) in text.lines().enumerate() {
let line_number = index + 1;
let (digest, name) = line
.split_once(" ")
.ok_or(VerifyError::Manifest(line_number))?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !SDK_RELEASE_ASSETS.contains(&name)
|| !names.insert(name.to_owned())
{
return Err(VerifyError::Manifest(line_number));
}
entries.push((name.to_owned(), digest.to_owned()));
}
if !text.ends_with('\n') || entries.len() != SDK_RELEASE_ASSETS.len() {
return Err(VerifyError::Manifest(1));
}
Ok(entries)
}
fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
let prefix: &[u8] = match format {
"IMAGEWTY-SD" | "update-zip" | "zip-installer" => b"PK\x03\x04",
@@ -340,7 +116,6 @@ fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
"wm-package-0x9a5ba57c" => b"\x7c\xa5\x5b\x9a",
"bmu" => b"\x26\x01",
"bin-AES-container" => b"\x3f\x0a\x64\xae",
"tar-gzip" => b"\x1f\x8b",
_ => return Err(VerifyError::UnsupportedFormat),
};
Ok(first.starts_with(prefix))
@@ -453,125 +228,6 @@ mod tests {
std::fs::remove_file(path).unwrap();
}
#[test]
fn sdk_release_requires_every_asset_and_exact_archive_digest() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-release-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join(SDK_RELEASE_ASSETS[0]);
let checksums = directory.join("SHA256SUMS");
let bytes = b"\x1f\x8bfixture";
std::fs::write(&archive, bytes).unwrap();
let digest: String = Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let manifest = SDK_RELEASE_ASSETS
.iter()
.map(|name| format!("{digest} {name}\n"))
.collect::<String>();
std::fs::write(&checksums, &manifest).unwrap();
let mut verified = verify_sdk_release_archive(&checksums, &archive).unwrap();
verified.revalidate().unwrap();
std::fs::write(&archive, b"\x1f\x8bfixturX").unwrap();
assert!(matches!(verified.revalidate(), Err(VerifyError::Digest)));
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Digest)
));
std::fs::write(
&checksums,
manifest.lines().take(7).collect::<Vec<_>>().join("\n") + "\n",
)
.unwrap();
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Manifest(1))
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_file(checksums).unwrap();
std::fs::remove_dir(directory).unwrap();
}
fn board_archive(files: &[(&str, &[u8])]) -> Vec<u8> {
let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
let mut builder = tar::Builder::new(encoder);
let mut directory = tar::Header::new_gnu();
directory.set_entry_type(tar::EntryType::Directory);
directory.set_size(0);
directory.set_mode(0o755);
directory.set_cksum();
builder
.append_data(&mut directory, "alkane-sdk-am335x-bb/", std::io::empty())
.unwrap();
for &(name, contents) in files {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(0o644);
header.set_cksum();
builder
.append_data(
&mut header,
format!("alkane-sdk-am335x-bb/{name}"),
contents,
)
.unwrap();
}
builder.into_inner().unwrap().finish().unwrap()
}
#[test]
fn sdk_inner_archive_requires_safe_files_and_matching_checksums() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-inner-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join("alkane-sdk-am335x-bb.tar.gz");
let sdk = format!("{}\n", "a".repeat(40));
let os = format!("{}\n", "b".repeat(40));
let artifact = b"image".as_slice();
let files = [
("SDK-REVISION", sdk.as_bytes()),
("OS-REVISION", os.as_bytes()),
("image.bin", artifact),
];
let checksums = files
.iter()
.map(|(name, data)| format!("{:x} ./{name}\n", Sha256::digest(data)))
.collect::<String>();
let mut members = files.to_vec();
members.push(("SHA256SUMS", checksums.as_bytes()));
let good = board_archive(&members);
let record = ArtifactRecord {
sha256: format!("{:x}", Sha256::digest(&good)),
size_bytes: good.len() as u64,
path: PathBuf::from("alkane-sdk-am335x-bb.tar.gz"),
family: "am335x-bb".to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
std::fs::write(&archive, &good).unwrap();
let mut verified = verify_file(&archive, &record).unwrap();
let info = inspect_sdk_release_archive(&mut verified).unwrap();
assert_eq!(info.board, "am335x-bb");
assert_eq!(info.sdk_revision, "a".repeat(40));
assert_eq!(info.os_revision, "b".repeat(40));
assert_eq!(info.artifact_count, 1);
members[2] = ("image.bin", b"other");
let changed = board_archive(&members);
std::fs::write(&archive, &changed).unwrap();
let mut changed_record = record.clone();
changed_record.sha256 = format!("{:x}", Sha256::digest(&changed));
changed_record.size_bytes = changed.len() as u64;
let mut verified = verify_file(&archive, &changed_record).unwrap();
assert!(matches!(
inspect_sdk_release_archive(&mut verified),
Err(VerifyError::ReleaseContents)
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_dir(directory).unwrap();
}
#[test]
#[ignore = "microbenchmark"]
fn bench_verify_artifact() {
-1
View File
@@ -7,4 +7,3 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
alkane-access = { path = "../alkane-access" }
+3 -59
View File
@@ -1,46 +1,14 @@
// SPDX-License-Identifier: MIT
//! Headless entry point for read-only artifact verification.
use alkane_access::{parse_build_marker, verify_build_marker, Probe, SshTarget};
use alkane_artifacts::{
inspect_sdk_release_archive, seed_manifest, verify_file, verify_sdk_release_archive,
};
use std::io;
use std::net::IpAddr;
use alkane_artifacts::{seed_manifest, verify_file};
use std::path::Path;
fn run() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
match args.get(1).map(String::as_str) {
Some("verify-artifact") if args.len() == 4 => verify_artifact(&args),
Some("verify-sdk-release") if args.len() == 4 => verify_sdk_release(&args),
Some("verify-running-build") if args.len() == 8 => verify_running_build(&args),
_ => Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>\n alkane-cli verify-sdk-release <SHA256SUMS> <archive>\n alkane-cli verify-running-build <ip> <user> <known-hosts> <board> <sdk-sha> <os-sha>".into()),
if args.len() != 4 || args[1] != "verify-artifact" {
return Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>".into());
}
}
fn verify_sdk_release(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let mut verified = verify_sdk_release_archive(Path::new(&args[2]), Path::new(&args[3]))?;
if verified.record().family == "qemu-zynq-research" {
println!(
"verified checksum for SDK research archive {}; no board revision metadata is present",
verified.record().path.display()
);
return Ok(());
}
let info = inspect_sdk_release_archive(&mut verified)?;
println!(
"verified SDK release archive {} board={} sdk={} os={} artifacts={}",
verified.record().path.display(),
info.board,
info.sdk_revision,
info.os_revision,
info.artifact_count
);
Ok(())
}
fn verify_artifact(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let record = seed_manifest()?
.into_iter()
.find(|item| item.path == Path::new(&args[2]))
@@ -55,30 +23,6 @@ fn verify_artifact(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_running_build(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let address: IpAddr = args[2].parse()?;
let expected_text = format!(
"board={}\nsdk_revision={}\nos_revision={}\n",
args[5], args[6], args[7]
);
let expected = parse_build_marker(expected_text.as_bytes())
.map_err(|error| io::Error::other(format!("invalid expected build: {error:?}")))?;
let target = SshTarget::new(address, 22, &args[3], Path::new(&args[4]))
.map_err(|error| io::Error::other(format!("SSH target: {error:?}")))?;
let raw = target
.probe(Probe::AlkaneBuildMarker)
.map_err(|error| io::Error::other(format!("running build read: {error:?}")))?;
let observed = parse_build_marker(&raw)
.map_err(|error| io::Error::other(format!("running build marker: {error:?}")))?;
verify_build_marker(&observed, &expected)
.map_err(|error| io::Error::other(format!("build comparison: {error:?}")))?;
println!(
"verified running build {} {} {}",
observed.board, observed.sdk_revision, observed.os_revision
);
Ok(())
}
fn main() {
if let Err(error) = run() {
eprintln!("artifact verification failed: {error}");
-1
View File
@@ -9,4 +9,3 @@ alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
sha2.workspace = true
thiserror.workspace = true
tempfile = "3"
+7 -55
View File
@@ -4,7 +4,7 @@
use alkane_artifacts::VerifiedArtifact;
use sha2::{Digest, Sha256};
use std::io::{Read, Seek, SeekFrom, Write};
use std::io::{Read, Seek, SeekFrom};
use thiserror::Error;
pub struct PartitionSpec {
@@ -90,34 +90,6 @@ fn digest_bytes(hex: &str) -> Result<[u8; 32], FlashError> {
Ok(result)
}
fn stage_verified_artifact(
artifact: &mut VerifiedArtifact,
size: u64,
expected: [u8; 32],
) -> Result<std::fs::File, FlashError> {
let mut staged = tempfile::tempfile().map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
artifact
.reader()
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
let mut source = DigestReader {
inner: artifact.reader(),
remaining: size,
digest: Sha256::new(),
};
std::io::copy(&mut source, &mut staged).map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
if source.remaining != 0 || <[u8; 32]>::from(source.digest.finalize()) != expected {
return Err(FlashError::ArtifactChanged);
}
staged
.flush()
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
staged
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
Ok(staged)
}
struct DigestReader<'a> {
inner: &'a mut dyn Read,
remaining: u64,
@@ -173,10 +145,6 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
artifact
.revalidate()
.map_err(|_| FlashError::ArtifactChanged)?;
let expected = digest_bytes(&artifact.record().sha256)?;
// The source path may change while backup or transport I/O runs. Copy and
// verify it before any device write; the anonymous file is removed on drop.
let mut staged = stage_verified_artifact(artifact, size, expected)?;
let backup = writer
.backup(partition)
.map_err(|e| FlashError::Write(e.to_string()))?;
@@ -186,8 +154,13 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
{
return Err(FlashError::BackupIncomplete);
}
let expected = digest_bytes(&artifact.record().sha256)?;
artifact
.reader()
.seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
let mut stream = DigestReader {
inner: &mut staged,
inner: artifact.reader(),
remaining: size,
digest: Sha256::new(),
};
@@ -230,7 +203,6 @@ mod tests {
max_read: Option<u64>,
writes: usize,
contents: Vec<u8>,
mutate_source_on_write: Option<PathBuf>,
}
impl Writer for MockWriter {
@@ -259,9 +231,6 @@ mod tests {
_: u64,
) -> Result<(), Self::Error> {
self.writes += 1;
if let Some(path) = &self.mutate_source_on_write {
std::fs::write(path, b"PK\x03\x04changed").map_err(|_| "mutation failed")?;
}
if let Some(limit) = self.max_read {
image
.take(limit)
@@ -316,7 +285,6 @@ mod tests {
max_read: None,
writes: 0,
contents: Vec::new(),
mutate_source_on_write: None,
}
}
@@ -427,20 +395,4 @@ mod tests {
assert_eq!(writer.writes, 1);
std::fs::remove_file(path).unwrap();
}
#[test]
fn writes_verified_snapshot_when_source_changes_during_transport() {
let (path, mut image) = artifact("mutated-during-write");
let mut writer = writer();
writer.mutate_source_on_write = Some(path.clone());
let mut readback = MockReadback {
channel: "serial",
digest: digest_bytes(SHA).unwrap(),
};
let receipt = write_verified(&partition(), &mut image, &mut writer, &mut readback).unwrap();
assert_eq!(receipt.image_sha256, digest_bytes(SHA).unwrap());
assert_eq!(writer.contents, IMAGE);
assert_eq!(std::fs::read(&path).unwrap(), b"PK\x03\x04changed");
std::fs::remove_file(path).unwrap();
}
}
-32
View File
@@ -2604,38 +2604,6 @@ mod tests {
assert!(per.as_millis() < 100, "cell rendering regressed: {per:?}");
}
/// Microbenchmark: component health scores and operator-facing diagnostics
/// recomputed when scan results refresh the table.
#[test]
#[ignore]
fn bench_health_diagnostics() {
use std::hint::black_box;
use std::time::Instant;
let rows = bench_fleet();
let iters = 1000u32;
let start = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
for row in &rows {
for facet in [
HealthFacet::Overall,
HealthFacet::Power,
HealthFacet::Fans,
HealthFacet::Boards,
] {
sink += black_box(row.health_score(facet)) as usize;
}
sink += row.health_summary().len();
sink += row.health_tooltips(4, 3).iter().map(String::len).sum::<usize>();
}
}
black_box(sink);
let per = start.elapsed() / iters;
println!("bench_health_diagnostics: {} rows = {:?}/refresh", rows.len(), per);
assert!(per.as_millis() < 20, "health diagnostics regressed: {per:?}/refresh");
}
#[test]
fn selection_survives_upsert() {
let mut rows = bench_fleet();
+1 -34
View File
@@ -58,11 +58,7 @@ pub fn firmware_family(raw: &str) -> (String, Option<String>) {
// Vendor prefixes asic-rs prepends on stock-firmware family strings, matched
// case-insensitively.
for vendor in ["AntMiner", "WhatsMiner"] {
if trimmed.len() > vendor.len()
&& trimmed
.get(..vendor.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(vendor))
{
if trimmed.len() > vendor.len() && trimmed[..vendor.len()].eq_ignore_ascii_case(vendor) {
let rest = trimmed[vendor.len()..].trim();
if !rest.is_empty() {
return (rest.to_string(), Some(vendor.to_string()));
@@ -481,35 +477,6 @@ mod tests {
assert_eq!(firmware_family("Braiins"), ("Braiins".to_string(), None));
// A bare vendor word with nothing after it is left as-is (not emptied).
assert_eq!(firmware_family("AntMiner"), ("AntMiner".to_string(), None));
// Firmware strings arrive from the network and may contain UTF-8 at
// the byte position used to check a vendor prefix.
let non_ascii = "AntMine\u{e9} Stock";
assert_eq!(firmware_family(non_ascii), (non_ascii.to_string(), None));
}
#[test]
#[ignore = "microbenchmark"]
fn bench_naming_transforms() {
let cases = [
("Antminer", "S19jPro", "AntMiner Stock", "Xilinx"),
("Antminer", "S21Pro", "VNish", "CVITek"),
("Whatsminer", "M30SPlusVE40", "WhatsMiner Stock", "H616"),
("Whatsminer", "M50SPlusPlusVK30", "Braiins", "H6"),
];
let iterations = 20_000;
let started = std::time::Instant::now();
for index in 0..iterations {
let (make, model, firmware, board) = cases[index % cases.len()];
let clean = clean_model(make, model);
std::hint::black_box(firmware_family(firmware));
std::hint::black_box(control_board_code(make, board, &clean));
std::hint::black_box(chip_type_for_model(make, model));
std::hint::black_box(clean);
}
let elapsed = started.elapsed();
let per = elapsed / iterations as u32;
println!("bench_naming_transforms: {per:?}/record");
assert!(elapsed < std::time::Duration::from_millis(500));
}
#[test]
+6 -6
View File
@@ -1,10 +1,10 @@
# Primary view
# UI Spec — primary view
Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
## Header
## Header (above the table)
- **KPI block, top left: 6 KPIs:**
- **KPI block, top left — 6 KPIs:**
1. Total miners
2. Hashing
3. Slow
@@ -31,7 +31,7 @@ Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
4. Cooling (fan)
5. Firmware
6. Pool worker account name
7. Remaining statistics in registry order.
7. …then the remaining statistics in registry order.
## Data sources
@@ -45,10 +45,10 @@ Source: operator description, 2026-09-15. Status: ACCEPTED (v1 scope).
ships with the board registry; missing band = excluded from Slow, counted
in Hashing).
## Implementation
## Implementation notes
- wxWidgets: the view is a `wxDataViewListCtrl`/`wxDataViewCtrl` (virtual
list for thousands of rows without materializing cells), checkbox column +
list — thousands of rows without materializing cells), checkbox column +
IP column fixed via attribute/serializer, drag reorder via `wxReorderable`
column events, sort via column header click events mapped to the model.
- Filter panel: per-column distinct-value checklist with text search,
+1 -1
View File
@@ -1,4 +1,4 @@
# ADR 0001: Recipe engine
# ADR 0001: Recipes as data, interpreted by one engine
Status: ACCEPTED
Date: 2026-09-14
+29 -15
View File
@@ -1,27 +1,41 @@
# ADR 0002: GUI bindings
# ADR 0002: GUI bindings — wxWidgets shell in C++ + Rust core, spike to revisit
Status: RESOLVED 2026-09-15 - the operator chose Option B (pure Rust via
wx-rs) with vendoring (ADR-0003). wx-rs 0.2.0 was extended via the patch
queue: Linux/GTK3 wx-config build path plus the widget bridge (panel,
sizers, static text, button, text ctrl, checkbox, checklistbox, dialog,
data view list ctrl, timer). The app ships this way; no C++ shell.
Date: 2026-09-14
Resolved: 2026-09-15
## Context
The toolkit needs a native wxWidgets GUI. At the time of evaluation,
`wxRust` 0.0.1-alpha had seen no maintenance since 2022, and `wx-rs`
0.2.0 lacked widgets needed for the Toolkit.
The toolkit must present a native cross-platform GUI (wxWidgets chosen).
Rust bindings to wxWidgets checked on crates.io 2026-09-14:
- `wxRust` 0.0.1-alpha — unmaintained since 2022.
- `wx-rs` 0.2.0 (2023, self-contained) — ~6k downloads, no 1.0.
Betting the GUI on alpha bindings risks weeks of binding-gap debugging
(paste-heavy widgets, worker threads + event loops, GTK/WinCocoa quirks).
## Decision
The operator chose a Rust GUI through a vendored, patched `wx-rs` 0.2.0.
The patch queue adds the Linux/GTK3 build path and bindings for panels,
sizers, controls, dialogs, data views, timers, and event dispatch. The
application uses this bridge; it has no separate C++ shell.
Default: **thin C++17 wxWidgets shell (`gui/`) + Rust core exposed over a
small stable C ABI** (cdylib from `alkane-core`, header generated with
cbindgen). The shell holds frames, lists, the install wizard, and event
glue only — no business logic, no safety logic. All invariants, engines,
and tests live in Rust where they are testable headlessly.
The original proposal was a small C++17 wxWidgets shell calling a Rust
core through a C ABI. The `wx-rs` spike met the GUI need, so that proposal
was not adopted.
Gate: M0 runs a time-boxed `wx-rs` spike (window + list/tree + wizard flow
+ worker-thread progress + cancel on Linux and Windows). If the spike is
solid, flip to pure Rust; either way the decision is recorded before M3.
## Consequences
- Keep business logic and safety checks in testable Rust code.
- Carry wx-rs changes as numbered patches under `thirdparty/wx-rs/patches`.
- Recheck the bridge on Linux, Windows, and macOS packaging changes.
- The repo builds two things: a Rust workspace and a small C++ app linked
against the core cdylib. CMake in `gui/`.
- Core API surface stays small and event-oriented (discover, identify,
plan, execute, cancel, progress events, log tail) — good FFI hygiene and
a natural match for the CLI too (D4).
- If wx-rs wins the spike, the C ABI is kept as an integration boundary for
scripted/HIL use anyway.
+2 -2
View File
@@ -1,4 +1,4 @@
# ADR 0003: Vendoring
# ADR 0003: Vendoring policy — pristine upstream archives + patch queue
Status: ACCEPTED
Date: 2026-09-15
@@ -42,7 +42,7 @@ thirdparty/
Rules:
1. Never edit a vendored pristine tree in place. Every local change is a
1. Never edit a vendored pristine tree in place — every local change is a
patch in `patches/`, applied by the build in numeric order. This makes
an upstream update: replace pristine archive, `git apply` surviving
patches, rebase the rest.
+17 -27
View File
@@ -8,13 +8,13 @@
#
# Usage: scripts/ui-screenshot.sh [out.png] [--live] [binary]
set -u
REPO=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}"
export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}"
OUT="${1:-alkane-toolkit.png}"
LIVE=0; BIN=""
[ "$#" -eq 0 ] || shift
shift 2>/dev/null || true
for a in "$@"; do
case "$a" in
--live) LIVE=1 ;;
@@ -32,31 +32,17 @@ if [ -z "$BIN" ]; then
fi
[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; }
DISPLAY_FILE=$(mktemp)
XPID=""; APID=""; WARM=""
cleanup() {
[ -z "$APID" ] || kill "$APID" 2>/dev/null || true
[ -z "$WARM" ] || kill "$WARM" 2>/dev/null || true
[ -z "$XPID" ] || kill "$XPID" 2>/dev/null || true
rm -f "$DISPLAY_FILE"
}
trap cleanup EXIT
Xvfb -displayfd 3 -screen 0 1280x850x24 -nolisten tcp 3>"$DISPLAY_FILE" >/dev/null 2>&1 &
DISP=":98"
FAKE_ENV="ALKANE_FAKE_SCAN=1"
[ "$LIVE" = "1" ] && FAKE_ENV=""
Xvfb "$DISP" -screen 0 1280x850x24 -nolisten tcp >/dev/null 2>&1 &
XPID=$!
for _ in {1..30}; do
[ -s "$DISPLAY_FILE" ] && break
kill -0 "$XPID" 2>/dev/null || { echo "Xvfb exited before startup" >&2; exit 3; }
sleep 0.1
done
[ -s "$DISPLAY_FILE" ] || { echo "Xvfb did not start" >&2; exit 3; }
DISP=":$(cat "$DISPLAY_FILE")"
sleep 1.2
# warm the font/GTK caches so the first window map is not stalled
DISPLAY="$DISP" xclock >/dev/null 2>&1 & WARM=$!; sleep 1.2; kill "$WARM" 2>/dev/null
if [ "$LIVE" = "1" ]; then
DISPLAY="$DISP" GDK_BACKEND=x11 "$BIN" >/dev/null 2>&1 &
else
DISPLAY="$DISP" GDK_BACKEND=x11 ALKANE_FAKE_SCAN=1 "$BIN" >/dev/null 2>&1 &
fi
# shellcheck disable=SC2086
DISPLAY="$DISP" GDK_BACKEND=x11 $FAKE_ENV "$BIN" >/dev/null 2>&1 &
APID=$!
WID=""; t=0
while [ "$t" -lt 25 ]; do
@@ -66,6 +52,10 @@ while [ "$t" -lt 25 ]; do
[ -n "$line" ] && { WID=$(echo "$line" | awk '{print $1}'); break; }
done
sleep 2 # let it paint and drain a scan tick
[ -n "$WID" ] || { echo "no app window mapped" >&2; exit 1; }
DISPLAY="$DISP" import -window "$WID" "$OUT" || exit 1
echo "wrote $OUT (window $WID, ${t}s)"
if [ -n "$WID" ]; then
DISPLAY="$DISP" import -window "$WID" "$OUT" && echo "wrote $OUT (window $WID, ${t}s)"
else
DISPLAY="$DISP" import -window root "$OUT"; echo "no app window; captured root -> $OUT" >&2
fi
kill "$APID" 2>/dev/null
kill "$XPID" 2>/dev/null