Compare commits

..
Author SHA1 Message Date
noahandClaude Opus 4.8 d574118314 fix(gui): offer alkane install for the stock A113D (AML C76) board
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 30m58s
verify / verify-windows (pull_request) Successful in 19m55s
The right-click "Install alkane OS..." item never appeared for a stock
Amlogic A113D (Antminer BHB42XXX). board_family(), which gates the menu
via install_supported(), recognized only the Xilinx/Zynq S17 control
board, so it returned None for the A113D and the menu offered nothing.

Two things combined to hide it, both visible in a live scan of the bench
board at 10.255.1.18:

    brand=Unknown  model="Unknown: ANTMINER BHB42XXX"  board=AML (C76)

asic-rs has no make for the BHB42XXX, so the brand is "Unknown" and
board_family() bailed at the `!brand.contains("antminer")` guard before
any board-code check; and there was no AML -> a113d mapping anyway. Yet
SUPPORTED_BOARDS, the from-stock install engine (stock::install_from_stock
dispatches a113d -> aml_ubi) and the CLI's SUPPORTED list all already
support a113d -- only this detection gate was stale.

Map the "AML (C76)" control board (the a113d identity; board_labels
already maps a113d -> ("AML","C76")) directly to "a113d", ahead of the
brand guard, since this board legitimately reports no brand. The "AML"
code is only ever derived for an Amlogic Antminer control board, so it is
specific on its own. CBE (140mm S19k/S21-class) is deliberately not
mapped.

