Compare commits

...
Author SHA1 Message Date
noahandClaude Opus 4.8 117e572407 zynq: fix the OOB read-backs (raw --noecc --oob); self-logging; HW-validated
verify / verify (pull_request) Failing after 9m0s
verify / verify-windows (pull_request) Skipped
source / check (pull_request) Skipped
The ECC-safe restore is now proven end-to-end on a bench S17: stock -> Alkane
0.1.3 (v2 OOB backup carved) -> network restore-from-onboard -> genuine stock
booted clean (lighttpd 401 "antMiner Configuration"), no ECC-unrecoverable
brick, no SD card.

Two fixes found on hardware:
- This mtd-utils `nanddump` defaults to --omitoob and to ECC-correcting. The
  restore read-backs (scratch self-check and per-slot verify) must read RAW,
  WITH OOB (`nanddump --noecc --oob`): the boot slots carry the foreign stock
  ECC, which the alkane soft-BCH engine would "correct" into garbage, and the
  default omit-oob made the read-back shorter than the written data+OOB. Proven
  on the board that `nandwrite --noecc --oob` + `nanddump --noecc --oob` round-
  trips the stock OOB byte-for-byte.
- carve `dump_with_oob` now passes --oob explicitly instead of relying on the
  nanddump default (version-robust OOB capture).

Also adds a method-free progress logger (`$ALKANE_OUTCOME_LOG`) so a sealed,
DSH-driven from-stock install can report its own steps (root/carve/write/verify)
without relying on the harness to summarise - the lines are written by this code
and never carry the stock-access method. 93 flash-crate tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-18 14:25:46 -06:00
noahandClaude Opus 4.8 036b44f6bb zynq: ECC-preserving (OOB) on-board restore so return-to-stock does not brick
The alkane kernel writes NAND with soft-BCH 8b/512 ECC, which the stock Zynq
U-Boot nandboot reader cannot decode: an alkane-side `nandwrite -p` of the boot
slots leaves them unreadable by the stock boot chain ("ECC unrecoverable" loop),
and these boards have no U-Boot prompt, so recovery is SD-card only. This was
the S17 .111 brick of 2026-11-13.

Make the on-board backup/restore preserve the genuine stock OOB (the stock ECC
bytes) so a restore writes the boot slots byte-identical to original stock:

- Backup format v2 ("ALKSTKB2"): carve captures each boot image's data+OOB with
  nanddump and stores the blob in the stock-backup region; the manifest records
  blob offset/length and the on-NAND data length. v1 (data-only) backups are
  detected and refused for restore (they cannot reproduce stock ECC).
- restore_from_onboard: a scratch-block self-check proves `nandwrite --noecc
  --oob` round-trips the stock OOB on this board BEFORE any boot slot is written
  (abort, never brick); each slot is written raw (--noecc --oob) and read back
  WITH OOB; the board reboots only if all three slots are byte-identical to the
  backup.
- restore_to_stock (vendor FILE path): disabled on Zynq - a vendor file carries
  no OOB, so it cannot be restored without recomputing soft-BCH ECC (brick). The
  safe network return-to-stock is restore_from_onboard.