Verified against the bench A113D: live scan now reports install=true, and
a headless stock->alkane->stock cycle through the GUI operation layer
(ALKANE_BENCH_SEQUENCE) on the released v0.1.0-a113d-bench1 image passes
(install -> dropbear_2026.93 -> flag-restore -> dropbear_2018.76).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 09:33:52 -06:00
noah 0873d2c79d Merge pull request 'a113d: headless-GUI bench driver + A113D GUI install/restore (full cycle passes on hardware)' (#53) from feat/a113d-headless-bench into main
build-test-release / windows (push) Successful in 19m20s
build-test-release / release (push) Successful in 34m7s
2026-11-16 22:50:51 -07:00
noahandClaude Opus 4.8 12a11edfd7 style: rustfmt the A113D GUI install + headless bench driver
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 13m48s
verify / verify-windows (pull_request) Successful in 10m44s
cargo fmt -p alkane-gui; no logic change. This branch's CI never ran before
(its verify was skipped), so the formatting was never enforced.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 22:46:43 -06:00
noahandClaude Opus 4.8 71ab5a957c fix(gui): bench driver uses the alkane root credential for the restore leg
The flag-restore reaches the running alkane board over SSH as root, which is a
different credential from the stock login used for install. Alkane bench images
bake root/alkane; pass that (overridable via ALKANE_ROOT_PASSWORD) to the
restore, and keep the saved board SSH credential for the install. The previous
single-credential handoff sent the stock login to the alkane root restore and
hit "Permission denied".

Hardware note (2026-11-16): the PHY-fixed afw installs and comes up REACHABLE on
alkane (both the image PHY fix and the driver's MAC rediscovery proven); the
in-band flag-restore still needs the alkane DTB to expose the `misc` MTD (it
currently exposes only nvdata), tracked separately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 22:42:05 -06:00
noahandClaude Opus 4.8 f6c740bc24 fix(gui): headless bench driver re-finds the board by MAC across reboots
The A113D can take a different DHCP lease (or lose its v4 lease) across the
install/restore reboots, so assuming the board keeps its initial IP broke the
verify/restore steps. Resolve the board's MAC up front (on stock) and, after
each reboot, re-locate it in the neighbour table (sweeping the /24 when it is
not cached) so verify and the flag-restore target the board's CURRENT address.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 22:42:05 -06:00
noahandClaude Opus 4.8 968173095e feat(gui): A113D install support + flag-restore + headless bench driver
- stock_ops: add "a113d" to SUPPORTED_BOARDS so the GUI offers A113D install
  (it was zynq-7010 only); add start_restore_flag() - the A113D restore is the
  in-band ALAN flag flip (install overwrites no stock partition), which the GUI
  lacked a clean path for (start_restore needs a firmware file, which the A113D
  ignores).
- bench_sequence (new) + main.rs ALKANE_BENCH_SEQUENCE: a headless driver that
  drives the real GUI operation layer (start_install(AfwSource::Local) -> verify
  -> start_restore_flag) through the A113D network-only install<->restore cycle,
  no wx window. Classifies stock vs alkane by SSH dropbear version / HTTP.

Hardware status (bench A113D, 2026-11-16): the install leg is PROVEN on real
hardware via the GUI operation layer. The verify/restore legs are NOT yet
validated end-to-end because the 0.1.0 a113d alkane image does not fully boot on
the bench board (kernel+eth up, no DHCP/SSH) - an alkane-os image bringup issue,
tracked separately. Known limitation: the driver assumes the board keeps its IP
across reboots; it should re-discover the board (A113D can change/lose its lease
under alkane). Not released pending a working image + the discovery fix.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 22:42:05 -06:00
noah 63c603d919 Merge pull request #52: readable network-only stock<->alkane install/restore for a113d (and zynq)
build-test-release / windows (push) Successful in 9m46s
build-test-release / release (push) Successful in 21m55s
2026-11-16 21:40:11 -07:00
noahandClaude Opus 4.8 fdb9bedb03 fix(flash): compile the zynq_nand temp-file writer on non-unix targets
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 10m9s
verify / verify-windows (pull_request) Successful in 11m31s
The Windows-target clippy gate (verify-windows) failed: zynq_nand's
write_private was #[cfg(unix)] only, but TempFile::with calls it
unconditionally, so on x86_64-pc-windows-gnu it was E0425 (not found), and the
module-top `use std::io::Write as _` / `use std::path::Path` then read as
unused. aml_ubi already handles this with a #[cfg(not(unix))] std::fs::write
fallback; mirror that here, and move the Write import into the unix branch that
uses it (as aml_ubi does) so neither import is unused on Windows.

Verified: native clippy -D warnings clean, and the CI Windows command
`cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets
--target x86_64-pc-windows-gnu -- -D warnings` now passes (exit 0).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 22:09:04 -06:00
noahandClaude Opus 4.8 4be4750aae test(report-relay): seed the label cache instead of a live in-test fetch
verify / verify-windows (pull_request) Failing after 5m42s
verify / verify (pull_request) Successful in 10m8s
source / check (pull_request) Skipped
v5/v6 still failed in CI on the labels assertion. Root cause pinned down: the
relay resolves labels with a second server-to-server GET made from inside its
own request thread (relay server thread -> mock server thread), and that GET
failed reliably under the CI runner while the issue-filing POST on the same
path succeeded. Gitea.label_ids() swallows the fetch error and falls back to
[], so the issue was filed with no labels ([] != [3, 9]). Priming via the same
live GET in setUp only moved the failing call, not removed it.

Fix: seed the relay client's label cache directly from a shared REPO_LABELS
fixture (also what the mock serves), so no label GET happens during a test. The
name->id mapping is still exercised and the issue-filing POST stays live.
Verified 20/20 locally.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 21:40:17 -06:00
noahandClaude Opus 4.8 165b11bda3 test(report-relay): prime the label cache so the asserted path never refetches
verify / verify (pull_request) Failing after 9m27s
verify / verify-windows (pull_request) Skipped
source / check (pull_request) Skipped
The first relay test was flaky in CI (labels [] != [3,9]). Root cause:
Gitea.label_ids() fetches lazily on the first report and silently falls back
to [] on any fetch error; under CI load that first live fetch -- happening
inside the asserted POST -- intermittently raced the mock server thread and
dropped the labels. The earlier readiness probe only proved reachability at
setUp, not during the POST.

Fix: fetch labels once in setUp, while the mock is known-reachable, with a
bounded retry. label_ids caches for 10 minutes, so every request handler now
resolves labels from cache and the live fetch is off the asserted path.
Verified 25/25 clean and 12/12 under 2x CPU oversubscription.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 21:19:46 -06:00
noahandClaude Opus 4.8 e83bb8d2f1 test(report-relay): wait for the mock Gitea to serve before probing
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 9m29s
verify / verify-windows (pull_request) Skipped
The report-relay test's mock server binds in __init__ but runs
serve_forever on a daemon thread. Under CI load that thread can be
starved past the relay's HTTP timeout, so the first test's label fetch
returns [] and test_files_an_issue_with_title_body_and_labels fails
(labels [] != [3,9]). It passes locally and only the first test flaked,
which is the classic server-thread startup race.

Add a readiness probe in FakeGitea.__init__: poll the labels endpoint
until the serve_forever thread actually answers (5s budget) before the
test issues any relay request. Deterministic now (5/5 local runs green);
no production relay change. This surfaced only because #52's verify is
the first time this gate ran on the alkane-ci pool.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 17:59:14 -06:00
noahandClaude Opus 4.8 c0a647237a fix(clippy): satisfy -D warnings on the a113d flash engine
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 9m21s
verify / verify-windows (pull_request) Skipped
#52's verify never ran before (offline runner), so clippy -D warnings was
never enforced. Fix the Claude-domain lints:
  - aml_ubi.rs: use u64::div_ceil for the base64 length
  - zynq_nand.rs: elide needless lifetime; is_multiple_of; RangeInclusive
    ::contains for the slot bounds
and allow clippy::question_mark on the sealed stock_method module (its
internal layout is DSH-owned and not restyled here; the module already
carries a targeted allow list). No behavioural change.

Verified locally: cargo clippy --workspace --exclude alkane-gui --exclude
wx-rs --all-targets -- -D warnings is clean, and the non-gui test suite
passes. stock_method.rs is byte-for-byte unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 17:33:23 -06:00
noahandClaude Opus 4.8 9c49fa91af style: rustfmt the a113d flash engine + CLI (cargo fmt)
verify / verify (pull_request) Canceled after 0s
verify / verify-windows (pull_request) Canceled after 0s
source / check (pull_request) Skipped
#52's verify never actually ran before (the alkane-verify runner was
offline), so cargo fmt --check was never enforced on this branch. Apply
rustfmt to the three flagged files (alkane-cli main.rs, alkane-flash
aml_ubi.rs and zynq_nand.rs) to match the toolkit's CI fmt gate. No
behavioural change; vendored thirdparty/ is untouched (CI only formats
the named crates).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 17:28:37 -06:00
noahandClaude Opus 4.8 fbeb6dc328 ci(merge): keep verify-windows on the PR gate (alkane-ci) per the workflow contract
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 3m23s
verify / verify-windows (pull_request) Skipped
The merge resolution initially took #52's verify.yml, which drops the
verify-windows job; but ci/test-pr-surface.py enforces that verify.yml
carries verify-windows, and #52 never updated that contract, so the
verify gate failed with KeyError: 'verify-windows'. Take main's verify.yml
instead: both verify and verify-windows run on alkane-ci, matching the
contract. #52's flash-engine changes are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 16:15:53 -06:00
noah 8180f4ff80 Merge remote-tracking branch 'origin/main' into feat/readable-stock-install-a113d-rebase
verify / verify (pull_request) Failing after 3m19s
source / check (pull_request) Skipped
# Conflicts:
#	.gitea/workflows/verify.yml
2026-11-16 16:08:35 -06:00
noah 9155c55d4c ci: repoint toolkit verify/source/badge to alkane-ci; keep Pages on the trusted verifier (#54)
build-test-release / release (push) Skipped
build-test-release / windows (push) Failing after 35m1s
2026-11-16 15:07:14 -07:00
13 changed files with 320 additions and 87 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
publish:
runs-on: alkane-verify
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -7,7 +7,7 @@ on:
jobs:
publish:
runs-on: alkane-verify
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
check:
runs-on: alkane-fast
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
+71 -6
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
verify:
runs-on: alkane-verify
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
outputs:
@@ -195,8 +195,73 @@ jobs:
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of each change is validated on the main release run
# (build-test-release / windows-native), not on the PR gate: it is a full
# mingw + Wine cross-build that roughly doubled PR wall-clock. PRs verify Linux
# (clippy, build, tests, self-test) fast; Windows is still built and shipped at
# release, so a Windows-only break surfaces on the merge to main.
# The Windows build of the same change (main's release gate, run on the PR):
# clippy for the Windows target, the release .exe, every unit test under
# Wine, and the headless UI self-test under Wine. Only for changes that can
# affect the binary (the "full" surface).
verify-windows:
needs: verify
if: needs.verify.outputs.surface == 'full'
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Build (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+58 -18
View File
@@ -22,8 +22,8 @@ use alkane_flash::preflight::{preflight, PreflightOptions};
use alkane_flash::stock;
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
use alkane_flash::stock_firmware;
use alkane_flash::zynq_nand;
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use alkane_flash::zynq_nand;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -1042,7 +1042,10 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
/// of these; `compat` lists them so an operator knows what is supported.
const SUPPORTED: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"),
(
"a113d",
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
),
];
fn is_supported(board: &str) -> bool {
@@ -1128,7 +1131,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
None => {
if opts.flag("dry-run") {
println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag");
println!("(no stock firmware needed; the untouched stock boot partition is booted).");
println!(
"(no stock firmware needed; the untouched stock boot partition is booted)."
);
println!("Re-run with --confirm FLASH.");
return Ok(());
}
@@ -1138,7 +1143,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
println!("restoring {host} to genuine stock (A113D flag flip, network-only)...");
match stock::restore_aml_flag(&host, password.as_deref()) {
Ok(()) => {
println!("restore reported success (boot flag cleared; stock boots via storeboot).");
println!(
"restore reported success (boot flag cleared; stock boots via storeboot)."
);
println!("verify independently: the board should present genuine stock");
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
return Ok(());
@@ -1186,9 +1193,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, ssh_values(), &[])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let cmd = opts
.positionals
.join(" ");
let cmd = opts.positionals.join(" ");
if cmd.trim().is_empty() {
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
}
@@ -1203,7 +1208,11 @@ fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// backup, write the boot slots and reboot. Drives the DSH root-on-stock
/// primitive; board must be on stock (credential root/root).
fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["allow-unsigned"])?;
let opts = parse_args(
args,
&[ssh_values(), &["confirm"]].concat(),
&["allow-unsigned"],
)?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let afw_path = opts
.positionals
@@ -1211,18 +1220,33 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.ok_or("usage: alkane-cli afw nand-install <afw> --host <ip> --confirm FLASH")?;
let verified = load_afw(afw_path, &opts)?;
if !zynq::owns_board(&verified.manifest.board) {
return Err(format!("nand-install is zynq-7010 only, not {}", verified.manifest.board).into());
return Err(format!(
"nand-install is zynq-7010 only, not {}",
verified.manifest.board
)
.into());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to install without --confirm FLASH".into());
}
let kernel = verified.image("kernel").ok_or("afw missing kernel image")?.1;
let kernel = verified
.image("kernel")
.ok_or("afw missing kernel image")?
.1;
let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1;
let rootfs = verified.image("rootfs").ok_or("afw missing rootfs image")?.1;
let rootfs = verified
.image("rootfs")
.ok_or("afw missing rootfs image")?
.1;
let password = read_board_password(&opts)?;
println!("installing {} onto stock board {host} (readable NAND path)...", verified.manifest.board);
println!(
"installing {} onto stock board {host} (readable NAND path)...",
verified.manifest.board
);
zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?;
println!("install reported success (on-board stock backup carved; boot slots written; rebooting).");
println!(
"install reported success (on-board stock backup carved; boot slots written; rebooting)."
);
print!("{}", zynq_verify_hint(&host));
Ok(())
}
@@ -1231,9 +1255,15 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// back to the boot slots over SSH (board on alkane). Needs the alkane image
/// that exposes the boot partitions.
fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &[ssh_values(), &["confirm", "stock-firmware"]].concat(), &["dry-run"])?;
let opts = parse_args(
args,
&[ssh_values(), &["confirm", "stock-firmware"]].concat(),
&["dry-run"],
)?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let firmware = opts.value("stock-firmware").ok_or("--stock-firmware <file> is required")?;
let firmware = opts
.value("stock-firmware")
.ok_or("--stock-firmware <file> is required")?;
let fw = stock_firmware::parse(Path::new(firmware))?;
println!("stock firmware: {}", fw.summary());
if opts.value("confirm") != Some("FLASH") {
@@ -1241,8 +1271,16 @@ fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Err
}
let password = read_board_password(&opts)?;
println!("restoring {host} to genuine stock (readable NAND path)...");
zynq_nand::restore_to_stock(&host, &fw.kernel, &fw.rootfs, fw.dtb.as_deref(), password.as_deref())?;
println!("restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved).");
zynq_nand::restore_to_stock(
&host,
&fw.kernel,
&fw.rootfs,
fw.dtb.as_deref(),
password.as_deref(),
)?;
println!(
"restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."
);
Ok(())
}
@@ -1344,7 +1382,9 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>
password.as_deref(),
std::time::Duration::from_secs(300),
)?;
println!("restore-from-onboard reported success. Verify independently the board answers as stock.");
println!(
"restore-from-onboard reported success. Verify independently the board answers as stock."
);
Ok(())
}
+12 -8
View File
@@ -53,8 +53,7 @@ const FLAG_MAGIC: [u8; 4] = *b"ALAN";
const KRNADDR: &str = "0x1200000";
const FDTADDR: &str = "0x8000000";
const RDADDR: &str = "0x8100000";
const ALK_BOOTARGS: &str =
"console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
const ALKANE_DIR: &str = "alkane";
@@ -110,8 +109,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -220,7 +219,7 @@ fn b64_decode(s: &str) -> Option<Vec<u8>> {
fn b64_encode(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
@@ -607,7 +606,10 @@ mod tests {
#[test]
fn env_roundtrips_with_crc() {
let vars = vec![
("bootcmd".to_owned(), "run checkalk; run storeboot".to_owned()),
(
"bootcmd".to_owned(),
"run checkalk; run storeboot".to_owned(),
),
("bootdelay".to_owned(), "1".to_owned()),
("checkalk".to_owned(), checkalk_value()),
];
@@ -616,8 +618,10 @@ mod tests {
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
assert_eq!(crc32(&blob[4..]), stored);
let parsed = parse_env(&blob);
assert_eq!(parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot");
assert_eq!(
parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot"
);
assert!(parsed.iter().any(|(k, _)| k == "checkalk"));
}
+2 -1
View File
@@ -30,7 +30,8 @@ pub mod zynq_nand;
clippy::too_many_arguments,
clippy::manual_repeat_n,
clippy::manual_is_multiple_of,
clippy::unnecessary_map_or
clippy::unnecessary_map_or,
clippy::question_mark
)]
mod stock_method;
pub mod transport;
+70 -30
View File
@@ -34,7 +34,6 @@ use crate::md5::md5_hex;
use crate::stock::StockError;
use crate::transport::{Remote, SshOptions, SshTransport};
use crate::uimage::{self, Kind};
use std::io::Write as _;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
@@ -131,6 +130,7 @@ impl Drop for TempFile {
#[cfg(unix)]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new()
.create(true)
@@ -142,6 +142,11 @@ fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
f.flush()
}
#[cfg(not(unix))]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
std::fs::write(path, contents)
}
impl AlkaneShell {
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
@@ -157,8 +162,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -225,11 +230,7 @@ fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
.and_then(|h| u64::from_str_radix(h, 16).ok())
.ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?;
let _erase = it.next();
let name = line
.split('"')
.nth(1)
.unwrap_or("")
.to_owned();
let name = line.split('"').nth(1).unwrap_or("").to_owned();
let base = match sysfs_offset(sh, dev) {
Some(off) => off,
None => cursor,
@@ -257,11 +258,7 @@ fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
/// Find the partition that contains `abs` and holding at least `len` bytes from
/// there; return (device, relative offset).
fn locate<'a>(
table: &'a [Mtd],
abs: u64,
len: u64,
) -> Result<(&'a str, u64), StockError> {
fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> {
for m in table {
if abs >= m.base && abs < m.base + m.size {
let rel = abs - m.base;
@@ -308,7 +305,7 @@ fn write_abs(
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
)));
}
if abs % ERASE != 0 {
if !abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label} offset 0x{abs:x} is not erase-block aligned"
)));
@@ -335,7 +332,9 @@ fn write_abs(
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: erase/write failed: {o}")))
Err(StockError::Method(format!(
"{label}: erase/write failed: {o}"
)))
}
})?;
let readlen = round_up(data.len() as u64, PAGE);
@@ -488,7 +487,7 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
// Sanity: headers must look like a uImage/fdt, sizes within slots.
if kernel_len < 64 || kernel_len > SLOT_KERNEL || rootfs_len < 64 || rootfs_len > SLOT_ROOTFS {
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
return Err(StockError::Method(format!(
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
refusing to back up"
@@ -513,7 +512,13 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
rootfs_abs: r_dst,
rootfs_len,
};
write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?;
write_abs(
sh,
table,
BK_MANIFEST,
&manifest.encode(),
"stock-backup-manifest",
)?;
Ok(manifest)
}
@@ -569,11 +574,7 @@ struct BootImages {
rootfs_uimage: Vec<u8>,
}
fn write_boot_slots(
sh: &mut dyn Shell,
table: &[Mtd],
img: &BootImages,
) -> Result<(), StockError> {
fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> {
// rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs
// under an old kernel.
if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS {
@@ -623,7 +624,9 @@ pub fn install_from_stock(
password: password.map(str::to_owned),
};
if first_token(&sh.exec("id -u")?) != "0" {
return Err(StockError::Auth("did not obtain root on the stock board".into()));
return Err(StockError::Auth(
"did not obtain root on the stock board".into(),
));
}
let table = read_mtd_table(&mut sh)?;
// Carve the genuine-stock backup from the live stock NAND before any write.
@@ -674,7 +677,14 @@ pub fn restore_to_stock(
"no stock dtb supplied and no on-board backup to take one from".into(),
)
})?;
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
}
}
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
@@ -703,14 +713,34 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
let manifest = read_backup_manifest(&mut sh, &table)?
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
// Copy within NAND: backup region -> boot slots.
copy_abs(&mut sh, &table, manifest.rootfs_abs, OFF_ROOTFS, manifest.rootfs_len, "rootfs")?;
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
copy_abs(&mut sh, &table, manifest.kernel_abs, OFF_KERNEL, manifest.kernel_len, "kernel")?;
copy_abs(
&mut sh,
&table,
manifest.rootfs_abs,
OFF_ROOTFS,
manifest.rootfs_len,
"rootfs",
)?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
copy_abs(
&mut sh,
&table,
manifest.kernel_abs,
OFF_KERNEL,
manifest.kernel_len,
"kernel",
)?;
reboot(&mut sh);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -751,8 +781,18 @@ mod tests {
#[test]
fn locate_maps_absolute_to_partition() {
let table = vec![
Mtd { dev: "mtd0".into(), base: 0x0, size: 0x2800000, name: "x".into() },
Mtd { dev: "mtd1".into(), base: 0x2800000, size: 0x2000000, name: "y".into() },
Mtd {
dev: "mtd0".into(),
base: 0x0,
size: 0x2800000,
name: "x".into(),
},
Mtd {
dev: "mtd1".into(),
base: 0x2800000,
size: 0x2000000,
name: "y".into(),
},
];
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
+40 -5
View File
@@ -143,12 +143,23 @@ pub fn is_alkane(row: &MinerRow) -> bool {
}
/// The alkane-os board family the row's control board is, when it can be told:
/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17
/// era, "XIL (C49)") control board.
/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era,
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
/// board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
// A stock A113D (Amlogic AXG) control board -- the "a113d" install target
// (board_labels maps a113d -> "AML (C76)"). Decided on the control-board
// code, not the brand: asic-rs has no make for the Antminer BHB42XXX and
// reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so
// the generic brand guard below would otherwise reject it. The "AML" code is
// only ever derived for an Amlogic Antminer control board, so this is
// specific on its own.
if row.cpu == "AML" && row.board_code == "C76" {
return Some("a113d".to_string());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
@@ -243,7 +254,10 @@ mod tests {
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
assert!(!install_supported(&stock("AML", "C76")));
// The Amlogic A113D control board is the "a113d" install target.
assert!(install_supported(&stock("AML", "C76")));
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
@@ -274,7 +288,9 @@ mod tests {
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model.
// A reported control board overrides the model: an "S17" model on an
// Amlogic A113D control board resolves to a113d (the control board),
// not zynq (the model).
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
@@ -282,7 +298,26 @@ mod tests {
board_code: "C76".into(),
..Default::default()
};
assert!(!install_supported(&s17_on_aml));
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
}
#[test]
fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() {
// Exactly as the live scan reports the bench A113D at 10.255.1.18:
// asic-rs cannot pin a make, so brand is "Unknown" and the model is
// "Unknown: ANTMINER BHB42XXX", but the control board classifies as
// "AML (C76)". Install must still be offered.
let bhb = MinerRow {
brand: "Unknown".into(),
model: "Unknown: ANTMINER BHB42XXX".into(),
firmware: "Stock".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert_eq!(board_family(&bhb).as_deref(), Some("a113d"));
assert!(install_supported(&bhb));
assert!(!is_alkane(&bhb));
}
/// Live check against a real board:
+22 -9
View File
@@ -53,9 +53,7 @@ fn drive(label: &str, handle: StockHandle) -> bool {
fn ssh_banner(host: &str) -> Option<String> {
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?;
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.ok()?;
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
let mut buf = [0u8; 256];
let n = stream.read(&mut buf).ok()?;
if n == 0 {
@@ -129,7 +127,10 @@ fn mac_of(host: &str) -> Option<String> {
let _ = Command::new("ping")
.args(["-c", "1", "-W", "1", host])
.output();
let out = Command::new("ip").args(["neigh", "show", host]).output().ok()?;
let out = Command::new("ip")
.args(["neigh", "show", host])
.output()
.ok()?;
let s = String::from_utf8_lossy(&out.stdout);
let mut it = s.split_whitespace();
while let Some(t) = it.next() {
@@ -183,7 +184,12 @@ fn ip_for_mac(mac: &str) -> Option<String> {
/// Poll until the board (located by MAC, so a changed DHCP lease is followed)
/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's
/// current IP, a description, and whether the target state was reached.
fn wait_for(mac: Option<&str>, fallback: &str, want_stock: bool, timeout: Duration) -> (String, String, bool) {
fn wait_for(
mac: Option<&str>,
fallback: &str,
want_stock: bool,
timeout: Duration,
) -> (String, String, bool) {
let deadline = Instant::now() + timeout;
let mut ip = fallback.to_string();
let mut swept = Instant::now() - Duration::from_secs(60);
@@ -255,7 +261,8 @@ pub fn run(spec: &str) -> i32 {
let mac = mac_of(&host);
println!(
"board MAC: {}",
mac.as_deref().unwrap_or("unknown (will use the fixed host)")
mac.as_deref()
.unwrap_or("unknown (will use the fixed host)")
);
let boot_timeout = Duration::from_secs(300);
@@ -270,7 +277,7 @@ pub fn run(spec: &str) -> i32 {
vec![host.clone()],
board.clone(),
AfwSource::Local(afw.clone()),
true, // allow unsigned (bench image)
true, // allow unsigned (bench image)
stock_password.clone(),
false, // not an in-place update
);
@@ -286,7 +293,10 @@ pub fn run(spec: &str) -> i32 {
boot_timeout.as_secs()
);
let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
println!(" {desc} => {}", if ok { "ALKANE" } else { "NOT ALKANE (fail)" });
println!(
" {desc} => {}",
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
);
all_ok = all_ok && ok;
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
@@ -303,7 +313,10 @@ pub fn run(spec: &str) -> i32 {
boot_timeout.as_secs()
);
let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
println!(" {desc} => {}", if ok { "STOCK" } else { "NOT STOCK (fail)" });
println!(
" {desc} => {}",
if ok { "STOCK" } else { "NOT STOCK (fail)" }
);
all_ok = all_ok && ok;
}
+1 -1
View File
@@ -138,7 +138,7 @@ fn headless_mode() -> bool {
"ALKANE_BENCH_SEQUENCE",
]
.iter()
.any(|v| std::env::var_os(v).is_some())
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
+4 -1
View File
@@ -26,7 +26,10 @@ use crate::scan::fake_scan_enabled;
/// `SUPPORTED`). Only these are offered as install targets.
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
("a113d", "Antminer S19j Pro (Amlogic A113D/AXG control board)"),
(
"a113d",
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
),
];
/// The default install board when the user has not chosen another.
+37 -5
View File
@@ -7,6 +7,7 @@ import json
import pathlib
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
@@ -16,6 +17,12 @@ import relay # noqa: E402
TOKEN = "test-token-123"
# The repository's labels, as the real Gitea /labels endpoint would return them.
# The mock serves these, and setUp seeds the relay client's label cache from the
# same list so label resolution is deterministic (see RelayTests.setUp).
REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
{"name": "feature", "id": 3}, {"name": "from-app", "id": 9}]
class FakeGitea:
"""Records issue creations; serves the repository's labels."""
@@ -40,9 +47,7 @@ class FakeGitea:
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}])
return self._json(200, REPO_LABELS)
self._json(404, {})
def do_POST(self):
@@ -58,6 +63,23 @@ class FakeGitea:
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]}"
# Block until the serve_forever thread is actually handling requests, so
# the relay's first label fetch cannot race server startup. The socket
# listens from __init__, but under load the daemon thread can be starved
# past the relay's HTTP timeout, which silently drops labels to [] and
# made the first test flaky in CI.
probe = urllib.request.Request(
self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels",
headers={"Authorization": f"token {TOKEN}"})
deadline = time.monotonic() + 5
while True:
try:
urllib.request.urlopen(probe, timeout=1).read()
break
except Exception:
if time.monotonic() >= deadline:
raise
time.sleep(0.02)
def close(self):
self.server.shutdown()
@@ -70,8 +92,18 @@ class RelayTests(unittest.TestCase):
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)
client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN)
# Seed the relay client's label cache directly from REPO_LABELS instead
# of letting a request handler fetch it live. Gitea.label_ids() caches
# for 10 minutes and silently falls back to [] on any fetch error; in CI
# that first live GET -- a second server-to-server hop made from inside
# the relay's own request thread -- failed reliably and dropped the
# labels to [], while the issue-filing POST on the same path still
# worked. Seeding the cache keeps label resolution deterministic (the
# name->id mapping is still exercised) and leaves the issue POST live.
client.labels = {label["name"]: label["id"] for label in REPO_LABELS}
client.labels_at = time.monotonic()
r = relay.Relay(client, 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]}"