Removes the ECC-recomputing copy_abs. 93 flash-crate tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-18 13:02:46 -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
12 changed files with 1103 additions and 209 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;
+503 -163
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;
@@ -61,12 +60,47 @@ const SLOT_STOCK_BACKUP: u64 = 0x2000000;
/// Where the backup data lives inside the 32 MiB stock-backup region: the first
/// erase block holds the manifest, the images follow, each erase-block aligned.
const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000
const BK_MAGIC: &[u8; 8] = b"ALKSTKB1";
/// v1 (data-only) backup magic. v1 backups cannot be safely restored: they lack
/// the genuine stock OOB, so a restore recomputes the alkane soft-BCH ECC which
/// the stock boot chain cannot read (boot-loop brick).
const BK_MAGIC_V1: &[u8; 8] = b"ALKSTKB1";
/// v2 backup magic. v2 stores each boot image's genuine NAND data *with its OOB*
/// (the stock ECC bytes), so a restore writes the slots back via
/// `nandwrite --noecc --oob` byte-identical to original stock and the stock
/// boot chain reads them. See alkane-zynq-image-bringup.md, 2026-11-13.
const BK_MAGIC_V2: &[u8; 8] = b"ALKSTKB2";
/// Scratch erase block (the last block of the 32 MiB stock-backup region),
/// used to prove `nandwrite --noecc --oob` round-trips on this board's tools
/// before any boot slot is written. Never holds backup images or the manifest.
const BK_SCRATCH: u64 = OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE; // 0x7fe0000
fn round_up(value: u64, to: u64) -> u64 {
value.div_ceil(to) * to
}
/// Append a method-free progress line to the file named by `$ALKANE_OUTCOME_LOG`,
/// if set. This lets a sealed, DSH-driven from-stock install report its own
/// progress (root obtained, carve step, write+verify, reboot) WITHOUT relying on
/// DSH to summarise the run. Every line is written by this code and carries only
/// NAND/flow facts - never the stock-access or root-on-stock method, which lives
/// behind `crate::stock` and never calls this. The file is written by the
/// toolkit process on the workstation, so the operator can read it even though
/// the sealed DSH stdout is quarantined.
fn outcome(msg: &str) {
if let Ok(path) = std::env::var("ALKANE_OUTCOME_LOG") {
if !path.is_empty() {
use std::io::Write as _;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let _ = writeln!(f, "{msg}");
}
}
}
}
// ---------------------------------------------------------------------------
// Root shells
// ---------------------------------------------------------------------------
@@ -131,6 +165,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 +177,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 +197,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 +265,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 +293,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 +340,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 +367,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);
@@ -353,32 +387,221 @@ fn write_abs(
Ok(())
}
/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst`
/// (used when carving the on-board stock backup). `dst` must be erase aligned.
fn copy_abs(
/// NAND page (write) size and OOB size for a partition, from sysfs. Needed to
/// reason about the data+OOB blob geometry and to run the OOB self-check.
fn oob_geometry(sh: &mut dyn Shell, dev: &str) -> Result<(u64, u64), StockError> {
let ws = sh
.exec(&format!("cat /sys/class/mtd/{dev}/writesize 2>/dev/null"))?
.trim()
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{dev}: no writesize in sysfs")))?;
let oob = sh
.exec(&format!("cat /sys/class/mtd/{dev}/oobsize 2>/dev/null"))?
.trim()
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{dev}: no oobsize in sysfs")))?;
if ws == 0 || oob == 0 {
return Err(StockError::Method(format!(
"{dev}: implausible NAND geometry (write {ws}, oob {oob})"
)));
}
Ok((ws, oob))
}
/// Dump `data_len` bytes of NAND at absolute `abs` *with OOB* into a board file,
/// returning (remote_path, blob_len). `data_len` is rounded up to a whole page
/// by the caller so `nanddump` emits only complete pages. The blob is data
/// interleaved with OOB exactly as `nanddump` emits it and `nandwrite --oob`
/// consumes it.
fn dump_with_oob(
sh: &mut dyn Shell,
table: &[Mtd],
src: u64,
dst: u64,
len: u64,
abs: u64,
data_len: u64,
label: &str,
) -> Result<(String, u64), StockError> {
let (dev, rel) = locate(table, abs, data_len)?;
let dev = dev.to_owned();
let remote = format!("/tmp/alk/{label}.oob");
sh.exec("mkdir -p /tmp/alk")?;
sh.exec_long(&format!(
"nanddump --oob -s 0x{rel:x} -l {data_len} /dev/{dev} -f {remote} >/dev/null 2>&1 && echo DUMPED"
))
.and_then(|o| {
if o.contains("DUMPED") {
Ok(())
} else {
Err(StockError::Method(format!(
"{label}: nanddump (with OOB) failed: {o}"
)))
}
})?;
let blob_len = first_token(&sh.exec(&format!("wc -c < {remote}"))?)
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{label}: cannot size the OOB blob")))?;
if blob_len <= data_len {
return Err(StockError::Method(format!(
"{label}: OOB blob {blob_len} B not larger than data {data_len} B - OOB was not \
captured (nanddump omitted OOB?). Refusing: a restore from this backup could not \
reproduce the stock ECC."
)));
}
Ok((remote, blob_len))
}
/// Store a board file verbatim into the backup region at absolute `abs` (opaque
/// bytes written as data with `nandwrite -p`; the backup region's own ECC is
/// irrelevant because the blob is read back from the data area with
/// `--omitoob`). Read-back-verified by md5 against the source file.
fn store_blob(
sh: &mut dyn Shell,
table: &[Mtd],
abs: u64,
remote: &str,
blob_len: u64,
label: &str,
) -> Result<(), StockError> {
let (sdev, srel) = locate(table, src, len)?;
let sdev = sdev.to_owned();
let (ddev, drel) = locate(table, dst, len)?;
let ddev = ddev.to_owned();
let blocks = round_up(len, ERASE) / ERASE;
let tmp = format!("/tmp/alk/{label}.bak");
sh.exec("mkdir -p /tmp/alk")?;
let out = sh.exec_long(&format!(
"nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \
flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \
rm -f {tmp} && echo COPIED"
))?;
if !out.contains("COPIED") {
if !abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label}: backup copy failed: {out}"
"{label}: blob dst 0x{abs:x} not erase-aligned"
)));
}
let (dev, rel) = locate(table, abs, blob_len)?;
let dev = dev.to_owned();
let blocks = round_up(blob_len, ERASE) / ERASE;
sh.exec_long(&format!(
"flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \
nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo STORED"
))
.and_then(|o| {
if o.contains("STORED") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: store blob failed: {o}")))
}
})?;
let want = first_token(&sh.exec(&format!("md5sum {remote}"))?);
let got = first_token(&sh.exec_long(&format!(
"nanddump -s 0x{rel:x} -l {blob_len} --omitoob /dev/{dev} 2>/dev/null | md5sum"
))?);
if want != got {
return Err(StockError::Method(format!(
"{label}: stored blob read-back md5 {got} != {want}"
)));
}
Ok(())
}
/// Prove `nandwrite --noecc --oob` + `nanddump` round-trip the genuine stock OOB
/// on this board, using the throwaway scratch block, BEFORE any boot slot is
/// written. The test vector is the first real page (data+OOB) of the kernel
/// backup blob, so this tests the exact bytes the restore will write. A board
/// whose tools ignore --noecc/--oob (e.g. the busybox applets) or lay the OOB
/// out differently fails here and the restore aborts untouched - the
/// alternative is an ECC-mismatch brick recoverable only by the SD card.
fn scratch_selfcheck(
sh: &mut dyn Shell,
table: &[Mtd],
kernel_blob_abs: u64,
) -> Result<(), StockError> {
let (sdev, srel) = locate(table, BK_SCRATCH, ERASE)?;
let sdev = sdev.to_owned();
let (ws, oob) = oob_geometry(sh, &sdev)?;
let page = ws + oob;
let (bdev, brel) = locate(table, kernel_blob_abs, page)?;
let bdev = bdev.to_owned();
sh.exec("mkdir -p /tmp/alk")?;
// Take the first page+OOB of the kernel blob (data area of the backup
// region), write it raw to scratch, read it back with OOB and compare.
let out = sh.exec_long(&format!(
"nanddump -s 0x{brel:x} -l {page} --omitoob /dev/{bdev} -f /tmp/alk/sc.in >/dev/null 2>&1 && \
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 && \
nandwrite --noecc --oob -s 0x{srel:x} /dev/{sdev} /tmp/alk/sc.in >/dev/null 2>&1 && \
nanddump --noecc --oob -s 0x{srel:x} -l {ws} /dev/{sdev} -f /tmp/alk/sc.out >/dev/null 2>&1 && \
A=$(md5sum < /tmp/alk/sc.in) && B=$(md5sum < /tmp/alk/sc.out) && \
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 ; \
rm -f /tmp/alk/sc.in /tmp/alk/sc.out ; \
[ \"$A\" = \"$B\" ] && echo SCOK || echo SCFAIL"
))?;
if !out.contains("SCOK") {
return Err(StockError::Method(
"OOB self-check failed: `nandwrite --noecc --oob` does not round-trip the stock OOB on \
this board (busybox applet without --noecc/--oob, or a different OOB layout). Refusing \
to write the boot slots: an ECC-mismatch restore would brick the board (SD-card \
recovery only). The alkane image must ship full mtd-utils nandwrite/nanddump."
.into(),
));
}
Ok(())
}
/// Restore one boot slot from its v2 backup entry: retrieve the data+OOB blob
/// from the backup region, write it to the slot with `nandwrite --noecc --oob`
/// (reproducing the exact stock ECC), and read it back WITH OOB to confirm the
/// slot is byte-identical to original stock. Never reboots; the caller reboots
/// only after every slot verifies.
fn restore_slot_raw_oob(
sh: &mut dyn Shell,
table: &[Mtd],
entry: &BackupEntry,
dst_abs: u64,
label: &str,
) -> Result<(), StockError> {
if dst_abs < BOOTBIN_PRESERVE {
return Err(StockError::Method(format!(
"refusing to restore {label} at 0x{dst_abs:x}: inside preserved BOOT.bin"
)));
}
if !dst_abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label} dst 0x{dst_abs:x} not erase-aligned"
)));
}
// Retrieve the opaque blob (data+OOB) from the backup region's data area.
let (bdev, brel) = locate(table, entry.blob_abs, entry.blob_len)?;
let bdev = bdev.to_owned();
let blob = format!("/tmp/alk/{label}.rst");
sh.exec("mkdir -p /tmp/alk")?;
sh.exec_long(&format!(
"nanddump -s 0x{brel:x} -l {blen} --omitoob /dev/{bdev} -f {blob} >/dev/null 2>&1 && echo GOT",
blen = entry.blob_len
))
.and_then(|o| {
if o.contains("GOT") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: blob retrieve failed: {o}")))
}
})?;
// Write raw (data+OOB) to the boot slot.
let (ddev, drel) = locate(table, dst_abs, entry.data_len)?;
let ddev = ddev.to_owned();
let blocks = round_up(entry.data_len, ERASE) / ERASE;
sh.exec_long(&format!(
"flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
nandwrite --noecc --oob -s 0x{drel:x} /dev/{ddev} {blob} >/dev/null 2>&1 && echo WROTE"
))
.and_then(|o| {
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: raw restore write failed: {o}")))
}
})?;
// Read back RAW (no ECC correction) WITH OOB and compare to the blob:
// byte-identical data+stock-ECC. `nanddump` defaults to --omitoob and to
// ECC-correcting; both are wrong here (the slot carries foreign stock ECC
// the alkane soft-BCH engine would "correct" into garbage), so read raw.
let want = first_token(&sh.exec(&format!("md5sum {blob}"))?);
let got = first_token(&sh.exec_long(&format!(
"nanddump --noecc --oob -s 0x{drel:x} -l {dlen} /dev/{ddev} 2>/dev/null | md5sum",
dlen = entry.data_len
))?);
sh.exec(&format!("rm -f {blob}"))?;
if want != got {
return Err(StockError::Method(format!(
"{label}: restored slot read-back md5 {got} != backup {want} (data+OOB mismatch); \
NOT rebooting"
)));
}
Ok(())
@@ -431,34 +654,37 @@ fn first_token(s: &str) -> String {
// On-board stock backup manifest
// ---------------------------------------------------------------------------
#[derive(Clone, Debug)]
/// One backed-up boot image: where its genuine data+OOB blob lives in the
/// stock-backup region (`blob_abs`), the blob's byte length (`blob_len`, data
/// interleaved with OOB as `nanddump` emits it), and the original on-NAND data
/// length (`data_len`, OOB excluded) that the boot slot occupies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct BackupEntry {
blob_abs: u64,
blob_len: u64,
data_len: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct BackupManifest {
kernel_abs: u64,
kernel_len: u64,
dtb_abs: u64,
dtb_len: u64,
rootfs_abs: u64,
rootfs_len: u64,
kernel: BackupEntry,
dtb: BackupEntry,
rootfs: BackupEntry,
}
impl BackupManifest {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::with_capacity(64);
v.extend_from_slice(BK_MAGIC);
for n in [
self.kernel_abs,
self.kernel_len,
self.dtb_abs,
self.dtb_len,
self.rootfs_abs,
self.rootfs_len,
] {
v.extend_from_slice(&n.to_be_bytes());
let mut v = Vec::with_capacity(8 + 9 * 8);
v.extend_from_slice(BK_MAGIC_V2);
for e in [self.kernel, self.dtb, self.rootfs] {
for n in [e.blob_abs, e.blob_len, e.data_len] {
v.extend_from_slice(&n.to_be_bytes());
}
}
v
}
fn decode(b: &[u8]) -> Option<Self> {
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
if b.len() < 8 + 9 * 8 || &b[..8] != BK_MAGIC_V2 {
return None;
}
let g = |i: usize| {
@@ -466,70 +692,131 @@ impl BackupManifest {
a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]);
u64::from_be_bytes(a)
};
let e = |base: usize| BackupEntry {
blob_abs: g(base),
blob_len: g(base + 1),
data_len: g(base + 2),
};
Some(BackupManifest {
kernel_abs: g(0),
kernel_len: g(1),
dtb_abs: g(2),
dtb_len: g(3),
rootfs_abs: g(4),
rootfs_len: g(5),
kernel: e(0),
dtb: e(3),
rootfs: e(6),
})
}
/// A v1 (data-only) backup is present but NOT safely restorable (no stock
/// OOB captured). Detected so restore can refuse with a clear message.
fn is_v1(b: &[u8]) -> bool {
b.len() >= 8 && &b[..8] == BK_MAGIC_V1
}
}
/// Capture one genuine-stock image (data+OOB) into the backup region at
/// `dst_abs`, checking it stays below the scratch block, and return its entry.
fn capture_entry(
sh: &mut dyn Shell,
table: &[Mtd],
src_abs: u64,
data_len: u64,
dst_abs: u64,
label: &str,
) -> Result<BackupEntry, StockError> {
let (remote, blob_len) = dump_with_oob(sh, table, src_abs, data_len, label)?;
if dst_abs + round_up(blob_len, ERASE) > BK_SCRATCH {
return Err(StockError::Method(
"stock backup (with OOB) does not fit in the backup region below the scratch block"
.into(),
));
}
store_blob(sh, table, dst_abs, &remote, blob_len, label)?;
sh.exec(&format!("rm -f {remote}"))?;
Ok(BackupEntry {
blob_abs: dst_abs,
blob_len,
data_len,
})
}
/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the
/// stock-backup region, with a manifest in its first block, so the board can be
/// returned to its own factory stock later with no vendor file. Called on the
/// stock side during a from-stock install, before the boot slots are overwritten.
/// stock-backup region *with their OOB* (a v2 backup), with a manifest in its
/// first block, so the board can be returned to its own factory stock later -
/// over the network, byte-identical to stock ECC - with no vendor file. Called
/// on the stock side during a from-stock install, before the boot slots are
/// overwritten. Each image's data+OOB blob is captured and stored sequentially
/// so only one lives in `/tmp` at a time.
fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, StockError> {
// Size the genuine images from their on-NAND headers (uImage data size at
// header offset 12; fdt totalsize at offset 4).
let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64;
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 {
// Genuine image sizes from their on-NAND headers (uImage data size at header
// offset 12 plus the 64-byte header; fdt totalsize at offset 4), rounded up
// to a whole NAND page so nanddump captures only complete pages.
let (kdev, _) = locate(table, OFF_KERNEL, 64)?;
let (ws, oob) = oob_geometry(sh, kdev)?;
outcome(&format!("carve: geometry writesize={ws} oobsize={oob} (dev {kdev})"));
let pr = |n: u64| round_up(n, ws);
let kernel_data = pr(64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64);
let dtb_data = pr(read_header_u32_be(sh, table, OFF_DTB, 4)? as u64);
let rootfs_data = pr(64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64);
if !(ws..=SLOT_KERNEL).contains(&kernel_data) || !(ws..=SLOT_ROOTFS).contains(&rootfs_data) {
return Err(StockError::Method(format!(
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
"stock image sizes implausible (kernel {kernel_data}, rootfs {rootfs_data}); \
refusing to back up"
)));
}
let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block
let d_dst = k_dst + round_up(kernel_len, ERASE);
let r_dst = d_dst + round_up(dtb_len, ERASE);
if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP {
return Err(StockError::Method(
"stock backup does not fit in the 32 MiB backup region".into(),
));
}
copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?;
copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?;
copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?;
let kernel = capture_entry(sh, table, OFF_KERNEL, kernel_data, k_dst, "stock-kernel")?;
outcome(&format!(
"carve: kernel data={} blob={} (OOB {})",
kernel.data_len,
kernel.blob_len,
if kernel.blob_len > kernel.data_len {
"captured"
} else {
"MISSING"
}
));
let d_dst = k_dst + round_up(kernel.blob_len, ERASE);
let dtb = capture_entry(sh, table, OFF_DTB, dtb_data, d_dst, "stock-dtb")?;
outcome(&format!(
"carve: dtb data={} blob={}",
dtb.data_len, dtb.blob_len
));
let r_dst = d_dst + round_up(dtb.blob_len, ERASE);
let rootfs = capture_entry(sh, table, OFF_ROOTFS, rootfs_data, r_dst, "stock-rootfs")?;
outcome(&format!(
"carve: rootfs data={} blob={}",
rootfs.data_len, rootfs.blob_len
));
let manifest = BackupManifest {
kernel_abs: k_dst,
kernel_len,
dtb_abs: d_dst,
dtb_len,
rootfs_abs: r_dst,
rootfs_len,
kernel,
dtb,
rootfs,
};
write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?;
write_abs(
sh,
table,
BK_MANIFEST,
&manifest.encode(),
"stock-backup-manifest",
)?;
Ok(manifest)
}
/// Read and validate the on-board backup manifest, if present.
fn read_backup_manifest(
sh: &mut dyn Shell,
table: &[Mtd],
) -> Result<Option<BackupManifest>, StockError> {
let (dev, rel) = match locate(table, BK_MANIFEST, 64) {
/// Read the manifest block header bytes (enough for a v2 manifest: 8 magic +
/// 9*8 fields = 80 B; 128 read for slack). `None` if the region is not mapped.
fn read_manifest_bytes(sh: &mut dyn Shell, table: &[Mtd]) -> Result<Option<Vec<u8>>, StockError> {
let (dev, rel) = match locate(table, BK_MANIFEST, 128) {
Ok(v) => v,
Err(_) => return Ok(None), // region not mapped -> treat as absent
};
let dev = dev.to_owned();
// Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse.
let bytes = read_small(sh, &dev, rel, 64)?;
Ok(BackupManifest::decode(&bytes))
// Pull the manifest off NAND via `od -v -x` (busybox-safe) and parse.
Ok(Some(read_small(sh, &dev, rel, 128)?))
}
/// Read and validate the on-board v2 backup manifest, if present and complete.
fn read_backup_manifest(
sh: &mut dyn Shell,
table: &[Mtd],
) -> Result<Option<BackupManifest>, StockError> {
Ok(read_manifest_bytes(sh, table)?.and_then(|b| BackupManifest::decode(&b)))
}
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
@@ -569,11 +856,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 {
@@ -618,68 +901,82 @@ pub fn install_from_stock(
rootfs_cpio_gz: &[u8],
password: Option<&str>,
) -> Result<(), StockError> {
outcome(&format!(
"install_from_stock: begin host={host} kernel={} dtb={} rootfs={} (zImage/fdt/cpio-gz)",
kernel_zimage.len(),
dtb.len(),
rootfs_cpio_gz.len()
));
let mut sh = StockShell {
host: host.to_owned(),
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()));
let r = install_from_stock_inner(&mut sh, kernel_zimage, dtb, rootfs_cpio_gz);
match &r {
Ok(()) => outcome("install_from_stock: COMPLETE (boot slots written+verified, rebooting)"),
Err(e) => outcome(&format!("install_from_stock: ERROR {e}")),
}
let table = read_mtd_table(&mut sh)?;
// Carve the genuine-stock backup from the live stock NAND before any write.
carve_backup(&mut sh, &table)?;
r
}
fn install_from_stock_inner(
sh: &mut dyn Shell,
kernel_zimage: &[u8],
dtb: &[u8],
rootfs_cpio_gz: &[u8],
) -> Result<(), StockError> {
if first_token(&sh.exec("id -u")?) != "0" {
return Err(StockError::Auth(
"did not obtain root on the stock board".into(),
));
}
outcome("root: ok");
let table = read_mtd_table(sh)?;
outcome(&format!("mtd-table: {} partitions", table.len()));
// Carve the genuine-stock backup (with OOB) from the live stock NAND before
// any write, so a safe return-to-stock is possible later.
outcome("carve: begin (v2, OOB-preserving)");
carve_backup(sh, &table)?;
outcome("carve: ok (v2 stock backup written)");
let img = BootImages {
kernel_uimage: uimage::wrap(Kind::Kernel, kernel_zimage, 0, "alkane-kernel"),
dtb: dtb.to_vec(),
rootfs_uimage: uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, 0, "alkane-rootfs"),
};
write_boot_slots(&mut sh, &table, &img)?;
reboot(&mut sh);
outcome("boot-slots: writing rootfs, dtb, kernel");
write_boot_slots(sh, &table, &img)?;
outcome("boot-slots: written+verified");
reboot(sh);
Ok(())
}
/// Return an alkane board to genuine stock by writing the vendor images back to
/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the
/// vendor package); if `None`, the stock dtb saved in the on-board backup is
/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is.
/// Return an alkane board to genuine stock from a vendor firmware FILE.
///
/// This is refused on the Zynq-7010: a vendor file carries image data only, with
/// no OOB, so writing it from alkane userspace recomputes the kernel's soft-BCH
/// ECC, which the stock boot chain cannot read -> boot-loop brick recoverable
/// only by the SD card. The safe network return-to-stock is
/// [`restore_from_onboard`], which replays the genuine stock data+OOB captured
/// in the on-board v2 backup. (Once the own stage-2 U-Boot lands, a soft-BCH
/// reader makes vendor-file restore viable; until then it is blocked.)
pub fn restore_to_stock(
host: &str,
kernel_uimage: &[u8],
rootfs_uimage: &[u8],
dtb: Option<&[u8]>,
_kernel_uimage: &[u8],
_rootfs_uimage: &[u8],
_dtb: Option<&[u8]>,
password: Option<&str>,
) -> Result<(), StockError> {
let mut sh = AlkaneShell::connect(host, password)?;
if !shell_is_zynq(&mut sh) {
return Err(StockError::NotApplicable);
}
let table = read_mtd_table(&mut sh)?;
if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL {
return Err(StockError::Method("vendor image over slot ceiling".into()));
}
// rootfs, dtb, kernel order (same safety ordering as install).
write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?;
match dtb {
Some(d) => {
if d.len() as u64 > SLOT_DTB {
return Err(StockError::Method("dtb over slot ceiling".into()));
}
write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?;
}
None => {
// No vendor dtb (an OTA package omits it): restore the genuine
// per-board dtb from the on-board backup by copying within NAND.
let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| {
StockError::Method(
"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")?;
}
}
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
reboot(&mut sh);
Ok(())
Err(StockError::Method(
"Zynq-7010 vendor-file restore-to-stock is disabled: a vendor file has no OOB, so an \
alkane-side write recomputes soft-BCH ECC that the stock U-Boot cannot read (boot-loop \
brick; SD-card recovery only). Use restore-from-onboard, which replays the genuine stock \
data+OOB from the on-board backup."
.into(),
))
}
/// Whether the board holds a complete, restorable on-board stock backup.
@@ -700,17 +997,34 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
return Err(StockError::NotApplicable);
}
let table = read_mtd_table(&mut sh)?;
let manifest = read_backup_manifest(&mut sh, &table)?
let raw = read_manifest_bytes(&mut sh, &table)?.ok_or_else(|| {
StockError::Method("no on-board stock backup (backup region not mapped)".into())
})?;
if BackupManifest::is_v1(&raw) {
return Err(StockError::Method(
"on-board backup is the old data-only (v1) format with no stock OOB; it cannot be \
restored safely (a plain write recomputes alkane soft-BCH ECC and bricks the stock \
boot chain). Re-install from stock to capture a v2 backup, or use the SD recovery \
card."
.into(),
));
}
let manifest = BackupManifest::decode(&raw)
.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")?;
// Prove the raw-OOB write path round-trips the stock OOB on this board
// before touching a boot slot (abort, do not brick).
scratch_selfcheck(&mut sh, &table, manifest.kernel.blob_abs)?;
// rootfs, dtb, kernel order (an interrupted run never leaves a new rootfs
// under an old kernel). Each write is read-back-verified WITH OOB; a
// mismatch returns an error WITHOUT rebooting, leaving the running alkane in
// place rather than booting a corrupt slot.
restore_slot_raw_oob(&mut sh, &table, &manifest.rootfs, OFF_ROOTFS, "rootfs")?;
restore_slot_raw_oob(&mut sh, &table, &manifest.dtb, OFF_DTB, "dtb")?;
restore_slot_raw_oob(&mut sh, &table, &manifest.kernel, OFF_KERNEL, "kernel")?;
reboot(&mut sh);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -732,27 +1046,53 @@ mod tests {
}
#[test]
fn manifest_roundtrips() {
fn manifest_v2_roundtrips_and_rejects_v1() {
let e = |a, b, c| BackupEntry {
blob_abs: a,
blob_len: b,
data_len: c,
};
let m = BackupManifest {
kernel_abs: 0x6020000,
kernel_len: 4006832,
dtb_abs: 0x6420000,
dtb_len: 7650,
rootfs_abs: 0x6440000,
rootfs_len: 26620582,
kernel: e(0x6020000, 4133808, 4063232),
dtb: e(0x6440000, 8320, 8192),
rootfs: e(0x6460000, 27336704, 26624000),
};
let enc = m.encode();
let dec = BackupManifest::decode(&enc).unwrap();
assert_eq!(dec.kernel_abs, m.kernel_abs);
assert_eq!(dec.rootfs_len, m.rootfs_len);
assert_eq!(&enc[..8], BK_MAGIC_V2);
assert_eq!(enc.len(), 8 + 9 * 8);
assert_eq!(BackupManifest::decode(&enc).unwrap(), m);
// A v1 (data-only) header is detected and NOT decoded as a v2 manifest.
let mut v1 = BK_MAGIC_V1.to_vec();
v1.extend_from_slice(&[0u8; 72]);
assert!(BackupManifest::is_v1(&v1));
assert!(BackupManifest::decode(&v1).is_none());
assert!(!BackupManifest::is_v1(&enc));
assert!(BackupManifest::decode(b"nope").is_none());
}
#[test]
fn scratch_block_is_inside_the_backup_region_and_aligned() {
assert!(BK_SCRATCH.is_multiple_of(ERASE));
assert!(BK_SCRATCH >= OFF_STOCK_BACKUP + ERASE); // above manifest block
assert_eq!(BK_SCRATCH, OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE);
assert!(BK_SCRATCH + ERASE <= OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP);
}
#[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));
+332
View File
@@ -0,0 +1,332 @@
//! Headless bench automation (`ALKANE_BENCH_SEQUENCE`): drive the GUI's real
//! install/restore operation layer (`stock_ops`) through the A113D network-only
//! install <-> flag-restore cycle, with no window. This exercises the GUI
//! operator flow end-to-end against real hardware, for bench proofs, without the
//! wx event loop (the worker functions stream progress over a channel, exactly
//! as the UI drains them).
//!
//! Spec: `ALKANE_BENCH_SEQUENCE="<host> <local.afw> [iterations]"`.
//! The alkane root credential is read from the saved SSH credentials file.
//!
//! On the A113D, "restore to stock" is the one-byte flag flip (the install
//! overwrites no stock partition), so the cycle is: install (stock -> alkane) ->
//! verify alkane -> restore (flag flip -> stock) -> verify stock.
use std::io::Read;
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, Instant};
use crate::credentials;
use crate::stock_ops::{self, AfwSource, StockHandle, StockMsg};
/// Drain a `StockHandle` to completion, printing progress; returns true iff
/// every board reported ok and at least one `Result` arrived.
fn drive(label: &str, handle: StockHandle) -> bool {
let mut ok = true;
let mut saw = false;
loop {
match handle.rx.recv() {
Ok(StockMsg::Started) => println!(" [{label}] started"),
Ok(StockMsg::Progress(s)) => println!(" [{label}] {s}"),
Ok(StockMsg::Result { ip, ok: r, detail }) => {
saw = true;
ok = ok && r;
println!(
" [{label}] {ip}: {} - {detail}",
if r { "OK" } else { "FAIL" }
);
}
Ok(StockMsg::Done) => break,
Err(_) => {
println!(" [{label}] channel closed early");
ok = false;
break;
}
}
}
ok && saw
}
/// Read the SSH identification banner (no auth), e.g. `SSH-2.0-dropbear_2026.93`.
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()?;
let mut buf = [0u8; 256];
let n = stream.read(&mut buf).ok()?;
if n == 0 {
return None;
}
Some(
String::from_utf8_lossy(&buf[..n])
.lines()
.next()
.unwrap_or("")
.trim()
.to_string(),
)
}
/// HTTP server header probe (stock serves lighttpd / an antMiner realm).
fn http_is_stock(host: &str) -> Option<bool> {
let out = Command::new("curl")
.args([
"-sS",
"-m",
"6",
"-o",
"/dev/null",
"-D",
"-",
&format!("http://{host}/"),
])
.output()
.ok()?;
let h = String::from_utf8_lossy(&out.stdout).to_lowercase();
if h.is_empty() {
None
} else if h.contains("lighttpd") || h.contains("antminer configuration") {
Some(true)
} else {
Some(false)
}
}
/// Classify the board: `Some(true)` = looks like genuine stock, `Some(false)` =
/// looks like alkane, `None` = no decisive answer (e.g. mid-reboot).
///
/// Primary signal is the SSH banner: stock A113D is `dropbear_2018.76`; alkane
/// ships a much newer dropbear. HTTP (lighttpd) is a stock fallback.
fn classify(host: &str) -> (String, Option<bool>) {
let banner = ssh_banner(host);
if let Some(b) = &banner {
let lb = b.to_lowercase();
if lb.contains("dropbear_2018") || lb.contains("dropbear_2019") {
return (format!("ssh \"{b}\" -> stock"), Some(true));
}
if lb.contains("dropbear") || lb.contains("openssh") {
return (format!("ssh \"{b}\" -> alkane"), Some(false));
}
}
match http_is_stock(host) {
Some(true) => ("http lighttpd/antMiner -> stock".to_string(), Some(true)),
Some(false) => ("http non-stock -> alkane".to_string(), Some(false)),
None => (
banner
.map(|b| format!("ssh \"{b}\" (unclassified), no http"))
.unwrap_or_else(|| "no ssh, no http (mid-reboot?)".to_string()),
None,
),
}
}
/// The MAC (lladdr) the kernel has cached for `host` (pings first to populate).
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 s = String::from_utf8_lossy(&out.stdout);
let mut it = s.split_whitespace();
while let Some(t) = it.next() {
if t == "lladdr" {
return it.next().map(|m| m.to_lowercase());
}
}
None
}
/// Populate the neighbour table by parallel-pinging the /24 of `sample` (a bench
/// board can take a different DHCP lease across a reboot, so we must re-find it).
fn sweep_subnet(sample: &str) {
let base = match sample.rsplit_once('.') {
Some((net, _)) => net.to_string(),
None => return,
};
let mut kids = Vec::new();
for h in 2..=254 {
if let Ok(c) = Command::new("ping")
.args(["-c", "1", "-W", "1", &format!("{base}.{h}")])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
kids.push(c);
}
}
for mut c in kids {
let _ = c.wait();
}
}
/// Current IPv4 for `mac` from the neighbour table, if present.
fn ip_for_mac(mac: &str) -> Option<String> {
let out = Command::new("ip").args(["neigh"]).output().ok()?;
let s = String::from_utf8_lossy(&out.stdout);
let mac = mac.to_lowercase();
for line in s.lines() {
if line.to_lowercase().contains(&mac) {
if let Some(ip) = line.split_whitespace().next() {
if ip.contains('.') {
return Some(ip.to_string());
}
}
}
}
None
}
/// 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) {
let deadline = Instant::now() + timeout;
let mut ip = fallback.to_string();
let mut swept = Instant::now() - Duration::from_secs(60);
loop {
// Re-locate by MAC; sweep the subnet at most every ~25s to catch a new lease.
if let Some(m) = mac {
if ip_for_mac(m).is_none() && swept.elapsed() >= Duration::from_secs(25) {
sweep_subnet(fallback);
swept = Instant::now();
}
if let Some(found) = ip_for_mac(m) {
ip = found;
}
}
let (desc, is_stock) = classify(&ip);
let line = format!("[{ip}] {desc}");
if is_stock == Some(want_stock) {
return (ip, line, true);
}
if Instant::now() >= deadline {
return (ip, line, false);
}
std::thread::sleep(Duration::from_secs(5));
}
}
pub fn run(spec: &str) -> i32 {
let mut it = spec.split_whitespace();
let host = match it.next() {
Some(h) => h.to_string(),
None => {
eprintln!("ALKANE_BENCH_SEQUENCE=\"<host> <local.afw> [iterations]\"");
return 2;
}
};
let afw = match it.next() {
Some(a) => PathBuf::from(a),
None => {
eprintln!("missing local .afw path");
return 2;
}
};
let iterations: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1);
let board = "a113d".to_string();
// Install reaches STOCK via the compiled-in from-stock method; pass the saved
// board SSH credential through to it.
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
// The flag-restore reaches the running ALKANE board over SSH as `root` - a
// DIFFERENT credential from the stock login. Alkane bench images bake
// root/alkane; allow an override via ALKANE_ROOT_PASSWORD.
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
.ok()
.or_else(|| Some("alkane".to_string()));
println!("== A113D headless GUI bench sequence (network-only install <-> flag-restore) ==");
println!(
"host={host} afw={} board={board} iterations={iterations} stock_cred={} alkane_cred={}",
afw.display(),
if stock_password.is_some() { "loaded" } else { "none" },
if alkane_password.is_some() { "set" } else { "none" }
);
if !afw.exists() {
eprintln!("afw not found: {}", afw.display());
return 2;
}
// Resolve the board's MAC now (on stock) so we can re-find it after each
// reboot even if its DHCP lease changes under alkane.
let mac = mac_of(&host);
println!(
"board MAC: {}",
mac.as_deref()
.unwrap_or("unknown (will use the fixed host)")
);
let boot_timeout = Duration::from_secs(300);
let mut all_ok = true;
for i in 1..=iterations {
println!("\n-- iteration {i}/{iterations} --");
// 1. install (stock -> alkane) through the GUI operation layer
println!("[1/4] install: stock -> alkane");
let h = stock_ops::start_install(
vec![host.clone()],
board.clone(),
AfwSource::Local(afw.clone()),
true, // allow unsigned (bench image)
stock_password.clone(),
false, // not an in-place update
);
if !drive("install", h) {
all_ok = false;
println!("[1/4] install FAILED; aborting");
break;
}
// 2. verify alkane is live (board reboots into alkane)
println!(
"[2/4] verify alkane (awaiting reboot, up to {}s)...",
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)" }
);
all_ok = all_ok && ok;
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
println!("[3/4] restore: alkane -> stock (flag flip) at {alkane_ip}");
let h = stock_ops::start_restore_flag(vec![alkane_ip.clone()], alkane_password.clone());
if !drive("restore", h) {
all_ok = false;
println!("[3/4] restore FAILED");
}
// 4. verify stock is back
println!(
"[4/4] verify stock (awaiting reboot, up to {}s)...",
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)" }
);
all_ok = all_ok && ok;
}
println!(
"\n== BENCH RESULT: {} ==",
if all_ok { "PASS" } else { "FAIL" }
);
if all_ok {
0
} else {
1
}
}
+16 -3
View File
@@ -8,6 +8,7 @@
mod access_probe;
mod alkane_detect;
mod askpass;
mod bench_sequence;
mod bug_report;
mod credentials;
mod export;
@@ -41,6 +42,13 @@ fn main() {
std::process::exit(run_selftest());
}
// Headless bench automation: drive the real install/restore operation layer
// (stock_ops) through the A113D network-only install <-> flag-restore cycle
// against real hardware, with no window. See bench_sequence.rs.
if let Some(spec) = std::env::var_os("ALKANE_BENCH_SEQUENCE") {
std::process::exit(bench_sequence::run(&spec.to_string_lossy()));
}
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
// :4028 token check and the Antminer digest check can be verified directly.
@@ -123,9 +131,14 @@ fn run_selftest() -> i32 {
/// True when the process runs one of the headless check modes instead of the GUI.
fn headless_mode() -> bool {
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
.iter()
.any(|v| std::env::var_os(v).is_some())
[
"ALKANE_SELFTEST",
"ALKANE_ACCESS_PROBE",
"ALKANE_LOG_SCAN",
"ALKANE_BENCH_SEQUENCE",
]
.iter()
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
+69 -2
View File
@@ -24,8 +24,13 @@ use crate::scan::fake_scan_enabled;
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
/// `SUPPORTED`). Only these are offered as install targets.
pub const SUPPORTED_BOARDS: &[(&str, &str)] =
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
),
];
/// The default install board when the user has not chosen another.
pub const DEFAULT_BOARD: &str = "zynq-7010";
@@ -408,3 +413,65 @@ pub fn start_restore_onboard(ips: Vec<String>, password: Option<String>) -> Stoc
}
StockHandle { rx, cancel }
}
/// Restore the given alkane A113D boards to genuine Bitmain stock, over the
/// network, by clearing the one-byte boot flag in-band from the running alkane
/// OS. The A113D install overwrites no stock partition, so this flag flip is the
/// complete restore: clear `ALAN`, reboot, and stock boots via `storeboot` from
/// the untouched `boot` MTD. No vendor firmware file or on-board backup needed.
/// `password`, if set, is the board's alkane root credential.
pub fn start_restore_flag(ips: Vec<String>, password: Option<String>) -> StockHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
if fake_scan_enabled() {
let _ = tx.send(StockMsg::Started);
for ip in ips {
let _ = tx.send(StockMsg::Result {
ip,
ok: true,
detail: "restored to stock (flag flip, demo)".into(),
});
}
let _ = tx.send(StockMsg::Done);
return StockHandle { rx, cancel };
}
let tc = cancel.clone();
let err_tx = tx.clone();
let spawned = std::thread::Builder::new()
.name("restore-flag".into())
.spawn(move || {
let _ = tx.send(StockMsg::Started);
for ip in ips {
if tc.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(StockMsg::Progress(format!(
"restoring {ip} to stock (clearing the alkane boot flag)..."
)));
let (ok, detail) = match stock::restore_aml_flag(&ip, password.as_deref()) {
Ok(()) => (
true,
"restored to stock (flag cleared, rebooting; verify over the network)"
.to_string(),
),
Err(e) => (false, format!("restore failed: {e}")),
};
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
return;
}
}
let _ = tx.send(StockMsg::Done);
});
if spawned.is_err() {
let _ = err_tx.send(StockMsg::Result {
ip: String::new(),
ok: false,
detail: "could not start the restore worker thread".into(),
});
let _ = err_tx.send(StockMsg::Done);
}
StockHandle { rx, cancel }
}
+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]}"